Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Vrai-Prix iOS9// File : VraiPrixWidgets/VraiPrixWidgets.swift10// Description : deux widgets : « Ventes récentes » (prix de vente réels du11// registre) et « Marché local » (prix payé médian et12// indice). Chaque chiffre dit sa nature ; aucun montant13// inventé, aucun compteur animé.14// Module : VraiPrixWidgets15// Repository : https://git.spboucher.ai/vrai-prix-ios-v316// Project Website : https://www.vrai-prix.com17// Created : 2026-11-2818// Last Modified : 2026-11-2819//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author : Simon-Pierre Boucher25// Position : Professor of Finance26// Institution : Université du Québec en Outaouais (UQO)27// Department : Département des sciences administratives28// Organization : SP Boucher29//30// Website : https://spboucher.ai31// Git : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General : info@spboucher.ai38// Professional : contact@spboucher.ai39// Direct : simon@spboucher.ai40// Research : research@spboucher.ai41// Development : dev@spboucher.ai42// Support : support@spboucher.ai43// Security/Admin : admin@spboucher.ai44// Notifications : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification : Public71// Distribution : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License : None specified (no license file in this repository)85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import AppIntents93import SwiftUI94import WidgetKit9596private enum WTheme {97 static func c(_ light: UInt32, _ dark: UInt32) -> Color {98 Color(uiColor: UIColor { t in99 let h = t.userInterfaceStyle == .dark ? dark : light100 return UIColor(red: CGFloat((h >> 16) & 0xFF) / 255, green: CGFloat((h >> 8) & 0xFF) / 255, blue: CGFloat(h & 0xFF) / 255, alpha: 1)101 })102 }103 static let bg = c(0xF3F2ED, 0x15171C)104 static let ink = c(0x15171C, 0xF1EFE9)105 static let ink2 = c(0x43464F, 0xC6C4BD)106 static let ink3 = c(0x585B64, 0xA9ACB4)107 static let line = c(0xDDD9CE, 0x2F333D)108 static let plumb = c(0x2540A6, 0x6C98F8)109 static let up = c(0x8C5800, 0xE3AE55)110 static let down = c(0x0E5F7A, 0x5FC3D4)111}112113/// Le symbole « Aplomb » réduit : le gabarit d'une maison et le fil à plomb qui tombe du faîte.114private struct AplombGlyph: View {115 var body: some View {116 Canvas { ctx, size in117 let w = size.width, h = size.height118 var house = Path()119 house.move(to: CGPoint(x: w * 0.08, y: h * 0.96)); house.addLine(to: CGPoint(x: w * 0.08, y: h * 0.46))120 house.addLine(to: CGPoint(x: w * 0.5, y: h * 0.06)); house.addLine(to: CGPoint(x: w * 0.92, y: h * 0.46))121 house.addLine(to: CGPoint(x: w * 0.92, y: h * 0.96))122 ctx.stroke(house, with: .color(WTheme.ink), style: StrokeStyle(lineWidth: max(1.4, w * 0.11), lineCap: .butt, lineJoin: .miter))123 var fil = Path(); fil.move(to: CGPoint(x: w * 0.5, y: h * 0.2)); fil.addLine(to: CGPoint(x: w * 0.5, y: h * 0.58))124 ctx.stroke(fil, with: .color(WTheme.ink), lineWidth: max(1, w * 0.06))125 var plumb = Path()126 plumb.move(to: CGPoint(x: w * 0.36, y: h * 0.58)); plumb.addLine(to: CGPoint(x: w * 0.64, y: h * 0.58))127 plumb.addLine(to: CGPoint(x: w * 0.5, y: h * 0.96)); plumb.closeSubpath()128 ctx.fill(plumb, with: .color(WTheme.plumb))129 }130 .accessibilityHidden(true)131 }132}133134private struct WidgetHeader: View {135 let title: String136 let place: String137 var body: some View {138 HStack(spacing: 7) {139 AplombGlyph().frame(width: 15, height: 16)140 VStack(alignment: .leading, spacing: 0) {141 Text(title).font(.system(size: 10, weight: .semibold)).tracking(0.8).textCase(.uppercase).foregroundStyle(WTheme.ink3)142 Text(place).font(.system(size: 13, weight: .semibold)).foregroundStyle(WTheme.ink).lineLimit(1)143 }144 }145 }146}147148private struct Unavailable: View {149 var body: some View {150 Text("Données indisponibles pour le moment.").font(.caption).foregroundStyle(WTheme.ink3)151 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)152 }153}154155// MARK: - Ventes récentes156157struct RecentSalesEntry: TimelineEntry {158 let date: Date159 let placeName: String160 let data: SharedAPI.RecentSales?161}162163struct RecentSalesProvider: AppIntentTimelineProvider {164 func placeholder(in context: Context) -> RecentSalesEntry { RecentSalesEntry(date: .now, placeName: "Québec", data: nil) }165 func entry(for c: RecentSalesConfiguration) async -> RecentSalesEntry {166 RecentSalesEntry(date: .now, placeName: c.place?.name ?? "Tout le Québec", data: try? await SharedAPI.recentSales(place: c.place?.ref))167 }168 func snapshot(for configuration: RecentSalesConfiguration, in context: Context) async -> RecentSalesEntry { await entry(for: configuration) }169 func timeline(for configuration: RecentSalesConfiguration, in context: Context) async -> Timeline<RecentSalesEntry> {170 let e = await entry(for: configuration)171 return Timeline(entries: [e], policy: .after(.now.addingTimeInterval(e.data == nil ? 900 : 4 * 3600)))172 }173}174175struct RecentSalesView: View {176 @Environment(\.widgetFamily) private var family177 let entry: RecentSalesEntry178179 var body: some View {180 VStack(alignment: .leading, spacing: family == .systemSmall ? 6 : 8) {181 WidgetHeader(title: "Ventes récentes", place: entry.placeName)182 if let d = entry.data {183 if d.items.isEmpty {184 Text("Aucune vente publiée ici depuis 90 jours.").font(.caption).foregroundStyle(WTheme.ink2)185 Spacer(minLength: 0)186 } else if family == .systemSmall, let s = d.items.first {187 Spacer(minLength: 0)188 Text(SharedFmt.money(s.price)).font(.system(size: 24, weight: .semibold)).monospacedDigit().foregroundStyle(WTheme.ink)189 .minimumScaleFactor(0.6).lineLimit(1)190 Text(s.street).font(.caption2.weight(.medium)).foregroundStyle(WTheme.ink2).lineLimit(1)191 Text([s.city, SharedFmt.day(iso: s.date)].compactMap { $0 }.joined(separator: " · ")).font(.caption2).foregroundStyle(WTheme.ink3).lineLimit(1)192 Text("Prix de vente réel").font(.system(size: 9)).foregroundStyle(WTheme.ink3)193 } else {194 Text(d.marketOnly ? "Prix de vente réels, ventes de marché" : "Prix de vente réels, publiés au registre")195 .font(.caption2).foregroundStyle(WTheme.ink3).lineLimit(1)196 VStack(spacing: 0) {197 ForEach(d.items.prefix(family == .systemLarge ? 6 : 3)) { s in198 Link(destination: s.url) {199 HStack(alignment: .firstTextBaseline, spacing: 8) {200 Text(SharedFmt.money(s.price)).font(.system(size: 14, weight: .semibold)).monospacedDigit().foregroundStyle(WTheme.ink)201 .frame(width: 84, alignment: .leading)202 Text(s.street).font(.caption).foregroundStyle(WTheme.ink2).lineLimit(1)203 Spacer(minLength: 4)204 Text(SharedFmt.day(iso: s.date) ?? "").font(.caption2).monospacedDigit().foregroundStyle(WTheme.ink3)205 }206 .padding(.vertical, family == .systemLarge ? 8 : 5)207 .overlay(alignment: .top) { Rectangle().fill(WTheme.line).frame(height: 1) }208 }209 .accessibilityLabel("Vendue \(SharedFmt.money(s.price)), \(s.street), \(s.city)")210 }211 }212 Spacer(minLength: 0)213 }214 } else {215 Unavailable()216 }217 }218 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)219 .widgetURL(URL(string: "vraiprix://ventes")!)220 .containerBackground(WTheme.bg, for: .widget)221 }222}223224struct RecentSalesWidget: Widget {225 var body: some WidgetConfiguration {226 AppIntentConfiguration(kind: "com.spboucher.vraiprix.v2.ventes", intent: RecentSalesConfiguration.self, provider: RecentSalesProvider()) { entry in227 RecentSalesView(entry: entry)228 }229 .configurationDisplayName("Ventes récentes")230 .description("Les dernières ventes publiées au registre : des prix de vente réels.")231 .supportedFamilies([.systemSmall, .systemMedium, .systemLarge])232 }233}234235// MARK: - Marché local236237struct MarketEntry: TimelineEntry {238 let date: Date239 let placeName: String240 let data: SharedAPI.MarketBrief?241 let url: URL242}243244struct MarketProvider: AppIntentTimelineProvider {245 func placeholder(in context: Context) -> MarketEntry { MarketEntry(date: .now, placeName: "Québec", data: nil, url: URL(string: "vraiprix://marche")!) }246 func entry(for c: LocalMarketConfiguration) async -> MarketEntry {247 let data = try? await SharedAPI.market(place: c.place?.ref)248 let url = c.place.flatMap { URL(string: "vraiprix://municipalite/" + $0.slug) } ?? URL(string: "vraiprix://marche")!249 return MarketEntry(date: .now, placeName: data?.placeName ?? c.place?.name ?? "Québec", data: data, url: url)250 }251 func snapshot(for configuration: LocalMarketConfiguration, in context: Context) async -> MarketEntry { await entry(for: configuration) }252 func timeline(for configuration: LocalMarketConfiguration, in context: Context) async -> Timeline<MarketEntry> {253 let e = await entry(for: configuration)254 return Timeline(entries: [e], policy: .after(.now.addingTimeInterval(e.data == nil ? 900 : 12 * 3600)))255 }256}257258struct MarketWidgetView: View {259 @Environment(\.widgetFamily) private var family260 let entry: MarketEntry261262 var body: some View {263 VStack(alignment: .leading, spacing: 6) {264 WidgetHeader(title: "Marché", place: entry.placeName)265 if let d = entry.data {266 Spacer(minLength: 0)267 HStack(alignment: .firstTextBaseline, spacing: 18) {268 VStack(alignment: .leading, spacing: 1) {269 Text(d.medianPaid == nil ? "—" : SharedFmt.money(d.medianPaid)).font(.system(size: 26, weight: .semibold)).monospacedDigit()270 .foregroundStyle(WTheme.ink).minimumScaleFactor(0.6).lineLimit(1)271 Text(d.medianPaid == nil ? "effectif insuffisant" : "prix payé médian, \(d.window)").font(.caption2).foregroundStyle(WTheme.ink3)272 }273 if family != .systemSmall, let n = d.sales {274 VStack(alignment: .leading, spacing: 1) {275 Text(SharedFmt.int(n)).font(.system(size: 20, weight: .semibold)).monospacedDigit().foregroundStyle(WTheme.ink)276 Text("ventes réelles").font(.caption2).foregroundStyle(WTheme.ink3)277 }278 }279 }280 if let c = d.indexChangePct {281 HStack(spacing: 4) {282 Image(systemName: abs(c) < 0.05 ? "equal" : c > 0 ? "arrow.up.right" : "arrow.down.right").font(.system(size: 10, weight: .bold))283 Text(SharedFmt.points(c)).font(.caption.weight(.semibold)).monospacedDigit()284 if family != .systemSmall {285 Text("indice des maisons sur un an" + (d.indexPlace.map { " (\($0))" } ?? "")).font(.caption2).foregroundStyle(WTheme.ink3).lineLimit(1)286 }287 }288 .foregroundStyle(abs(c) < 0.05 ? WTheme.ink3 : c > 0 ? WTheme.up : WTheme.down)289 .accessibilityElement(children: .combine)290 .accessibilityLabel("Indice des prix de vente des maisons, sur un an : \(SharedFmt.points(c))")291 } else if family != .systemSmall, let v = d.medianValue {292 Text("Valeur estimée médiane : \(SharedFmt.money(v))").font(.caption2).monospacedDigit().foregroundStyle(WTheme.ink3).lineLimit(1)293 }294 if family == .systemSmall { Text("Prix de vente réels").font(.system(size: 9)).foregroundStyle(WTheme.ink3) }295 } else {296 Unavailable()297 }298 }299 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)300 .widgetURL(entry.url)301 .containerBackground(WTheme.bg, for: .widget)302 }303}304305struct LocalMarketWidget: Widget {306 var body: some WidgetConfiguration {307 AppIntentConfiguration(kind: "com.spboucher.vraiprix.v2.marche", intent: LocalMarketConfiguration.self, provider: MarketProvider()) { entry in308 MarketWidgetView(entry: entry)309 }310 .configurationDisplayName("Marché local")311 .description("Le prix payé médian d'une municipalité et la variation de l'indice des prix de vente.")312 .supportedFamilies([.systemSmall, .systemMedium])313 }314}315316@main317struct VraiPrixWidgetBundle: WidgetBundle {318 var body: some Widget {319 RecentSalesWidget()320 LocalMarketWidget()321 }322}323