SPB Git

Repository Public

HistoryView.swift 11.3 KB 211 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/HistoryView.swift10// Description      : Historique filtrable des SMS et conversations en bulles.11// Module           : ios12// Repository       : https://git.spboucher.ai/maclustr-sms13// Project Website  : https://sms.spboucher.ai14// Created          : 2026-11-3015// Last Modified    : 2026-12-0116//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: admin@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : None specified (no license file in this repository)82// Maintainer       : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import SwiftUI9091struct MessageRow: View {92    let m: SMSMessage93    var body: some View {94        HStack(alignment: .top, spacing: 12) {95            Image(systemName: m.isOutbound ? "arrow.up.right" : "arrow.down.left").font(.footnote.weight(.semibold)).foregroundStyle(m.isOutbound ? Theme.muted : Theme.accent).frame(width: 18).padding(.top, 3)96            VStack(alignment: .leading, spacing: 4) {97                HStack { Text(PhoneNumber.pretty(m.peer)).font(.subheadline.weight(.semibold).monospacedDigit()).foregroundStyle(Theme.text); Spacer(); Text(m.createdAt.shortStamp).font(.caption.monospacedDigit()).foregroundStyle(Theme.faint) }98                Text(m.displayText).font(.footnote).foregroundStyle(Theme.muted).lineLimit(2)99                StatusBadge(status: m.status)100            }101        }102        .padding(.vertical, 4)103    }104}105106struct HistoryView: View {107    @Environment(AppModel.self) private var model108    enum Filter: String, CaseIterable, Identifiable { case all = "Tous", sent = "Envoyés", received = "Reçus", problems = "Échecs"; var id: String { rawValue } }109    @State private var filter: Filter = .all110    @State private var search = ""111    @State private var items: [SMSMessage] = []112    @State private var cursor: String?113    @State private var loaded = false114    @State private var error: String?115    @Environment(\.scenePhase) private var scenePhase116117    var body: some View {118        NavigationStack {119            List {120                Picker("Filtre", selection: $filter) { ForEach(Filter.allCases) { Text($0.rawValue).tag($0) } }.pickerStyle(.segmented).listRowBackground(Color.clear).listRowSeparator(.hidden)121                if let error { Banner(text: error, tone: .bad).listRowBackground(Color.clear) }122                if loaded && items.isEmpty { ContentUnavailableView("Aucun message", systemImage: "tray", description: Text(search.isEmpty ? "Les SMS envoyés et reçus apparaîtront ici." : "Aucun message pour ce numéro.")).listRowBackground(Color.clear) }123                ForEach(items) { m in124                    NavigationLink(value: m) { MessageRow(m: m) }.listRowBackground(Theme.panel)125                }126                if cursor != nil { Button("Charger la suite") { Task { await load(more: true) } }.frame(maxWidth: .infinity).listRowBackground(Theme.panel) }127            }128            .listStyle(.insetGrouped).scrollContentBackground(.hidden).background(Theme.bg)129            .navigationTitle("Historique")130            .navigationDestination(for: SMSMessage.self) { TrackingView(messageId: $0.id, initial: $0) }131            .searchable(text: $search, prompt: "Numéro exact (+1…)")132            .refreshable { await load(more: false) }133            .task(id: "\(filter.rawValue)|\(PhoneNumber.e164(search) ?? "")|\(model.messagesRevision)|\(scenePhase == .active)") {134                await load(more: false)135                // Tant qu'un envoi récent n'a pas d'issue, la liste se recharge seule (sans dépendre du flux temps réel).136                while !Task.isCancelled, PollSchedule.listNeedsPolling(items) { try? await Task.sleep(for: .seconds(2)); await load(more: false) }137            }138        }139    }140    private func load(more: Bool) async {141        do {142            let page = try await model.api.messages(direction: filter == .sent ? "outbound" : filter == .received ? "inbound" : nil,143                                                    status: filter == .problems ? "failed,expired,unknown" : nil, peer: PhoneNumber.e164(search), cursor: more ? cursor : nil)144            items = more ? items + page.data.filter { n in !items.contains { $0.id == n.id } } : page.data145            cursor = page.nextCursor; loaded = true; error = nil146        } catch { self.error = model.handle(error) }147    }148}149150struct ConversationsView: View {151    @Environment(AppModel.self) private var model152    @State private var items: [Conversation] = []153    @State private var loaded = false154    @State private var error: String?155    var body: some View {156        NavigationStack {157            List {158                if let error { Banner(text: error, tone: .bad).listRowBackground(Color.clear) }159                if loaded && items.isEmpty { ContentUnavailableView("Aucune conversation", systemImage: "bubble.left.and.bubble.right", description: Text("Un fil apparaît dès le premier message échangé avec un numéro.")).listRowBackground(Color.clear) }160                ForEach(items) { c in161                    NavigationLink(value: c) {162                        HStack {163                            VStack(alignment: .leading, spacing: 3) {164                                Text(PhoneNumber.pretty(c.peer)).font(.subheadline.weight(.semibold).monospacedDigit()).foregroundStyle(Theme.text)165                                Text("\(c.outboundCount) envoyé\(c.outboundCount > 1 ? "s" : "") · \(c.inboundCount) reçu\(c.inboundCount > 1 ? "s" : "") · ligne \(c.simId)").font(.caption).foregroundStyle(Theme.muted)166                            }167                            Spacer()168                            VStack(alignment: .trailing, spacing: 3) {169                                Text(c.lastMessageAt.ago).font(.caption).foregroundStyle(Theme.faint)170                                if c.unread > 0 { Text("\(c.unread)").font(.caption2.weight(.bold)).foregroundStyle(Theme.onAccent).padding(.horizontal, 6).padding(.vertical, 2).background(Theme.accent, in: Capsule()) }171                            }172                        }173                    }.listRowBackground(Theme.panel)174                }175                Section { } footer: { Text("La réception des réponses n'a pas encore été validée sur le téléphone passerelle : une réponse envoyée en RCS ou en iMessage n'arrive pas comme un SMS et n'apparaît pas ici.").font(.caption) }176            }177            .listStyle(.insetGrouped).scrollContentBackground(.hidden).background(Theme.bg)178            .navigationTitle("Conversations")179            .navigationDestination(for: Conversation.self) { ThreadView(conversation: $0) }180            .refreshable { await load() }181            .task(id: model.messagesRevision) { await load() }182        }183    }184    private func load() async { do { items = try await model.api.conversations(); loaded = true; error = nil } catch { self.error = model.handle(error) } }185}186187struct ThreadView: View {188    let conversation: Conversation189    @Environment(AppModel.self) private var model190    @State private var messages: [SMSMessage] = []191    @State private var error: String?192    var body: some View {193        ScrollViewReader { proxy in194            ScrollView {195                LazyVStack(spacing: 10) {196                    if let error { Banner(text: error, tone: .bad) }197                    ForEach(messages) { m in198                        NavigationLink(value: m) { Bubble(text: m.displayText, outgoing: m.isOutbound, footer: "\(m.createdAt.shortStamp) · \(m.status.label.lowercased())") }.buttonStyle(.plain).id(m.id)199                    }200                }.padding(16)201            }202            .background(Theme.bg)203            .onChange(of: messages.last?.id) { _, id in if let id { proxy.scrollTo(id, anchor: .bottom) } }204        }205        .navigationTitle(PhoneNumber.pretty(conversation.peer)).navigationBarTitleDisplayMode(.inline)206        .navigationDestination(for: SMSMessage.self) { TrackingView(messageId: $0.id, initial: $0) }207        .toolbar { ToolbarItem(placement: .primaryAction) { Button { model.pendingDraft = ComposeDraft(to: conversation.peer, text: "", simId: conversation.simId); model.selectedTab = 0 } label: { Image(systemName: "square.and.pencil") }.accessibilityLabel("Écrire à ce numéro") } }208        .task(id: model.messagesRevision) { do { messages = try await model.api.thread(conversation.id).reversed(); error = nil } catch { self.error = model.handle(error) } }209    }210}211
Files main
Menu

Theme