Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Lou-Ka iOS9// File : LouKaWidgets/LouKaWidgets.swift10// Description : widgets d'écran d'accueil — « Nouvelles annonces » et «11// Marché local », pour un lieu choisi. Données réelles de12// l'API v3 ; en cas de panne, le widget le dit au lieu13// d'afficher un chiffre.14// Module : LouKaWidgets15// Repository : https://git.spboucher.ai/lou-ka-ios-v316// Project Website : https://www.lou-ka.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 WidgetKit9596// Jetons du Design System V3 (clair / sombre), sans dépendance à l'app.97private enum WTheme {98 static func c(_ light: UInt32, _ dark: UInt32) -> Color {99 Color(uiColor: UIColor { t in100 let h = t.userInterfaceStyle == .dark ? dark : light101 return UIColor(red: CGFloat((h >> 16) & 0xFF) / 255, green: CGFloat((h >> 8) & 0xFF) / 255, blue: CGFloat(h & 0xFF) / 255, alpha: 1)102 })103 }104 static let bg = c(0xF7F6F0, 0x111815)105 static let ink = c(0x181C1A, 0xF1F3EE)106 static let ink2 = c(0x454D48, 0xB9C1BA)107 static let ink3 = c(0x5C645E, 0x97A199)108 static let line = c(0xE3E4DC, 0x262F2A)109 static let brand = c(0x245B48, 0x86C2A4)110 static let up = c(0x8A570C, 0xD9A85C)111 static let down = c(0x17686B, 0x7CC4C2)112 static let frame = c(0xE96B32, 0xEE7C48)113 static let door = c(0x181C1A, 0xF1F3EE)114}115116/// Symbole « Seuil » : chambranle terracotta, battant entrouvert, seuil.117private struct DoorGlyph: View {118 var body: some View {119 Canvas { ctx, size in120 let w = size.height * 39 / 56.5, x0 = (size.width - w) / 2, t = w * 0.128121 var frame = Path()122 frame.addRect(CGRect(x: x0, y: 0, width: t, height: size.height))123 frame.addRect(CGRect(x: x0 + w - t, y: 0, width: t, height: size.height))124 frame.addRect(CGRect(x: x0, y: 0, width: w, height: t))125 ctx.fill(frame, with: .color(WTheme.frame))126 // battant entrouvert : trapèze charnière à gauche127 var leaf = Path()128 let l = x0 + t, r = x0 + t + (w - 2 * t) * 0.72129 leaf.move(to: CGPoint(x: l, y: t)); leaf.addLine(to: CGPoint(x: r, y: t + size.height * 0.07))130 leaf.addLine(to: CGPoint(x: r, y: size.height)); leaf.addLine(to: CGPoint(x: l, y: size.height)); leaf.closeSubpath()131 ctx.fill(leaf, with: .color(WTheme.door))132 }133 .accessibilityHidden(true)134 }135}136137private struct WidgetHeader: View {138 let title: String139 let place: String140 var body: some View {141 HStack(spacing: 7) {142 DoorGlyph().frame(width: 12, height: 17)143 VStack(alignment: .leading, spacing: 0) {144 Text(title).font(.system(size: 10, weight: .semibold)).tracking(0.8).textCase(.uppercase).foregroundStyle(WTheme.ink3)145 Text(place).font(.system(size: 13, weight: .semibold)).foregroundStyle(WTheme.ink).lineLimit(1)146 }147 }148 }149}150151private struct Unavailable: View {152 var body: some View {153 Text("Données indisponibles pour le moment.").font(.caption).foregroundStyle(WTheme.ink3)154 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)155 }156}157158// MARK: - Nouvelles annonces159160struct NewListingsEntry: TimelineEntry {161 let date: Date162 let placeName: String163 let rooms: String?164 let data: SharedAPI.NewListings?165 let exploreURL: URL166}167168struct NewListingsProvider: AppIntentTimelineProvider {169 func placeholder(in context: Context) -> NewListingsEntry {170 NewListingsEntry(date: .now, placeName: "Québec", rooms: nil, data: nil, exploreURL: URL(string: "louka://recherche?new_days=3&sort=recent")!)171 }172173 func entry(for c: NewListingsConfiguration) async -> NewListingsEntry {174 let ref = c.place?.ref175 let data = try? await SharedAPI.newListings(place: ref, rooms: c.rooms?.rooms)176 var comps = URLComponents(string: "louka://recherche")!177 var q = SharedAPI.searchParams(ref).compactMap { k, v in v.map { URLQueryItem(name: k, value: $0) } }178 q += [URLQueryItem(name: "new_days", value: "3"), URLQueryItem(name: "sort", value: "recent")]179 if let r = c.rooms?.rooms { q.append(URLQueryItem(name: "rooms", value: String(r))) }180 comps.queryItems = q181 return NewListingsEntry(date: .now, placeName: c.place?.name ?? "Tout le Québec", rooms: c.rooms?.label, data: data,182 exploreURL: comps.url ?? URL(string: "louka://recherche")!)183 }184185 func snapshot(for configuration: NewListingsConfiguration, in context: Context) async -> NewListingsEntry { await entry(for: configuration) }186187 func timeline(for configuration: NewListingsConfiguration, in context: Context) async -> Timeline<NewListingsEntry> {188 let e = await entry(for: configuration)189 // l'index est reconstruit environ chaque heure ; en cas de panne, nouvel essai plus tôt190 return Timeline(entries: [e], policy: .after(.now.addingTimeInterval(e.data == nil ? 900 : 3600)))191 }192}193194struct NewListingsView: View {195 @Environment(\.widgetFamily) private var family196 let entry: NewListingsEntry197198 var body: some View {199 VStack(alignment: .leading, spacing: family == .systemSmall ? 6 : 8) {200 WidgetHeader(title: "Nouveautés" + (entry.rooms.map { " · \($0)" } ?? ""), place: entry.placeName)201 if let d = entry.data {202 if family == .systemSmall {203 Spacer(minLength: 0)204 Text(SharedFmt.int(d.total)).font(.system(size: 34, weight: .semibold)).monospacedDigit().foregroundStyle(WTheme.ink)205 .minimumScaleFactor(0.6).lineLimit(1)206 Text(d.total > 1 ? "logements vus depuis 3 jours" : "logement vu depuis 3 jours").font(.caption2).foregroundStyle(WTheme.ink3)207 if let first = d.items.first {208 Text("Dernier : \(SharedFmt.money(first.price)) · \(first.unit)").font(.caption2.weight(.medium)).monospacedDigit()209 .foregroundStyle(WTheme.ink2).lineLimit(1)210 }211 } else {212 Text("\(SharedFmt.int(d.total)) \(d.total > 1 ? "logements vus" : "logement vu") pour la première fois depuis 3 jours")213 .font(.caption2).monospacedDigit().foregroundStyle(WTheme.ink3).lineLimit(1)214 if d.items.isEmpty {215 Text("Aucune nouvelle annonce ici pour le moment.").font(.caption).foregroundStyle(WTheme.ink2)216 Spacer(minLength: 0)217 } else {218 VStack(spacing: 0) {219 ForEach(d.items.prefix(family == .systemLarge ? 6 : 3)) { l in220 Link(destination: l.url) {221 HStack(alignment: .firstTextBaseline, spacing: 8) {222 Text(SharedFmt.money(l.price)).font(.system(size: 14, weight: .semibold)).monospacedDigit().foregroundStyle(WTheme.ink)223 .frame(width: 66, alignment: .leading)224 Text(l.unit).font(.caption.weight(.medium)).foregroundStyle(WTheme.ink2).frame(width: 44, alignment: .leading)225 Text(l.place).font(.caption).foregroundStyle(WTheme.ink3).lineLimit(1)226 Spacer(minLength: 0)227 }228 .padding(.vertical, family == .systemLarge ? 8 : 5)229 .overlay(alignment: .top) { Rectangle().fill(WTheme.line).frame(height: 1) }230 }231 .accessibilityLabel("\(SharedFmt.money(l.price)), \(l.unit), \(l.place)")232 }233 }234 Spacer(minLength: 0)235 }236 }237 } else {238 Unavailable()239 }240 }241 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)242 .widgetURL(entry.exploreURL)243 .containerBackground(WTheme.bg, for: .widget)244 }245}246247struct NewListingsWidget: Widget {248 var body: some WidgetConfiguration {249 AppIntentConfiguration(kind: "com.spboucher.louka.v2.nouveautes", intent: NewListingsConfiguration.self, provider: NewListingsProvider()) { entry in250 NewListingsView(entry: entry)251 }252 .configurationDisplayName("Nouvelles annonces")253 .description("Les logements vus pour la première fois depuis trois jours.")254 .supportedFamilies([.systemSmall, .systemMedium, .systemLarge])255 }256}257258// MARK: - Marché local259260struct MarketEntry: TimelineEntry {261 let date: Date262 let placeName: String263 let data: SharedAPI.MarketBrief?264 let url: URL265}266267struct MarketProvider: AppIntentTimelineProvider {268 func placeholder(in context: Context) -> MarketEntry {269 MarketEntry(date: .now, placeName: "Québec", data: nil, url: URL(string: "louka://marche")!)270 }271 func entry(for c: LocalMarketConfiguration) async -> MarketEntry {272 let data = try? await SharedAPI.market(place: c.place?.ref)273 return MarketEntry(date: .now, placeName: data?.placeName ?? c.place?.name ?? "Québec", data: data, url: URL(string: "louka://marche")!)274 }275 func snapshot(for configuration: LocalMarketConfiguration, in context: Context) async -> MarketEntry { await entry(for: configuration) }276 func timeline(for configuration: LocalMarketConfiguration, in context: Context) async -> Timeline<MarketEntry> {277 let e = await entry(for: configuration)278 return Timeline(entries: [e], policy: .after(.now.addingTimeInterval(e.data == nil ? 900 : 6 * 3600)))279 }280}281282struct MarketWidgetView: View {283 @Environment(\.widgetFamily) private var family284 let entry: MarketEntry285286 var body: some View {287 VStack(alignment: .leading, spacing: 6) {288 WidgetHeader(title: "Marché affiché", place: entry.placeName)289 if let d = entry.data {290 Spacer(minLength: 0)291 HStack(alignment: .firstTextBaseline, spacing: 18) {292 VStack(alignment: .leading, spacing: 1) {293 Text(d.median == nil ? "—" : SharedFmt.money(d.median)).font(.system(size: 30, weight: .semibold)).monospacedDigit()294 .foregroundStyle(WTheme.ink).minimumScaleFactor(0.6).lineLimit(1)295 Text(d.median == nil ? "effectif insuffisant" : "loyer affiché médian").font(.caption2).foregroundStyle(WTheme.ink3)296 }297 if family != .systemSmall, let a = d.active {298 VStack(alignment: .leading, spacing: 1) {299 Text(SharedFmt.int(a)).font(.system(size: 20, weight: .semibold)).monospacedDigit().foregroundStyle(WTheme.ink)300 Text("annonces présentes").font(.caption2).foregroundStyle(WTheme.ink3)301 }302 }303 }304 if let c = d.changePct {305 HStack(spacing: 4) {306 Image(systemName: abs(c) < 0.05 ? "equal" : c > 0 ? "arrow.up.right" : "arrow.down.right").font(.system(size: 10, weight: .bold))307 Text(SharedFmt.points(c)).font(.caption.weight(.semibold)).monospacedDigit()308 if family != .systemSmall, let a = d.previousMonth, let b = d.currentMonth {309 Text("de \(a) à \(b), à sources constantes").font(.caption2).foregroundStyle(WTheme.ink3).lineLimit(1)310 }311 }312 .foregroundStyle(abs(c) < 0.05 ? WTheme.ink3 : c > 0 ? WTheme.up : WTheme.down)313 .accessibilityElement(children: .combine)314 .accessibilityLabel("Variation du loyer médian : \(SharedFmt.points(c))")315 }316 if family == .systemSmall {317 Text("Loyers demandés, non signés").font(.system(size: 9)).foregroundStyle(WTheme.ink3)318 } else {319 Text("Loyers demandés dans les annonces, pas les loyers signés.").font(.caption2).foregroundStyle(WTheme.ink3).lineLimit(1)320 }321 } else {322 Unavailable()323 }324 }325 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)326 .widgetURL(entry.url)327 .containerBackground(WTheme.bg, for: .widget)328 }329}330331struct LocalMarketWidget: Widget {332 var body: some WidgetConfiguration {333 AppIntentConfiguration(kind: "com.spboucher.louka.v2.marche", intent: LocalMarketConfiguration.self, provider: MarketProvider()) { entry in334 MarketWidgetView(entry: entry)335 }336 .configurationDisplayName("Marché local")337 .description("Le loyer affiché médian d'un lieu et sa variation d'un mois à l'autre.")338 .supportedFamilies([.systemSmall, .systemMedium])339 }340}341342@main343struct LouKaWidgetBundle: WidgetBundle {344 var body: some Widget {345 NewListingsWidget()346 LocalMarketWidget()347 }348}349