SPB Git

Repository Public

ImmoKaWidgets.swift 19.2 KB 421 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKaWidgets/ImmoKaWidgets.swift10// Description      : widgets de l'écran d'accueil et de l'écran verrouillé —11//                    nouvelles inscriptions d'une ville, marché local. Aplats12//                    de la marque (chaux, charbon, ardoise, un seul rouge),13//                    sans dégradé ni verre.14// Module           : ImmoKaWidgets15// Repository       : https://git.spboucher.ai/immo-ka-ios-v316// Project Website  : https://www.immo-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// MARK: - Réglage : la ville9798struct PlaceConfigurationIntent: WidgetConfigurationIntent {99    static let title: LocalizedStringResource = "Lieu"100    static let description = IntentDescription("La ville dont le widget montre les propriétés. Laissez vide pour tout le Québec.")101102    @Parameter(title: "Ville")103    var city: String?104}105106// MARK: - Marque107108enum WidgetPalette {109    static func hex(_ light: UInt32, _ dark: UInt32) -> Color {110        Color(uiColor: UIColor { t in111            let h = t.userInterfaceStyle == .dark ? dark : light112            return UIColor(red: CGFloat((h >> 16) & 0xFF) / 255, green: CGFloat((h >> 8) & 0xFF) / 255, blue: CGFloat(h & 0xFF) / 255, alpha: 1)113        })114    }115    static let bg = hex(0xF6F3EC, 0x14161A)116    static let ink = hex(0x1B1D22, 0xF2EFE8)117    static let ink2 = hex(0x474A52, 0xBDBBB4)118    static let ink3 = hex(0x5D6068, 0x9DA0A8)119    static let line = hex(0xE4E0D6, 0x282C32)120    static let brand = hex(0x2B4A63, 0x9DBEDA)121    static let door = hex(0xD12C37, 0xE04A52)122}123124/// Le symbole « Larmier » : la maison et sa porte rouge entrouverte (grille 64, mêmes points que l'app).125struct WidgetHouse: View {126    var body: some View {127        Canvas { ctx, size in128            let u = min(size.width, size.height) / 64129            let t = CGAffineTransform(scaleX: u, y: u)130            var p = Path()131            p.move(to: CGPoint(x: 32, y: 6.5)); p.addLine(to: CGPoint(x: 41.5, y: 15.3)); p.addLine(to: CGPoint(x: 41.5, y: 9.5))132            p.addLine(to: CGPoint(x: 47, y: 9.5)); p.addLine(to: CGPoint(x: 47, y: 20.4)); p.addLine(to: CGPoint(x: 49.7, y: 22.9))133            p.addCurve(to: CGPoint(x: 59.8, y: 27.9), control1: CGPoint(x: 52.7, y: 25.7), control2: CGPoint(x: 55.7, y: 27.2))134            p.addCurve(to: CGPoint(x: 59.5, y: 31.5), control1: CGPoint(x: 62.1, y: 28.3), control2: CGPoint(x: 61.9, y: 31.5))135            p.addLine(to: CGPoint(x: 53, y: 31.5)); p.addLine(to: CGPoint(x: 53, y: 58)); p.addLine(to: CGPoint(x: 11, y: 58))136            p.addLine(to: CGPoint(x: 11, y: 31.5)); p.addLine(to: CGPoint(x: 4.5, y: 31.5))137            p.addCurve(to: CGPoint(x: 4.2, y: 27.9), control1: CGPoint(x: 2.1, y: 31.5), control2: CGPoint(x: 1.9, y: 28.3))138            p.addCurve(to: CGPoint(x: 14.3, y: 22.9), control1: CGPoint(x: 8.3, y: 27.2), control2: CGPoint(x: 11.3, y: 25.7))139            p.closeSubpath()140            // embrasure en réserve141            p.addRoundedRect(in: CGRect(x: 23, y: 28, width: 18, height: 30), cornerSize: CGSize(width: 1.5, height: 1.5))142            ctx.fill(p.applying(t), with: .color(WidgetPalette.ink), style: FillStyle(eoFill: true))143            // battant du logo au repos (40°) : bord libre en x 36,5, de y 31,3 à y 55,2144            var d = Path()145            d.move(to: CGPoint(x: 23, y: 28)); d.addLine(to: CGPoint(x: 36.5, y: 31.3)); d.addLine(to: CGPoint(x: 36.5, y: 55.2)); d.addLine(to: CGPoint(x: 23, y: 58))146            d.closeSubpath()147            ctx.fill(d.applying(t), with: .color(WidgetPalette.door))148            var s = Path()149            s.move(to: CGPoint(x: 5, y: 59.5)); s.addLine(to: CGPoint(x: 59, y: 59.5))150            ctx.stroke(s.applying(t), with: .color(WidgetPalette.ink), style: StrokeStyle(lineWidth: 3 * u, lineCap: .round))151        }152        .accessibilityHidden(true)153    }154}155156struct WidgetHeader: View {157    let title: String158    var body: some View {159        HStack(spacing: 6) {160            WidgetHouse().frame(width: 16, height: 16)161            Text(title).font(.caption2.weight(.semibold)).foregroundStyle(WidgetPalette.ink3).lineLimit(1)162            Spacer(minLength: 0)163        }164    }165}166167/// Ce que montre un widget quand le service n'a pas répondu : pas de chiffre, la raison.168struct WidgetUnavailable: View {169    let reason: String170    var body: some View {171        VStack(alignment: .leading, spacing: 6) {172            Image(systemName: "wifi.slash").font(.footnote).foregroundStyle(WidgetPalette.ink3)173            Text(reason).font(.caption).foregroundStyle(WidgetPalette.ink2).fixedSize(horizontal: false, vertical: true)174        }175        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)176    }177}178179func widgetReason(_ error: Error) -> String {180    switch error as? WidgetAPIError {181    case .notFound: "Ville inconnue d'Immo-Ka. Vérifiez son nom dans les réglages du widget."182    case .offline: "Hors ligne. Les chiffres reviendront avec la connexion."183    default: "Immo-Ka n'a pas répondu. Nouvel essai dans une heure."184    }185}186187// MARK: - Nouvelles inscriptions188189struct NewListingsEntry: TimelineEntry {190    let date: Date191    var data: NewListingsData?192    var reason: String?193    var city: String?194}195196struct NewListingsProvider: AppIntentTimelineProvider {197    func placeholder(in context: Context) -> NewListingsEntry { NewListingsEntry(date: .now) }198199    func snapshot(for configuration: PlaceConfigurationIntent, in context: Context) async -> NewListingsEntry {200        await entry(configuration)201    }202203    func timeline(for configuration: PlaceConfigurationIntent, in context: Context) async -> Timeline<NewListingsEntry> {204        let e = await entry(configuration)205        // une heure quand tout va bien ; vingt minutes après un échec206        return Timeline(entries: [e], policy: .after(.now.addingTimeInterval(e.data == nil ? 1200 : 3600)))207    }208209    private func entry(_ c: PlaceConfigurationIntent) async -> NewListingsEntry {210        do { return NewListingsEntry(date: .now, data: try await WidgetAPI.newListings(city: c.city), city: c.city) }211        catch { return NewListingsEntry(date: .now, reason: widgetReason(error), city: c.city) }212    }213}214215struct NewListingsView: View {216    let entry: NewListingsEntry217    @Environment(\.widgetFamily) private var family218219    private var place: String { entry.data?.city ?? entry.city.flatMap { $0.isEmpty ? nil : $0 } ?? "Québec" }220    private var searchURL: URL {221        var c = URLComponents(); c.scheme = "immoka"; c.host = "recherche"222        if let city = entry.data?.city { c.queryItems = [URLQueryItem(name: "city", value: city)] }223        return c.url ?? URL(string: "immoka://recherche")!224    }225226    var body: some View {227        VStack(alignment: .leading, spacing: 8) {228            WidgetHeader(title: "Nouvelles · \(place)")229            if let d = entry.data {230                if family == .systemSmall { small(d) } else { medium(d) }231            } else if let r = entry.reason {232                WidgetUnavailable(reason: r)233            } else {234                // gabarit pendant le premier chargement : des filets, aucun chiffre235                VStack(alignment: .leading, spacing: 8) {236                    ForEach(0..<3, id: \.self) { _ in RoundedRectangle(cornerRadius: 3).fill(WidgetPalette.line).frame(height: 12) }237                }238                .frame(maxHeight: .infinity, alignment: .top)239            }240        }241        .widgetURL(searchURL)242        .containerBackground(WidgetPalette.bg, for: .widget)243    }244245    @ViewBuilder246    private func small(_ d: NewListingsData) -> some View {247        if let first = d.items.first {248            VStack(alignment: .leading, spacing: 3) {249                Text(first.price.map { WidgetFormat.money($0) } ?? "Prix sur demande")250                    .font(.system(.title3, design: .default).weight(.semibold)).monospacedDigit().foregroundStyle(WidgetPalette.ink)251                    .minimumScaleFactor(0.7).lineLimit(1)252                Text(first.address).font(.caption.weight(.medium)).foregroundStyle(WidgetPalette.ink).lineLimit(2)253                Text([first.type, d.city == nil ? first.city : nil].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · "))254                    .font(.caption2).foregroundStyle(WidgetPalette.ink3).lineLimit(1)255            }256            Spacer(minLength: 0)257            if let n = d.newThisWeek {258                Text("\(WidgetFormat.int(n)) depuis 7 jours").font(.caption2.weight(.medium)).monospacedDigit().foregroundStyle(WidgetPalette.brand)259            }260        } else {261            Text("Aucune nouvelle inscription.").font(.caption).foregroundStyle(WidgetPalette.ink2)262            Spacer(minLength: 0)263        }264    }265266    @ViewBuilder267    private func medium(_ d: NewListingsData) -> some View {268        if d.items.isEmpty {269            Text("Aucune nouvelle inscription.").font(.caption).foregroundStyle(WidgetPalette.ink2)270            Spacer(minLength: 0)271        } else {272            VStack(spacing: 0) {273                ForEach(Array(d.items.prefix(3).enumerated()), id: \.element.id) { i, l in274                    Link(destination: l.url) {275                        HStack(alignment: .firstTextBaseline, spacing: 8) {276                            VStack(alignment: .leading, spacing: 1) {277                                Text(l.address).font(.caption.weight(.medium)).foregroundStyle(WidgetPalette.ink).lineLimit(1)278                                Text([l.type, d.city == nil ? l.city : nil].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · "))279                                    .font(.caption2).foregroundStyle(WidgetPalette.ink3).lineLimit(1)280                            }281                            Spacer(minLength: 4)282                            Text(l.price.map { WidgetFormat.money($0) } ?? "sur demande")283                                .font(.caption.weight(.semibold)).monospacedDigit().foregroundStyle(WidgetPalette.ink)284                        }285                        .padding(.vertical, 4)286                    }287                    if i < min(d.items.count, 3) - 1 { Rectangle().fill(WidgetPalette.line).frame(height: 1) }288                }289            }290            Spacer(minLength: 0)291            if let n = d.newThisWeek {292                Text("\(WidgetFormat.int(n)) nouvelles inscriptions depuis 7 jours").font(.caption2.weight(.medium)).monospacedDigit().foregroundStyle(WidgetPalette.brand)293            }294        }295    }296}297298struct NewListingsWidget: Widget {299    var body: some WidgetConfiguration {300        AppIntentConfiguration(kind: "com.spboucher.immoka.nouvelles", intent: PlaceConfigurationIntent.self, provider: NewListingsProvider()) { entry in301            NewListingsView(entry: entry)302        }303        .configurationDisplayName("Nouvelles inscriptions")304        .description("Les dernières propriétés repérées par Immo-Ka dans une ville.")305        .supportedFamilies([.systemSmall, .systemMedium])306    }307}308309// MARK: - Marché local310311struct MarketEntry: TimelineEntry {312    let date: Date313    var data: MarketData?314    var reason: String?315    var city: String?316}317318struct MarketProvider: AppIntentTimelineProvider {319    func placeholder(in context: Context) -> MarketEntry { MarketEntry(date: .now) }320    func snapshot(for configuration: PlaceConfigurationIntent, in context: Context) async -> MarketEntry { await entry(configuration) }321    func timeline(for configuration: PlaceConfigurationIntent, in context: Context) async -> Timeline<MarketEntry> {322        let e = await entry(configuration)323        // le portrait de marché change une fois par jour : trois heures suffisent324        return Timeline(entries: [e], policy: .after(.now.addingTimeInterval(e.data == nil ? 1200 : 3 * 3600)))325    }326    private func entry(_ c: PlaceConfigurationIntent) async -> MarketEntry {327        do { return MarketEntry(date: .now, data: try await WidgetAPI.market(city: c.city), city: c.city) }328        catch { return MarketEntry(date: .now, reason: widgetReason(error), city: c.city) }329    }330}331332struct MarketWidgetView: View {333    let entry: MarketEntry334    @Environment(\.widgetFamily) private var family335336    private var url: URL {337        if let s = entry.data?.slug { return URL(string: "immoka://marche/\(s)") ?? URL(string: "immoka://marche")! }338        return URL(string: "immoka://marche")!339    }340341    var body: some View {342        Group {343            if family == .accessoryRectangular { lockScreen } else { home }344        }345        .widgetURL(url)346    }347348    private var home: some View {349        VStack(alignment: .leading, spacing: 8) {350            WidgetHeader(title: "Marché · \(entry.data?.place ?? entry.city.flatMap { $0.isEmpty ? nil : $0 } ?? "Québec")")351            if let d = entry.data {352                VStack(alignment: .leading, spacing: 2) {353                    Text(d.askMedian.map { WidgetFormat.money($0) } ?? "Inconnu")354                        .font(.system(.title3).weight(.semibold)).monospacedDigit()355                        .foregroundStyle(d.askMedian == nil ? WidgetPalette.ink3 : WidgetPalette.ink).minimumScaleFactor(0.7).lineLimit(1)356                    Text("prix demandé médian").font(.caption2).foregroundStyle(WidgetPalette.ink3)357                }358                Spacer(minLength: 0)359                if family == .systemMedium {360                    HStack(alignment: .top, spacing: 18) {361                        stat(d.inventory.map { WidgetFormat.int($0) }, "à vendre")362                        stat(d.new30d.map { WidgetFormat.int($0) }, "nouvelles, 30 jours")363                        if let y = d.indexYoY {364                            stat((y >= 0 ? "+" : "−") + abs(y).formatted(.number.precision(.fractionLength(1)).locale(WidgetFormat.locale)) + " %", "prix de vente, 1 an")365                        }366                    }367                } else {368                    Text([d.inventory.map { "\(WidgetFormat.int($0)) à vendre" }, WidgetFormat.shortDay(d.asOf)].compactMap { $0 }.joined(separator: " · "))369                        .font(.caption2).monospacedDigit().foregroundStyle(WidgetPalette.ink2).lineLimit(1)370                }371            } else if let r = entry.reason {372                WidgetUnavailable(reason: r)373            } else {374                RoundedRectangle(cornerRadius: 3).fill(WidgetPalette.line).frame(width: 110, height: 20)375                Spacer(minLength: 0)376            }377        }378        .containerBackground(WidgetPalette.bg, for: .widget)379    }380381    private func stat(_ value: String?, _ label: String) -> some View {382        VStack(alignment: .leading, spacing: 1) {383            Text(value ?? "Inconnu").font(.caption.weight(.semibold)).monospacedDigit().foregroundStyle(value == nil ? WidgetPalette.ink3 : WidgetPalette.ink)384            Text(label).font(.caption2).foregroundStyle(WidgetPalette.ink3).lineLimit(1)385        }386    }387388    private var lockScreen: some View {389        VStack(alignment: .leading, spacing: 1) {390            Text(entry.data?.place ?? "Immo-Ka").font(.caption2.weight(.semibold)).lineLimit(1)391            if let d = entry.data, let m = d.askMedian {392                Text(WidgetFormat.money(m)).font(.headline).monospacedDigit().lineLimit(1)393                Text("demandé médian\(d.inventory.map { " · \(WidgetFormat.int($0)) à vendre" } ?? "")").font(.caption2).lineLimit(1)394            } else {395                Text(entry.reason == nil ? "Chargement" : "Indisponible").font(.caption)396            }397        }398        .frame(maxWidth: .infinity, alignment: .leading)399        .containerBackground(.clear, for: .widget)400    }401}402403struct MarketWidget: Widget {404    var body: some WidgetConfiguration {405        AppIntentConfiguration(kind: "com.spboucher.immoka.marche", intent: PlaceConfigurationIntent.self, provider: MarketProvider()) { entry in406            MarketWidgetView(entry: entry)407        }408        .configurationDisplayName("Marché local")409        .description("Le prix demandé médian et le nombre de propriétés à vendre dans une ville.")410        .supportedFamilies([.systemSmall, .systemMedium, .accessoryRectangular])411    }412}413414@main415struct ImmoKaWidgetBundle: WidgetBundle {416    var body: some Widget {417        NewListingsWidget()418        MarketWidget()419    }420}421
Files main
Menu

Theme