SPB Git

Repository Public

TableauEcran.swift 14.7 KB 310 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : Groupe Ka — app iOS native7// File             : GroupeKa/Features/Stats/TableauEcran.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/// Le tableau de bord complet d'un site, rendu à partir du contrat de l'API : chaque section n'apparaît que si le44/// site la publie (indicateurs, séries, répartitions, distributions, jauges, activité par jour et par heure,45/// tableaux, records, sections propres au site).46struct TableauEcran: View {47    let site: KaSite48    @Environment(AppEtat.self) private var app49    @Environment(\.horizontalSizeClass) private var classe50    @State private var tableau = Ressource<Tableau>()5152    private var couleur: Color { site.id.couleur }53    private var colonnes: Int { classe == .regular ? 2 : 1 }5455    var body: some View {56        @Bindable var app = app57        ScrollViewReader { defile in58            ScrollView {59                Colonne {60                    VStack(alignment: .leading, spacing: 0) {61                        tete62                        if let t = tableau.valeur {63                            corps(t)64                        } else if let e = tableau.erreur {65                            Constat(titre: "Le tableau de bord ne répond pas", texte: e.errorDescription) { Task { await charger() } }66                        } else {67                            Text("Lecture du tableau de bord sur \(app.periode.libelleLong)…").ka(.sans, 15, style: .subheadline).foregroundStyle(Ka.encre3).padding(.vertical, 40)68                        }69                    }70                }71                .padding(.bottom, 28)72            }73            .refreshable { await charger() }74            .onChange(of: tableau.valeur != nil, initial: true) { _, pret in75                // captures : aller droit à une section (-GKAncre series)76                guard pret, let a = app.options.ancre else { return }77                Task { try? await Task.sleep(for: .milliseconds(500)); defile.scrollTo(a, anchor: .top) }78            }79        }80        .safeAreaInset(edge: .top, spacing: 0) {81            VStack(spacing: 0) {82                EnTete(retour: { app.cheminStats = [] }) { SymboleMarque(site: site.id).frame(width: 26, height: 26) }83                Rectangle().fill(Ka.encre).frame(height: 5)84                    .overlay(alignment: .leading) { Rectangle().fill(couleur).frame(width: 64, height: 5).padding(.leading, 16) }85            }86        }87        .fondPapier()88        .toolbar(.hidden, for: .navigationBar)89        .task(id: app.periode) { await charger() }90    }9192    private func charger() async {93        await tableau.charger("/api/v1/sites/\(site.id.rawValue)/tableau", [("periode", app.periode.rawValue)])94    }9596    private var tete: some View {97        @Bindable var app = app98        return VStack(alignment: .leading, spacing: 0) {99            HStack(spacing: 12) {100                SymboleMarque(site: site.id).frame(width: 46, height: 46)101                VStack(alignment: .leading, spacing: 0) {102                    MotSymbole(site: site, taille: 32, style: .largeTitle).accessibilityAddTraits(.isHeader)103                        .accessibilityIdentifier("tableau-ecran-\(site.id.rawValue)")104                    Text("Tableau de bord · \(site.genre.lowercased(with: Fmt.locale))").ka(.sans, 14, style: .footnote).foregroundStyle(Ka.encre3)105                }106            }107            .padding(.top, 18)108            ChoixPeriode(periode: $app.periode, couleur: couleur).padding(.horizontal, -16).padding(.top, 8)109            Fraicheur(reponse: tableau.reponse, erreur: tableau.erreur, enCours: tableau.enCours).padding(.top, 6)110            if let p = tableau.valeur?.period {111                VStack(alignment: .leading, spacing: 4) {112                    if let e = Couverture.enonce(de: p.from, a: p.to) {113                        Text("Période couverte : \(e)").ka(.sans, 15, graisse: 600, style: .subheadline).foregroundStyle(Ka.encre)114                            .fixedSize(horizontal: false, vertical: true)115                            .accessibilityIdentifier("periode-couverte-tableau")116                    }117                    if p.composed == true, let n = p.note {118                        Text(n).ka(.sans, 13, style: .footnote).foregroundStyle(Ka.encre2).fixedSize(horizontal: false, vertical: true)119                    }120                }121                .padding(.top, 6)122            }123        }124        .padding(.bottom, 22)125    }126127    @ViewBuilder128    private func corps(_ t: Tableau) -> some View {129        indicateurs(t.kpis, titre: "Indicateurs").id("indicateurs")130131        if !t.series.isEmpty {132            section("Séries", id: "series") {133                grille {134                    ForEach(Array(t.series.enumerated()), id: \.offset) { _, s in135                        bloc(s.title, unite: s.unit) {136                            GraphiqueSerie(points: s.points, compare: s.compare, genre: s.kind ?? "line", couleur: couleur, unite: nil,137                                           identifiant: "serie-\(s.id ?? "")")138                        }139                    }140                }141            }142        }143        if !t.multiseries.isEmpty || !t.stacked.isEmpty {144            section("Comparaisons", id: "comparaisons") {145                grille {146                    ForEach(Array(t.multiseries.enumerated()), id: \.offset) { _, m in147                        bloc(m.title, unite: m.unit) { GraphiqueMulti(lignes: GraphiqueMulti.lignes(m.series, couleur: couleur), unite: m.unit) }148                    }149                    ForEach(Array(t.stacked.enumerated()), id: \.offset) { _, e in150                        bloc(e.title, unite: e.unit) { GraphiqueEmpile(empile: e, couleur: couleur) }151                    }152                }153            }154        }155        if !t.breakdowns.isEmpty || t.geo != nil {156            section("Répartitions", id: "repartitions") {157                grille {158                    ForEach(Array(t.breakdowns.enumerated()), id: \.offset) { _, r in repartition(r) }159                    if let g = t.geo, !g.items.isEmpty {160                        bloc(g.title, unite: g.unit) { BarresRepartition(items: g.items, couleur: couleur, parts: g.unit == nil) }161                    }162                }163            }164        }165        if !t.distributions.isEmpty {166            section("Distributions", id: "distributions") {167                grille {168                    ForEach(Array(t.distributions.enumerated()), id: \.offset) { _, d in169                        bloc(d.title, unite: d.unit) { Histogramme(bins: d.bins, couleur: couleur) }170                    }171                }172            }173        }174        if !t.gauges.isEmpty {175            section("Qualité des données", id: "jauges") {176                grille(espacement: 14) {177                    ForEach(Array(t.gauges.enumerated()), id: \.offset) { _, j in RegleJauge(jauge: j, couleur: couleur) }178                }179            }180        }181        if (t.heatmap?.cells.isEmpty == false) || (t.hourly?.cells.isEmpty == false) {182            section("Activité", id: "activite") {183                grille {184                    if let h = t.heatmap, !h.cells.isEmpty { bloc(h.title ?? "Par jour", unite: nil) { CarteDesJours(carte: h, couleur: couleur) } }185                    if let h = t.hourly, !h.cells.isEmpty { bloc(h.title ?? "Par heure", unite: nil) { GrilleDesHeures(grille: h, couleur: couleur) } }186                }187            }188        }189        if !t.tables.isEmpty {190            section("Tableaux", id: "tableaux") {191                ForEach(Array(t.tables.enumerated()), id: \.offset) { _, tb in bloc(tb.title, unite: nil) { TableKa(table: tb) } }192            }193        }194        if !t.records.isEmpty {195            section("Records", id: "records") { records(t.records) }196        }197        ForEach(Array(t.panels.enumerated()), id: \.offset) { _, p in panneau(p) }198        if let m = t.method { methode(m) }199    }200201    // ── pièces202203    @ViewBuilder204    private func indicateurs(_ kpis: [Indicateur], titre: String?) -> some View {205        let lisibles = kpis.filter { Fmt.valeur($0.value, unite: $0.unit) != nil }206        if !lisibles.isEmpty {207            VStack(alignment: .leading, spacing: 0) {208                if let titre { TitreSection(titre: titre).padding(.bottom, 10) }209                LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 20, alignment: .top), count: classe == .regular ? 4 : 2), spacing: 0) {210                    ForEach(Array(lisibles.enumerated()), id: \.offset) { _, k in211                        CaseIndicateur(libelle: k.label ?? "—", valeur: Fmt.valeur(k.value, unite: k.unit) ?? "", variation: k.delta_pct, spark: k.spark, couleur: couleur)212                    }213                }214            }215            .padding(.bottom, titre == nil ? 14 : 28)216        }217    }218219    private func section<C: View>(_ titre: String, id: String, @ViewBuilder _ contenu: () -> C) -> some View {220        VStack(alignment: .leading, spacing: 16) {221            TitreSection(titre: titre)222            contenu()223        }224        .padding(.bottom, 30)225        .id(id)226    }227228    private func grille<C: View>(espacement: CGFloat = 26, @ViewBuilder _ contenu: () -> C) -> some View {229        LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 36, alignment: .top), count: colonnes), alignment: .leading, spacing: espacement) { contenu() }230    }231232    private func bloc<C: View>(_ titre: String?, unite: String?, @ViewBuilder _ contenu: () -> C) -> some View {233        VStack(alignment: .leading, spacing: 10) {234            if let titre { TitreBloc(titre: titre, unite: unite) }235            contenu()236        }237        .frame(maxWidth: .infinity, alignment: .leading)238        .padding(.bottom, 6)239    }240241    private func repartition(_ r: Repartition) -> some View {242        bloc(r.title, unite: r.unit) {243            // peu de parts d'un tout : une règle ; sinon une ligne par catégorie244            if r.kind == "donut", r.items.count <= 6 { RegleParts(items: r.items, couleur: couleur) } else {245                BarresRepartition(items: r.items, couleur: couleur, parts: r.kind == "donut")246            }247        }248    }249250    private func records(_ liste: [Record]) -> some View {251        VStack(spacing: 0) {252            ForEach(Array(liste.enumerated()), id: \.offset) { _, r in253                VStack(alignment: .leading, spacing: 2) {254                    Text(r.label ?? "—").ka(.sans, 13, style: .footnote).foregroundStyle(Ka.encre3).fixedSize(horizontal: false, vertical: true)255                    HStack(alignment: .firstTextBaseline) {256                        Text(r.value ?? "").ka(.serif, 20, graisse: 500, style: .title3).foregroundStyle(Ka.encre).fixedSize(horizontal: false, vertical: true)257                        Spacer(minLength: 8)258                        if let d = Fmt.jour(r.date, annee: true) { Text(d).ka(.sans, 12, style: .caption1).foregroundStyle(Ka.encre3) }259                    }260                }261                .frame(maxWidth: .infinity, alignment: .leading)262                .padding(.vertical, 9)263                .overlay(alignment: .top) { Filet() }264                .accessibilityElement(children: .combine)265            }266        }267    }268269    private func panneau(_ p: Panneau) -> some View {270        VStack(alignment: .leading, spacing: 14) {271            TitreSection(titre: p.title ?? "—", note: p.subtitle)272            indicateurs(p.kpis, titre: nil)273            grille {274                ForEach(Array(p.breakdowns.enumerated()), id: \.offset) { _, r in repartition(r) }275                ForEach(Array(p.distributions.enumerated()), id: \.offset) { _, d in bloc(d.title, unite: d.unit) { Histogramme(bins: d.bins, couleur: couleur) } }276            }277            ForEach(Array(p.tables.enumerated()), id: \.offset) { _, tb in bloc(tb.title, unite: nil) { TableKa(table: tb) } }278        }279        .padding(.bottom, 30)280        .id("panneau-\(p.id ?? "")")281    }282283    /// La méthode publiée avec le tableau (indice de Food-Ka) : les textes du serveur, tels quels.284    @ViewBuilder285    private func methode(_ m: JSONValeur) -> some View {286        if case .objet(let o) = m {287            let ordre = ["nom", "type", "prix", "champ", "exclusions", "bornes", "seuil"]288            let cles = ordre.filter { o[$0]?.chaine != nil } + o.keys.filter { !ordre.contains($0) && o[$0]?.chaine != nil }.sorted()289            VStack(alignment: .leading, spacing: 0) {290                TitreSection(titre: "Méthode").padding(.bottom, 10)291                Filet()292                ForEach(cles, id: \.self) { k in LigneFiche(libelle: k.prefix(1).uppercased() + k.dropFirst(), valeur: o[k]?.chaine ?? "") }293                if case .liste(let limites)? = o["limites"] {294                    VStack(alignment: .leading, spacing: 8) {295                        Cote(texte: "Limites").padding(.top, 12)296                        ForEach(Array(limites.compactMap(\.chaine).enumerated()), id: \.offset) { _, l in297                            HStack(alignment: .firstTextBaseline, spacing: 10) {298                                Rectangle().fill(couleur).frame(width: 9, height: 1.5).offset(y: -4)299                                Text(l).ka(.sans, 14, style: .footnote).foregroundStyle(Ka.encre2).fixedSize(horizontal: false, vertical: true)300                            }301                        }302                    }303                }304            }305            .padding(.bottom, 30)306            .id("methode")307        }308    }309}310
Files main
Menu

Theme