Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : Groupe Ka — app iOS native7// File : GroupeKaWidget/GroupeKaWidget.swift8// Module : Groupe Ka Widget9// 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 AppIntents42import SwiftUI43import WidgetKit4445// Widget de l'écran d'accueil : les quatre chiffres vivants de l'observatoire, ou le chiffre et la courbe d'un site.46// Les données viennent de /api/v1/observatoire ; rien n'est inventé : sans lecture, le widget le dit.4748@main49struct GroupeKaWidgets: WidgetBundle {50 var body: some Widget { ChiffresWidget() }51}5253enum ChoixSite: String, AppEnum {54 case tous, louka, immoka, autoka, foodka5556 static let typeDisplayRepresentation: TypeDisplayRepresentation = "Affichage"57 static let caseDisplayRepresentations: [ChoixSite: DisplayRepresentation] = [58 .tous: "Les quatre sites", .louka: "Lou-Ka", .immoka: "Immo-Ka", .autoka: "Auto-Ka", .foodka: "Food-Ka",59 ]6061 var site: SiteID? { SiteID(rawValue: rawValue) }62}6364struct ConfigurationChiffres: WidgetConfigurationIntent {65 static let title: LocalizedStringResource = "Chiffres du Groupe Ka"66 static let description = IntentDescription("Les quatre sites côte à côte, ou le chiffre et la courbe d'un seul.")6768 @Parameter(title: "Affichage", default: .tous)69 var affichage: ChoixSite70}7172struct SiteWidget: Sendable, Identifiable {73 let id: SiteID74 let valeur: Double?75 let libelle: String?76 let variation: Double?77 let points: [Double]78 let enLigne: Bool?79}8081struct EntreeChiffres: TimelineEntry {82 let date: Date83 let affichage: ChoixSite84 let sites: [SiteWidget]85 /// instant où la réponse affichée a été reçue ; `nil` : aucune lecture86 let recuA: Date?87 let horsLigne: Bool88 let perime: Bool89}9091struct FournisseurChiffres: AppIntentTimelineProvider {92 func placeholder(in context: Context) -> EntreeChiffres {93 EntreeChiffres(date: .now, affichage: .tous, sites: [], recuA: nil, horsLigne: false, perime: false)94 }9596 func snapshot(for configuration: ConfigurationChiffres, in context: Context) async -> EntreeChiffres {97 await lire(configuration.affichage)98 }99100 func timeline(for configuration: ConfigurationChiffres, in context: Context) async -> Timeline<EntreeChiffres> {101 let e = await lire(configuration.affichage)102 // relecture environ toutes les 30 minutes (le système décide de l'instant exact)103 return Timeline(entries: [e], policy: .after(Date().addingTimeInterval(30 * 60)))104 }105106 private func lire(_ affichage: ChoixSite) async -> EntreeChiffres {107 guard let r = try? await API.partagee.lire(Observatoire.self, "/api/v1/observatoire", [("periode", "30j")]) else {108 return EntreeChiffres(date: .now, affichage: affichage, sites: [], recuA: nil, horsLigne: true, perime: false)109 }110 let sites = r.valeur.sites.compactMap { s -> SiteWidget? in111 guard let id = s.siteID else { return nil }112 return SiteWidget(id: id, valeur: s.chiffre?.valeur, libelle: s.chiffre?.libelle, variation: s.variation_pct,113 points: s.pouls?.points.map(\.v) ?? [], enLigne: s.etat?.en_ligne)114 }115 return EntreeChiffres(date: .now, affichage: affichage, sites: sites, recuA: r.recueA, horsLigne: r.provenance == .horsLigne, perime: r.perime)116 }117}118119struct ChiffresWidget: Widget {120 var body: some WidgetConfiguration {121 AppIntentConfiguration(kind: "chiffres", intent: ConfigurationChiffres.self, provider: FournisseurChiffres()) { entree in122 VueChiffres(entree: entree)123 .containerBackground(Ka.papier, for: .widget)124 }125 .configurationDisplayName("Chiffres")126 .description("Ce que Lou-Ka, Immo-Ka, Auto-Ka et Food-Ka affichent en ce moment.")127 .supportedFamilies([.systemSmall, .systemMedium])128 .contentMarginsDisabled()129 }130}131132struct VueChiffres: View {133 let entree: EntreeChiffres134 @Environment(\.widgetFamily) private var famille135136 var body: some View {137 Group {138 if entree.sites.isEmpty {139 vide140 } else if let id = entree.affichage.site {141 if let s = entree.sites.first(where: { $0.id == id }) { unSite(s) } else { vide }142 } else {143 tous144 }145 }146 .padding(famille == .systemSmall ? 14 : 16)147 .widgetURL(URL(string: entree.affichage.site.map { "groupeka://stats/\($0.rawValue)" } ?? "groupeka://stats"))148 }149150 // ── sans lecture : on le dit, sans chiffre de remplacement151152 private var vide: some View {153 VStack(alignment: .leading, spacing: 6) {154 tete155 Spacer(minLength: 0)156 Text(entree.recuA == nil && !entree.horsLigne ? "Lecture en cours." : "Aucune lecture pour l'instant.")157 .font(KaFont.police(.sans, 13)).foregroundStyle(Ka.encre2)158 Spacer(minLength: 0)159 }160 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)161 }162163 private var tete: some View {164 HStack(spacing: 6) {165 SymboleGroupe().frame(width: 15, height: 15)166 (Text("Groupe ").foregroundStyle(Ka.encre3) + Text("Ka").foregroundStyle(Ka.encre)).font(KaFont.police(.serif, 14, graisse: 500))167 Spacer(minLength: 4)168 if let f = fraicheur { Text(f).font(KaFont.police(.sans, 10)).foregroundStyle(Ka.encre3).lineLimit(1) }169 }170 }171172 /// « 18 h 12 » ; « hors ligne » ou « périmé » quand c'est le cas173 private var fraicheur: String? {174 guard let d = entree.recuA else { return nil }175 if entree.horsLigne { return "hors ligne · \(Fmt.heure(d))" }176 if entree.perime { return "périmé · \(Fmt.heure(d))" }177 return Fmt.heure(d)178 }179180 // ── les quatre sites181182 @ViewBuilder183 private var tous: some View {184 let sites = SiteID.mesures.compactMap { id in entree.sites.first { $0.id == id } }185 if famille == .systemSmall {186 VStack(alignment: .leading, spacing: 0) {187 tete.padding(.bottom, 7)188 ForEach(sites) { s in189 Rectangle().fill(Ka.filet).frame(height: 1)190 HStack(spacing: 7) {191 SymboleMarque(site: s.id).frame(width: 17, height: 17)192 Spacer(minLength: 2)193 if let v = s.valeur {194 Text(Fmt.nombre(v)).font(KaFont.police(.sans, 15, graisse: 600)).foregroundStyle(Ka.encre).monospacedDigit().lineLimit(1).minimumScaleFactor(0.7)195 }196 }197 .frame(maxHeight: .infinity)198 .accessibilityElement(children: .ignore)199 .accessibilityLabel(KaSite.de(s.id).nomComplet)200 .accessibilityValue(s.valeur.map { "\(Fmt.nombre($0)) \(s.libelle ?? "")" } ?? "pas de chiffre")201 }202 }203 } else {204 VStack(alignment: .leading, spacing: 8) {205 tete206 Rectangle().fill(Ka.encre).frame(height: 1)207 HStack(alignment: .top, spacing: 12) {208 ForEach(sites) { s in209 VStack(alignment: .leading, spacing: 3) {210 SymboleMarque(site: s.id).frame(width: 22, height: 22)211 if let v = s.valeur {212 Text(Fmt.nombre(v)).font(KaFont.police(.serif, 19, graisse: 500)).foregroundStyle(Ka.encre).monospacedDigit().lineLimit(1).minimumScaleFactor(0.6)213 }214 if let l = s.libelle {215 Text(l).font(KaFont.police(.sans, 10)).foregroundStyle(Ka.encre3).lineLimit(2).fixedSize(horizontal: false, vertical: true)216 }217 Spacer(minLength: 0)218 if let t = Fmt.variation(s.variation) {219 Text(t).font(KaFont.police(.sans, 11, graisse: 500)).foregroundStyle(Ka.encre2).monospacedDigit()220 }221 }222 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)223 .accessibilityElement(children: .ignore)224 .accessibilityLabel(KaSite.de(s.id).nomComplet)225 .accessibilityValue(s.valeur.map { "\(Fmt.nombre($0)) \(s.libelle ?? "")" } ?? "pas de chiffre")226 }227 }228 }229 }230 }231232 // ── un site : son chiffre et sa courbe233234 @ViewBuilder235 private func unSite(_ s: SiteWidget) -> some View {236 let site = KaSite.de(s.id)237 let nom = HStack(spacing: 7) {238 SymboleMarque(site: s.id).frame(width: 20, height: 20)239 (Text(site.nom.0).foregroundStyle(Ka.encre) + Text("-").foregroundStyle(Ka.encre3) + Text(site.nom.1).foregroundStyle(s.id.couleurTexte))240 .font(KaFont.police(.serif, 16, graisse: 500))241 Spacer(minLength: 2)242 if let f = fraicheur { Text(f).font(KaFont.police(.sans, 10)).foregroundStyle(Ka.encre3).lineLimit(1) }243 }244 let chiffre = VStack(alignment: .leading, spacing: 1) {245 if let v = s.valeur {246 Text(Fmt.nombre(v)).font(KaFont.police(.serif, famille == .systemSmall ? 30 : 34, graisse: 500)).foregroundStyle(Ka.encre).monospacedDigit()247 .lineLimit(1).minimumScaleFactor(0.6)248 } else {249 Text("Pas de chiffre lu.").font(KaFont.police(.sans, 13)).foregroundStyle(Ka.encre2)250 }251 if let l = s.libelle { Text(l).font(KaFont.police(.sans, 11)).foregroundStyle(Ka.encre2).lineLimit(2) }252 if let t = Fmt.variation(s.variation) {253 Text("\(t) sur 30 jours").font(KaFont.police(.sans, 11, graisse: 500)).foregroundStyle(Ka.encre3).monospacedDigit()254 }255 }256 if famille == .systemSmall {257 VStack(alignment: .leading, spacing: 6) {258 nom259 chiffre260 if s.points.count > 1 { CourbeWidget(points: s.points, couleur: s.id.couleur).frame(maxHeight: .infinity) } else { Spacer(minLength: 0) }261 }262 } else {263 VStack(alignment: .leading, spacing: 8) {264 nom265 Rectangle().fill(Ka.encre).frame(height: 1)266 HStack(alignment: .center, spacing: 14) {267 chiffre.frame(maxWidth: 150, alignment: .leading)268 if s.points.count > 1 { CourbeWidget(points: s.points, couleur: s.id.couleur).frame(maxWidth: .infinity, maxHeight: .infinity) }269 }270 }271 }272 }273}274275/// La courbe du pouls : un trait à la couleur du site, sur sa ligne de sol.276struct CourbeWidget: View {277 let points: [Double]278 let couleur: Color279 var body: some View {280 Canvas { ctx, t in281 guard points.count > 1, let mn = points.min(), let mx = points.max() else { return }282 let e = mx - mn283 func pt(_ i: Int) -> CGPoint {284 CGPoint(x: 1 + (t.width - 5) * CGFloat(i) / CGFloat(points.count - 1),285 y: e == 0 ? t.height / 2 : 3 + (t.height - 8) * (1 - CGFloat((points[i] - mn) / e)))286 }287 ctx.fill(Path(CGRect(x: 0, y: t.height - 1, width: t.width, height: 1)), with: .color(Ka.filet2))288 var p = Path()289 p.move(to: pt(0))290 for i in 1..<points.count { p.addLine(to: pt(i)) }291 ctx.stroke(p, with: .color(couleur), style: StrokeStyle(lineWidth: 1.6, lineCap: .round, lineJoin: .round))292 let f = pt(points.count - 1)293 ctx.fill(Path(ellipseIn: CGRect(x: f.x - 2.5, y: f.y - 2.5, width: 5, height: 5)), with: .color(couleur))294 }295 .accessibilityHidden(true)296 }297}298