SPB Git

Repository Public

StatsEcran.swift 19.4 KB 393 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : Groupe Ka — app iOS native7// File             : GroupeKa/Features/Stats/StatsEcran.swift8// Module           : Groupe Ka9// Repository       : https://git.spboucher.ai/groupe-ka-ios10// Project Website  : Not specified11// Created          : 2026-12-0312// Last Modified    : 2026-12-0313//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI4243/// L'onglet Stats : l'observatoire des quatre sites mesurés (Lou-Ka, Immo-Ka, Auto-Ka, Food-Ka), côte à côte.44struct StatsEcran: View {45    @Environment(AppEtat.self) private var app46    @Environment(\.horizontalSizeClass) private var classe47    @Environment(\.scenePhase) private var phase48    @State private var obs = Ressource<Observatoire>()4950    var body: some View {51        @Bindable var app = app52        NavigationStack(path: $app.cheminStats) {53            ScrollView {54                Colonne {55                    VStack(alignment: .leading, spacing: 0) {56                        tete57                        if let o = obs.valeur {58                            totaux(o)59                            marche(o)60                            sites(o)61                            comparer62                            collectes(o)63                        } else if let e = obs.erreur {64                            Constat(titre: "L'observatoire ne répond pas", texte: e.errorDescription) { Task { await charger() } }65                        } else {66                            Text("Lecture de l'observatoire…").ka(.sans, 15, style: .subheadline).foregroundStyle(Ka.encre3).padding(.vertical, 40)67                        }68                    }69                }70                .padding(.bottom, 28)71            }72            .refreshable { await charger() }73            .safeAreaInset(edge: .top, spacing: 0) {74                EnTete { BoutonTexte(titre: "Réglages") { app.reglagesOuverts = true } }75            }76            .fondPapier()77            .toolbar(.hidden, for: .navigationBar)78            .navigationDestination(for: DestStats.self) { d in79                switch d {80                case .site(let id): TableauEcran(site: KaSite.de(id))81                case .comparateur: ComparateurEcran()82                }83            }84        }85        .task(id: app.periode) { await charger() }86        .onChange(of: phase) { _, p in if p == .active { Task { await charger() } } }87    }8889    private func charger() async { await obs.charger("/api/v1/observatoire", [("periode", app.periode.rawValue)]) }9091    // ── tête : le titre, la période, la fraîcheur9293    private var tete: some View {94        @Bindable var app = app95        return VStack(alignment: .leading, spacing: 0) {96            Text("L’observatoire")97                .ka(.serif, 36, graisse: 500, style: .largeTitle, plafond: 1.6).tracking(-0.8).foregroundStyle(Ka.encre)98                .padding(.top, 10)99                .accessibilityAddTraits(.isHeader)100            Text("Lou-Ka, Immo-Ka, Auto-Ka et Food-Ka côte à côte : ce que chaque site affiche, lu dans son instance de production.")101                .ka(.sans, 15, style: .subheadline).foregroundStyle(Ka.encre2).padding(.top, 6)102                .fixedSize(horizontal: false, vertical: true)103            ChoixPeriode(periode: $app.periode).padding(.horizontal, -16).padding(.top, 10)104            Fraicheur(reponse: obs.reponse, erreur: obs.erreur, enCours: obs.enCours).padding(.top, 6).padding(.bottom, 18)105        }106    }107108    // ── totaux109110    @ViewBuilder111    private func totaux(_ o: Observatoire) -> some View {112        let t = o.totaux113        let cases: [(String, Double?)] = [("Annonces affichées", t?.annonces), ("Sources de collecte", t?.sources),114                                          ("Prix évalués", t?.evaluees), ("Sous le marché", t?.sous_le_marche)]115        let presents = cases.filter { $0.1 != nil }116        if !presents.isEmpty {117            VStack(alignment: .leading, spacing: 0) {118                Filet(couleur: Ka.encre)119                LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 16, alignment: .topLeading), count: classe == .regular ? 4 : 2), alignment: .leading, spacing: 0) {120                    ForEach(presents, id: \.0) { c in121                        VStack(alignment: .leading, spacing: 2) {122                            Text(Fmt.entier(c.1) ?? "").ka(.serif, 30, graisse: 500, style: .title1, plafond: 1.5).foregroundStyle(Ka.encre).monospacedDigit()123                                .lineLimit(1).minimumScaleFactor(0.6)124                            Text(c.0).ka(.sans, 13, style: .footnote).foregroundStyle(Ka.encre3)125                        }126                        .padding(.vertical, 12)127                        .frame(maxWidth: .infinity, alignment: .leading)128                        .accessibilityElement(children: .combine)129                    }130                }131                if let n = t?.sites, let l = t?.sites_en_ligne {132                    Filet()133                    HStack(spacing: 7) {134                        Rectangle().fill(l == n ? Ka.encre : Ka.filet2).frame(width: 7, height: 7)135                        Text("\(Fmt.nombre(l)) instance\(l > 1 ? "s" : "") sur \(Fmt.nombre(n)) en ligne\(o.periode?.de != nil ? " · période du \(Fmt.jour(o.periode?.de) ?? "") au \(Fmt.jour(o.periode?.a, annee: true) ?? "")" : "")")136                            .ka(.sans, 13, style: .footnote).foregroundStyle(Ka.encre2)137                            .fixedSize(horizontal: false, vertical: true)138                    }139                    .padding(.vertical, 10)140                    .accessibilityElement(children: .combine)141                }142            }143            .padding(.bottom, 26)144        }145    }146147    // ── position des prix par rapport au marché, sur une échelle commune148149    @ViewBuilder150    private func marche(_ o: Observatoire) -> some View {151        let lignes = o.sites.filter { $0.marche?.pct_sous != nil && $0.marche?.pct_dans != nil && $0.marche?.pct_dessus != nil }152        if !lignes.isEmpty {153            VStack(alignment: .leading, spacing: 0) {154                TitreSection(titre: "Les prix face au marché",155                             note: "Part des annonces sous, dans et au-dessus du marché, sur la même règle de 0 à 100 %. Chaque site juge selon sa propre référence.")156                HStack(spacing: 14) {157                    Legende(couleur: Ka.encre, aplat: true, texte: "sous le marché")158                    Legende(couleur: Ka.encre.opacity(0.4), aplat: true, texte: "dans le marché")159                    Legende(couleur: Ka.filet2, aplat: true, texte: "au-dessus")160                }161                .padding(.top, 12)162                .accessibilityHidden(true)163                VStack(spacing: 14) {164                    ForEach(lignes) { s in RegleMarche(site: s) }165                }166                .padding(.top, 14)167            }168            .padding(.bottom, 30)169        }170    }171172    // ── les quatre sites173174    private func sites(_ o: Observatoire) -> some View {175        VStack(alignment: .leading, spacing: 0) {176            TitreSection(titre: "Site par site").padding(.bottom, 4)177            // quatre planches : une grille simple, rien n'est différé178            LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 32, alignment: .top), count: classe == .regular ? 2 : 1), spacing: 0) {179                ForEach(o.sites) { s in180                    PlancheSite(site: s) { if let id = s.siteID, id.estMesure { app.cheminStats = [.site(id)] } }181                }182            }183        }184        .padding(.bottom, 26)185    }186187    private var comparer: some View {188        VStack(alignment: .leading, spacing: 6) {189            TitreSection(titre: "Comparer des séries", note: "Deux à quatre séries de l'historique sur le même repère, d'un site à l'autre.")190            LienTexte(titre: "Ouvrir le comparateur", couleur: Ka.encre) { app.cheminStats = [.comparateur] }191                .accessibilityIdentifier("ouvrir-comparateur")192        }193        .padding(.bottom, 26)194    }195196    // ── collectes au fil de l'eau197198    @ViewBuilder199    private func collectes(_ o: Observatoire) -> some View {200        if !o.collectes.isEmpty {201            VStack(alignment: .leading, spacing: 0) {202                TitreSection(titre: "Collectes récentes", note: "Les derniers passages des collecteurs dans les sources de chaque site.")203                    .padding(.bottom, 10)204                ForEach(Array(o.collectes.prefix(14).enumerated()), id: \.offset) { _, c in205                    LigneCollecte(collecte: c)206                }207            }208        }209    }210}211212/// La règle d'un site : trois aplats à sa couleur, de 0 à 100 %.213private struct RegleMarche: View {214    let site: SiteObservatoire215216    var body: some View {217        let m = site.marche, c = site.siteID?.couleur ?? Ka.encre218        let sous = m?.pct_sous ?? 0, dans = m?.pct_dans ?? 0, dessus = m?.pct_dessus ?? 0219        VStack(alignment: .leading, spacing: 5) {220            HStack(alignment: .firstTextBaseline) {221                Text(site.nom ?? "—").ka(.sans, 15, graisse: 600, style: .subheadline).foregroundStyle(Ka.encre)222                Spacer(minLength: 8)223                Text("\(Fmt.pct(sous) ?? "") · \(Fmt.pct(dans) ?? "") · \(Fmt.pct(dessus) ?? "")").ka(.sans, 13, style: .footnote).foregroundStyle(Ka.encre2).monospacedDigit()224            }225            GeometryReader { g in226                let l = g.size.width227                HStack(spacing: 0) {228                    Rectangle().fill(c).frame(width: max(0, l * sous / 100))229                    Rectangle().fill(c.opacity(0.4)).frame(width: max(0, l * dans / 100))230                    Rectangle().fill(Ka.filet2).frame(width: max(0, l * dessus / 100))231                }232                // graduations de la règle commune : 25, 50, 75 %233                .overlay(alignment: .leading) {234                    ForEach(1..<4) { k in Rectangle().fill(Ka.papier).frame(width: 1).offset(x: g.size.width * CGFloat(k) / 4) }235                }236            }237            .frame(height: 14)238            if let r = m?.reference {239                Text("\(Fmt.entier(m?.evalues) ?? "") évaluées · référence : \(r)").ka(.sans, 12, style: .caption1).foregroundStyle(Ka.encre3)240                    .fixedSize(horizontal: false, vertical: true)241            }242        }243        .accessibilityElement(children: .ignore)244        .accessibilityLabel("\(site.nom ?? "") : \(Fmt.pct(sous) ?? "") sous le marché, \(Fmt.pct(dans) ?? "") dans le marché, \(Fmt.pct(dessus) ?? "") au-dessus")245        .accessibilityValue(m?.reference.map { "Référence : \($0)" } ?? "")246    }247}248249/// La planche d'un site dans la vue d'ensemble : son chiffre, sa variation, son pouls, ses indicateurs, sa collecte,250/// son instance. Chaque ligne n'existe que si le serveur l'a publiée.251private struct PlancheSite: View {252    let site: SiteObservatoire253    let ouvrir: () -> Void254255    var body: some View {256        let id = site.siteID, c = id?.couleur ?? Ka.encre257        VStack(alignment: .leading, spacing: 0) {258            Filet()259            HStack(spacing: 12) {260                if let id { SymboleMarque(site: id).frame(width: 38, height: 38) }261                VStack(alignment: .leading, spacing: 1) {262                    if let id { MotSymbole(site: KaSite.de(id), taille: 23, style: .title2) } else {263                        Text(site.nom ?? "—").ka(.serif, 23, graisse: 500, style: .title2)264                    }265                    if let g = site.genre { Text(g).ka(.sans, 13, style: .footnote).foregroundStyle(Ka.encre3) }266                }267                Spacer(minLength: 8)268                instance269            }270            .padding(.top, 16)271272            if let v = site.chiffre?.valeur {273                HStack(alignment: .firstTextBaseline, spacing: 10) {274                    Text(Fmt.nombre(v)).ka(.serif, 44, graisse: 500, style: .largeTitle, plafond: 1.4).tracking(-1).foregroundStyle(Ka.encre).monospacedDigit()275                        .lineLimit(1).minimumScaleFactor(0.6)276                    if let t = Fmt.variation(site.variation_pct) { Variation(texte: t, valeur: site.variation_pct ?? 0) }277                }278                .padding(.top, 10)279                .accessibilityElement(children: .combine)280                .accessibilityIdentifier("chiffre-obs-\(site.id ?? "")")281                if let l = site.chiffre?.libelle { Text(l).ka(.sans, 14, style: .footnote).foregroundStyle(Ka.encre2) }282            }283284            if let p = site.pouls, p.points.count > 1 {285                VStack(alignment: .leading, spacing: 4) {286                    Cote(texte: [p.libelle, p.pas == "semaine" ? "par semaine" : nil].compactMap { $0 }.joined(separator: " · "))287                    GraphiqueSerie(points: p.points, couleur: c, unite: nil, hauteur: 120)288                }289                .padding(.top, 14)290            }291292            let kpis = site.kpis.filter { Fmt.valeur($0.valeur, unite: $0.unite) != nil }.prefix(4)293            if !kpis.isEmpty {294                LazyVGrid(columns: [GridItem(.flexible(), spacing: 16, alignment: .topLeading), GridItem(.flexible(), alignment: .topLeading)], spacing: 0) {295                    ForEach(Array(kpis.enumerated()), id: \.offset) { _, k in296                        VStack(alignment: .leading, spacing: 1) {297                            Text(Fmt.valeur(k.valeur, unite: k.unite) ?? "").ka(.sans, 16, graisse: 600, style: .callout).foregroundStyle(Ka.encre).monospacedDigit()298                            Text((k.libelle ?? "") + (Fmt.variation(k.variation_pct).map { " (\($0))" } ?? ""))299                                .ka(.sans, 12, style: .caption1).foregroundStyle(Ka.encre3).fixedSize(horizontal: false, vertical: true)300                        }301                        .frame(maxWidth: .infinity, alignment: .leading)302                        .padding(.vertical, 7)303                        .overlay(alignment: .top) { Filet() }304                        .accessibilityElement(children: .combine)305                    }306                }307                .padding(.top, 12)308            }309310            if let t = collecte { ligne("Collecte", t) }311            if let h = site.hebergement { ligne("Instance", h) }312313            LienTexte(titre: "Tableau de bord de \(site.nom ?? "ce site")", couleur: id?.couleurTexte ?? Ka.encre, action: ouvrir)314                .padding(.top, 4)315                .accessibilityIdentifier("tableau-\(site.id ?? "")")316        }317        .padding(.bottom, 18)318    }319320    private func ligne(_ nom: String, _ texte: String) -> some View {321        HStack(alignment: .firstTextBaseline, spacing: 10) {322            Cote(texte: nom).frame(width: 74, alignment: .leading)323            Text(texte).ka(.sans, 13, style: .footnote).foregroundStyle(Ka.encre2).fixedSize(horizontal: false, vertical: true)324        }325        .padding(.vertical, 7)326        .frame(maxWidth: .infinity, alignment: .leading)327        .overlay(alignment: .top) { Filet() }328        .accessibilityElement(children: .combine)329    }330331    /// « 143 sources · 134 en bon état · 1 en alerte · 6 en panne » : seulement ce que le site publie332    private var collecte: String? {333        guard let c = site.collecte else { return nil }334        var p: [String] = []335        if let s = c.sources { p.append("\(Fmt.nombre(s)) sources") }336        if let v = c.ok { p.append("\(Fmt.nombre(v)) en bon état") }337        if let v = c.en_alerte { p.append("\(Fmt.nombre(v)) en alerte") }338        if let v = c.en_panne { p.append("\(Fmt.nombre(v)) en panne") }339        if let v = c.suspendues { p.append("\(Fmt.nombre(v)) suspendues") }340        return p.isEmpty ? nil : p.joined(separator: " · ")341    }342343    /// état de l'instance : un carré plein si elle répond, vide sinon ; le délai de la dernière sonde344    @ViewBuilder345    private var instance: some View {346        if let e = site.etat, let enLigne = e.en_ligne {347            VStack(alignment: .trailing, spacing: 2) {348                HStack(spacing: 6) {349                    Rectangle().fill(enLigne ? Ka.encre : .clear).frame(width: 8, height: 8).overlay(Rectangle().strokeBorder(Ka.encre, lineWidth: 1))350                    Text(enLigne ? "en ligne" : "hors ligne").ka(.sans, 13, graisse: 500, style: .footnote).foregroundStyle(Ka.encre)351                }352                if let d = Fmt.delai(e.delai_ms), enLigne { Text(d).ka(.sans, 12, style: .caption1).foregroundStyle(Ka.encre3).monospacedDigit() }353                if e.donnees_perimees == true { Text("données périmées").ka(.sans, 12, graisse: 500, style: .caption1).foregroundStyle(Ka.encre) }354            }355            .accessibilityElement(children: .combine)356            .accessibilityLabel("Instance \(enLigne ? "en ligne" : "hors ligne")\(Fmt.delai(e.delai_ms).map { ", \($0)" } ?? "")\(e.donnees_perimees == true ? ", données périmées" : "")")357        }358    }359}360361struct LigneCollecte: View {362    let collecte: Collecte363    var body: some View {364        let id = collecte.site.flatMap(SiteID.init(rawValue:))365        VStack(spacing: 0) {366            HStack(alignment: .center, spacing: 10) {367                if let id { SymboleMarque(site: id).frame(width: 22, height: 22) }368                VStack(alignment: .leading, spacing: 1) {369                    Text(collecte.source ?? "—").ka(.sans, 14, graisse: 500, style: .footnote).foregroundStyle(Ka.encre).lineLimit(1)370                    Text(detail).ka(.sans, 12, style: .caption1).foregroundStyle(Ka.encre3).monospacedDigit()371                }372                Spacer(minLength: 8)373                VStack(alignment: .trailing, spacing: 1) {374                    if let d = Dates.instant(collecte.a) { Text(Fmt.ilYA(d)).ka(.sans, 12, style: .caption1).foregroundStyle(Ka.encre3) }375                    if collecte.ok == false { Text("échec").ka(.sans, 12, graisse: 600, style: .caption1).foregroundStyle(Ka.encre) }376                }377            }378            .padding(.vertical, 8)379            Filet()380        }381        .accessibilityElement(children: .combine)382    }383384    private var detail: String {385        var p: [String] = []386        if let v = collecte.trouvees { p.append("\(Fmt.nombre(v)) trouvées") }387        if let v = collecte.ajoutees { p.append("\(Fmt.nombre(v)) ajoutées") }388        if let v = collecte.mises_a_jour { p.append("\(Fmt.nombre(v)) mises à jour") }389        if let v = collecte.retirees { p.append("\(Fmt.nombre(v)) retirées") }390        return p.joined(separator: " · ")391    }392}393
Files main
Menu

Theme