SPB Git

Repository Public

TrackingView.swift 12.9 KB 238 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr SMS Gateway9// File             : ios/MacLustrSMS/UI/TrackingView.swift10// Description      : Suivi d'un envoi en direct : frise des états, explication11//                    honnête de chaque état, annulation, renvoi comme nouveau12//                    message.13// Module           : ios14// Repository       : https://git.spboucher.ai/maclustr-sms15// Project Website  : https://sms.spboucher.ai16// Created          : 2026-11-3017// Last Modified    : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: admin@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import SwiftUI9293struct TrackingView: View {94    let messageId: String95    var initial: SMSMessage? = nil96    @Environment(AppModel.self) private var model97    @Environment(\.dismiss) private var dismiss98    @State private var message: SMSMessage?99    @State private var error: String?100    @State private var working = false101    @State private var submittedSeenAt: Date?102    @Environment(\.scenePhase) private var scenePhase103104    var body: some View {105        Screen {106            if let m = message {107                summary(m)108                if m.isOutbound { timeline(m) }109                if m.status == .unknown { Banner(text: MessageStatus.unknown.explanation, tone: .warn) }110                if let e = m.error { Banner(text: "Code d'erreur : \(e.code)\(e.detail.map { " — \($0)" } ?? "")", tone: .bad, symbol: "xmark.octagon") }111                content(m)112                if let error { Banner(text: error, tone: .bad, symbol: "exclamationmark.circle") }113                actions(m)114            } else if let error { Banner(text: error, tone: .bad) } else { ProgressView().frame(maxWidth: .infinity).padding(40) }115        }116        .navigationTitle("Suivi").navigationBarTitleDisplayMode(.inline)117        // Le suivi recharge le message lui-même (cadence de PollSchedule) : il ne dépend pas du flux temps réel, qui ne fait qu'accélérer.118        .task(id: messageId) { await pollLoop() }119        .onChange(of: model.messagesRevision) { _, _ in Task { await load() } }120        .onChange(of: scenePhase) { _, p in if p == .active { Task { await pollLoop() } } }121        .refreshable { await load() }122        .onAppear { if message == nil { message = initial; if initial?.status == .submitted { submittedSeenAt = initial?.submittedAt ?? .now } } }123    }124125    private func summary(_ m: SMSMessage) -> some View {126        Card {127            VStack(alignment: .leading, spacing: 8) {128                HStack(spacing: 10) {129                    Image(systemName: symbol(m.status)).font(.title).foregroundStyle(Theme.tone(m.status.tone)).contentTransition(.symbolEffect(.replace))130                    VStack(alignment: .leading, spacing: 1) {131                        Text(SendTimeline.headline(m.status)).font(.title3.weight(.semibold)).foregroundStyle(Theme.text).accessibilityIdentifier("trackingHeadline")132                        Text(m.status.label).font(.subheadline).foregroundStyle(Theme.tone(m.status.tone)).accessibilityIdentifier("trackingStatus")133                    }134                    Spacer()135                    if !m.status.isFinal && m.status != .submitted { ProgressView().accessibilityIdentifier("trackingSpinner") }136                }137                Text(m.status.explanation).font(.footnote).foregroundStyle(Theme.muted).fixedSize(horizontal: false, vertical: true)138                Divider().overlay(Theme.line)139                HStack { Text(m.isOutbound ? "À" : "De").foregroundStyle(Theme.muted); Text(PhoneNumber.pretty(m.peer)).monospacedDigit().foregroundStyle(Theme.text); Spacer(); Text(m.createdAt.shortStamp).foregroundStyle(Theme.faint) }.font(.subheadline)140                if let s = m.simId { Text("Ligne \(s)\(m.from.map { " · \(PhoneNumber.pretty($0))" } ?? "") · \(m.segments ?? 1) segment\((m.segments ?? 1) > 1 ? "s" : "")").font(.caption.monospacedDigit()).foregroundStyle(Theme.faint) }141            }142        }143    }144145    private func timeline(_ m: SMSMessage) -> some View {146        let steps = SendTimeline.steps(status: m.status, events: m.events ?? [])147        // L'horloge fait passer « accusé en attente » à « non reçu » après 30 s, sans action de l'utilisateur.148        return TimelineView(.periodic(from: .now, by: 5)) { ctx in timelineCard(m, steps: steps, now: ctx.date) }149    }150    private func timelineCard(_ m: SMSMessage, steps: [TimelineStep], now: Date) -> some View {151        let receipt = DeliveryReceipt.state(status: m.status, submittedAt: submittedSeenAt ?? m.submittedAt, deliveredAt: m.deliveredAt, now: now)152        return Card {153            VStack(alignment: .leading, spacing: 0) {154                ForEach(Array(steps.enumerated()), id: \.element.id) { i, s in155                    HStack(alignment: .top, spacing: 12) {156                        VStack(spacing: 0) {157                            ZStack {158                                Circle().fill(color(s).opacity(s.state == .pending || s.state == .skipped ? 0 : 1)).frame(width: 14, height: 14)159                                Circle().strokeBorder(color(s), lineWidth: 2).frame(width: 14, height: 14)160                                if s.state == .done { Image(systemName: "checkmark").font(.system(size: 7, weight: .black)).foregroundStyle(Theme.panel) }161                            }162                            if i < steps.count - 1 { Rectangle().fill(s.state == .done ? Theme.accent.opacity(0.6) : Theme.line).frame(width: 2).frame(minHeight: 22) }163                        }164                        HStack(alignment: .firstTextBaseline) {165                            // L'étape « Livré » ne dit jamais « livré » sans rapport : elle décrit l'accusé (en attente, non reçu, reçu).166                            Text(s.status == .delivered && receipt != .notApplicable ? receipt.label : s.status.label)167                                .font(.subheadline.weight(s.state == .current || s.state == .problem ? .semibold : .regular))168                                .foregroundStyle(s.state == .pending || s.state == .skipped ? Theme.faint : Theme.text)169                                .fixedSize(horizontal: false, vertical: true)170                            Spacer()171                            if let at = s.at { Text(at.shortStamp).font(.caption.monospacedDigit()).foregroundStyle(Theme.faint) }172                        }173                        .padding(.bottom, i < steps.count - 1 ? 12 : 0)174                    }175                    .accessibilityElement(children: .combine)176                    .accessibilityIdentifier(s.status == .delivered ? "receiptLine" : "step-\(s.status.rawValue)")177                }178            }179        }180        // Un identifiant posé sur un conteneur masque ceux de ses enfants : on garde d'abord les enfants accessibles.181        .accessibilityElement(children: .contain)182        .accessibilityIdentifier("timeline")183    }184    private func color(_ s: TimelineStep) -> Color {185        switch s.state { case .done: Theme.accent; case .current: Theme.info; case .problem: Theme.tone(s.status.tone); case .pending, .skipped: Theme.line }186    }187    private func symbol(_ s: MessageStatus) -> String {188        switch s {189        case .delivered, .submitted: "checkmark.circle.fill"; case .failed, .expired: "xmark.octagon.fill"; case .unknown: "questionmark.circle.fill"190        case .cancelled: "minus.circle.fill"; case .received: "arrow.down.circle.fill"; default: "clock.fill"191        }192    }193194    private func content(_ m: SMSMessage) -> some View {195        VStack(alignment: .leading, spacing: 8) {196            SectionLabel("Message")197            Bubble(text: m.displayText, outgoing: m.isOutbound)198        }199    }200    @ViewBuilder private func actions(_ m: SMSMessage) -> some View {201        if m.status.isCancellable {202            Button("Annuler ce message") { Task { await cancel() } }.buttonStyle(QuietButtonStyle(tone: Theme.bad)).disabled(working).accessibilityIdentifier("cancelButton")203        }204        if m.isOutbound, m.sensitive != true, let t = m.text, let to = m.to {205            Button { model.pendingDraft = ComposeDraft(to: to, text: t, simId: nil); model.selectedTab = 0; dismiss() } label: { Label("Reprendre comme nouveau message", systemImage: "arrow.uturn.forward") }206                .buttonStyle(QuietButtonStyle())207        }208        Text(m.id).font(.caption2.monospaced()).foregroundStyle(Theme.faint).textSelection(.enabled).frame(maxWidth: .infinity)209    }210211    /// Recharge immédiatement, puis selon PollSchedule, jusqu'à une issue stable.212    private func pollLoop() async {213        let start = Date.now214        while !Task.isCancelled {215            await load()216            guard let m = message else { try? await Task.sleep(for: .seconds(2)); if Date.now.timeIntervalSince(start) > 30 { return }; continue }217            guard let delay = PollSchedule.nextDelay(status: m.status, elapsed: Date.now.timeIntervalSince(start), sinceSubmitted: submittedSeenAt.map { Date.now.timeIntervalSince($0) }) else { return }218            try? await Task.sleep(for: .seconds(delay))219        }220    }221    private func load() async {222        do {223            let m = try await model.api.message(messageId)224            if m.status == .submitted, submittedSeenAt == nil { submittedSeenAt = .now }225            if let old = message, old.status != m.status {226                let g = UINotificationFeedbackGenerator()227                switch m.status { case .submitted, .delivered: g.notificationOccurred(.success); case .failed, .expired, .unknown: g.notificationOccurred(.warning); default: UIImpactFeedbackGenerator(style: .soft).impactOccurred() }228            }229            withAnimation(.snappy) { message = m }230            error = nil231        } catch { self.error = model.handle(error) }232    }233    private func cancel() async {234        working = true; defer { working = false }235        do { _ = try await model.api.cancel(messageId); await load() } catch { self.error = model.handle(error) }236    }237}238
Files main
Menu

Theme