SPB Git

Repository Public

ManagersView.swift 21.8 KB 465 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka iOS9// File             : LouKa/Features/Managers/ManagersView.swift10// Description      : annuaire de tous les gestionnaires immobiliers —11//                    recherche, régions, tris ; accès villes et déménageurs.12// Module           : LouKa13// Repository       : https://git.spboucher.ai/lou-ka-ios-v314// Project Website  : https://www.lou-ka.com15// Created          : 2026-11-2516// Last Modified    : 2026-11-3017//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import SwiftUI9192struct ManagersView: View {93    enum Sort: String, CaseIterable, Identifiable {94        case listings, name, rating, price95        var id: String { rawValue }96        var label: String {97            switch self {98            case .listings: "Logements"99            case .name: "Nom"100            case .rating: "Note"101            case .price: "Loyer médian"102            }103        }104    }105106    @State private var directory: ManagersDirectory?107    @State private var error: Error?108    @State private var query = ""109    @State private var region: String?110    @State private var onlyWithListings = false111    @State private var sort: Sort = .listings112    @State private var external: ExternalLink?113114    private var filtered: [ManagerEntry] {115        guard let d = directory else { return [] }116        let q = Fmt.slug(query)117        var out = d.managers.filter { m in118            (region == nil || (m.region.isEmpty ? "Autres" : m.region) == region)119                && (!onlyWithListings || m.activeListings > 0)120                && (q.isEmpty || Fmt.slug(m.name).contains(q) || m.cities.contains { Fmt.slug($0).contains(q) })121        }122        switch sort {123        case .listings: break124        case .name: out.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }125        case .rating: out.sort { ($0.rating ?? -1, $0.reviews ?? 0) > ($1.rating ?? -1, $1.reviews ?? 0) }126        case .price: out.sort { ($0.priceMedian ?? .infinity) < ($1.priceMedian ?? .infinity) }127        }128        return out129    }130131    var body: some View {132        ScrollView {133            LazyVStack(alignment: .leading, spacing: 14, pinnedViews: []) {134                if let d = directory {135                    header(d)136                    regions(d)137                    HStack {138                        Toggle("Avec logements disponibles", isOn: $onlyWithListings).font(.subheadline).tint(Theme.brand)139                    }140                    let list = filtered141                    let managers = list.filter { $0.kind != "courtage" }142                    let brokers = list.filter { $0.kind == "courtage" }143                    Text(Fmt.plural(managers.count, "gestionnaire", "gestionnaires")).eyebrowStyle().padding(.top, 4)144                    ForEach(Array(managers.enumerated()), id: \.element.id) { i, m in ManagerCard(entry: m, external: $external).staggered(i) }145                    if !brokers.isEmpty {146                        Text("Bannières de courtage").eyebrowStyle().padding(.top, 12)147                        ForEach(brokers) { m in ManagerCard(entry: m, external: $external) }148                    }149                    if list.isEmpty {150                        EmptyStateView(door: .closed, title: "Aucun gestionnaire trouvé", message: "Essayez un autre nom, une ville ou une autre région.")151                    }152                } else if let error {153                    ErrorStateView(error: error) { Task { await load() } }154                } else {155                    ForEach(0..<6, id: \.self) { _ in Skeleton(height: 120, radius: 20) }156                }157            }158            .padding(.horizontal, 20).padding(.bottom, 30)159            .frame(maxWidth: 760)160            .frame(maxWidth: .infinity)161        }162        .background(Theme.bg)163        .navigationTitle("Gestionnaires")164        .searchable(text: $query, prompt: "Nom du gestionnaire ou ville")165        .toolbar {166            ToolbarItem(placement: .topBarTrailing) {167                Menu {168                    Picker("Trier par", selection: $sort) { ForEach(Sort.allCases) { Text($0.label).tag($0) } }169                } label: { Image(systemName: "arrow.up.arrow.down") }170                .accessibilityLabel("Trier")171            }172        }173        .refreshable { await load() }174        .task { if directory == nil { await load() } }175        .safariSheet($external)176    }177178    private func load() async {179        error = nil180        do { directory = try await APIClient.shared.managers() } catch is CancellationError {} catch { self.error = error }181    }182183    private func header(_ d: ManagersDirectory) -> some View {184        VStack(alignment: .leading, spacing: 14) {185            Text("Tous les gestionnaires immobiliers qui louent des appartements au Québec, réunis.")186                .font(.subheadline).foregroundStyle(Theme.ink2)187            HStack(spacing: 10) {188                StatTile(value: Fmt.int(d.total), label: "gestionnaires")189                StatTile(value: Fmt.int(d.listings), label: "logements")190                StatTile(value: Fmt.int(d.regions.count), label: "régions")191            }192            .cardStyle(padding: 16)193            HStack(spacing: 10) {194                NavigationLink(value: Route.cities) { Label("Villes", systemImage: "mappin.and.ellipse") }.buttonStyle(SoftButtonStyle())195                NavigationLink(value: Route.movers) { Label("Déménageurs", systemImage: "shippingbox") }.buttonStyle(SoftButtonStyle())196            }197        }198    }199200    private func regions(_ d: ManagersDirectory) -> some View {201        ScrollView(.horizontal, showsIndicators: false) {202            HStack(spacing: 8) {203                Chip(label: "Toutes", active: region == nil) { region = nil }204                ForEach(d.regions) { r in205                    Chip(label: "\(r.region.isEmpty ? "Autres" : r.region) · \(r.managers)", active: region == r.region) {206                        region = region == r.region ? nil : r.region207                    }208                }209            }210        }211        .scrollClipDisabled()212    }213}214215struct ManagerCard: View {216    let entry: ManagerEntry217    @Binding var external: ExternalLink?218219    var body: some View {220        let m = entry221        VStack(alignment: .leading, spacing: 10) {222            HStack(alignment: .top, spacing: 12) {223                Text(String(m.name.prefix(1)).uppercased()).font(.headline).foregroundStyle(Theme.brand)224                    .frame(width: 44, height: 44).background(Theme.brandSoft, in: RoundedRectangle(cornerRadius: 14, style: .continuous))225                    .accessibilityHidden(true)226                VStack(alignment: .leading, spacing: 3) {227                    Text(m.name).font(.headline).foregroundStyle(Theme.ink).lineLimit(2)228                    Text([m.region, m.cities.prefix(3).joined(separator: ", ")].filter { !$0.isEmpty }.joined(separator: " · "))229                        .font(.caption).foregroundStyle(Theme.ink3).lineLimit(1)230                }231                Spacer(minLength: 4)232                if let r = m.rating {233                    VStack(alignment: .trailing, spacing: 2) {234                        HStack(spacing: 3) {235                            Image(systemName: "star.fill").font(.system(size: 11)).foregroundStyle(Theme.high)236                            Text(String(format: "%.1f", r).replacingOccurrences(of: ".", with: ",")).font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)237                        }238                        if let n = m.reviews { Text("\(Fmt.int(n)) avis").font(.caption2).foregroundStyle(Theme.ink3) }239                    }240                    .accessibilityElement(children: .ignore)241                    .accessibilityLabel(String(format: "Note Google %.1f sur 5", r))242                }243            }244            if m.activeListings > 0 {245                HStack(spacing: 16) {246                    fact(Fmt.int(m.activeListings), m.activeListings > 1 ? "logements" : "logement")247                    if let p = m.priceMin { fact(Fmt.money(p), "à partir de") }248                    if let p = m.priceMedian { fact(Fmt.money(p), "loyer médian") }249                    if m.citiesTotal > 1 { fact(Fmt.int(m.citiesTotal), "villes") }250                }251            } else {252                HStack {253                    Text(m.state == "pause" ? "Synchronisation suspendue" : "Inventaire consultable sur son site")254                        .font(.footnote).foregroundStyle(Theme.ink3)255                    Spacer()256                    if let u = m.bestURL {257                        Button { external = ExternalLink(url: u) } label: { Label("Voir le site", systemImage: "arrow.up.right").font(.footnote.weight(.semibold)) }258                    }259                }260            }261        }262        .cardStyle(padding: 14)263        .overlay {264            if entry.activeListings > 0 {265                NavigationLink(value: Route.manager(entry.id)) { Color.clear }.buttonStyle(.plain)266                    .accessibilityLabel("\(entry.name), \(entry.activeListings) logements à louer")267            }268        }269    }270271    private func fact(_ value: String, _ label: String) -> some View {272        VStack(alignment: .leading, spacing: 1) {273            Text(value).font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)274            Text(label).font(.caption2).foregroundStyle(Theme.ink3)275        }276    }277}278279// MARK: - Fiche gestionnaire280281struct ManagerView: View {282    let id: String283    @Environment(AppModel.self) private var app284    @State private var profile: ManagerProfile?285    @State private var entry: ManagerEntry?286    @State private var listings: [Listing] = []287    @State private var total: Int?288    @State private var cursor: String?289    private var hasMore: Bool { cursor != nil }290    @State private var loading = true291    @State private var loadingMore = false292    @State private var sort: SearchSort = .recent293    @State private var external: ExternalLink?294    @Environment(Account.self) private var account295    /// Fiche publique du gestionnaire (pastille, contenu publié) ; une vue comptée par ouverture de la page.296    @State private var fiche: ManagerFiche?297    @State private var ficheAsked = false298299    private var name: String { profile?.nom ?? entry?.name ?? app.sourceName(id) }300301    var body: some View {302        ScrollView {303            LazyVStack(alignment: .leading, spacing: 22) {304                head305                if let fiche, fiche.verified || fiche.content != nil { ManagerFicheView(fiche: fiche, name: name, external: $external) }306                if let p = profile { reviews(p) }307                listingsSection308            }309            .padding(.horizontal, 20).padding(.bottom, 30)310            .frame(maxWidth: 760)311            .frame(maxWidth: .infinity)312        }313        .background(Theme.bg)314        .navigationTitle(name)315        .navigationBarTitleDisplayMode(.inline)316        .task(id: sort) { await load() }317        .task {318            guard !ficheAsked else { return }319            ficheAsked = true320            fiche = await account.messaging.managerFiche(sourceID: id, countView: true)321        }322        .safariSheet($external)323    }324325    private func load() async {326        loading = true327        async let p = try? APIClient.shared.manager(id)328        async let d = try? APIClient.shared.managers()329        var f = SearchFilters(); f.source = id330        async let s = try? APIClient.shared.search(f, sort: sort, limit: 24)331        let (pv, dv, sv) = await (p, d, s)332        profile = pv ?? profile333        entry = dv?.managers.first { $0.id == id } ?? entry334        if let sv {335            listings = sv.items; total = sv.total; cursor = sv.nextCursor336        }337        loading = false338    }339340    private func more() async {341        guard hasMore, !loadingMore else { return }342        loadingMore = true343        var f = SearchFilters(); f.source = id344        if let r = try? await APIClient.shared.search(f, sort: sort, cursor: cursor, limit: 24) {345            listings += r.items.filter { n in !listings.contains { $0.uid == n.uid } }346            cursor = r.nextCursor347        }348        loadingMore = false349    }350351    private var head: some View {352        VStack(alignment: .leading, spacing: 14) {353            HStack(spacing: 14) {354                if let logo = fiche?.content?.logo, logo.isSafe {355                    ManagerLogo(image: logo, name: name, size: 60)356                } else {357                    Text(String(name.prefix(1)).uppercased()).font(.title2.weight(.semibold)).foregroundStyle(Theme.brand)358                        .frame(width: 60, height: 60).background(Theme.brandSoft, in: RoundedRectangle(cornerRadius: 18, style: .continuous))359                }360                VStack(alignment: .leading, spacing: 5) {361                    Text(name).font(.editorial(24)).tracking(-0.2).foregroundStyle(Theme.ink)362                    if fiche?.verified == true { VerifiedBadge() }363                    if let r = entry?.region, !r.isEmpty { Text(r).font(.subheadline).foregroundStyle(Theme.ink3) }364                }365            }366            if let e = entry, e.activeListings > 0 {367                HStack(spacing: 10) {368                    StatTile(value: Fmt.int(e.activeListings), label: "logements")369                    if let p = e.priceMedian { StatTile(value: Fmt.money(p), label: "loyer médian") }370                    if e.citiesTotal > 0 { StatTile(value: Fmt.int(e.citiesTotal), label: e.citiesTotal > 1 ? "villes" : "ville") }371                }372                .cardStyle(padding: 16)373            }374            if let a = profile?.gmapsAdresse ?? entry?.address { Label(a, systemImage: "mappin.and.ellipse").font(.footnote).foregroundStyle(Theme.ink2) }375            FlowLayout(spacing: 10) {376                if let link = ExternalLink(profile?.siteWeb ?? entry?.url) {377                    Button { external = link } label: { Label("Site web", systemImage: "safari") }.buttonStyle(SoftButtonStyle())378                }379                if let phone = profile?.telephone ?? entry?.phone, let tel = URL(string: "tel:\(phone.filter { $0.isNumber || $0 == "+" })") {380                    Link(destination: tel) { Label(phone, systemImage: "phone") }.buttonStyle(SoftButtonStyle())381                }382                Button { var f = SearchFilters(); f.source = id; app.explore(f) } label: { Label("Sur la carte", systemImage: "map") }383                    .buttonStyle(SoftButtonStyle())384            }385        }386        .padding(.top, 8)387    }388389    @ViewBuilder390    private func reviews(_ p: ManagerProfile) -> some View {391        if p.gmapsStatut == "non_associe" {392            Label(p.noteMethode ?? "Aucune fiche Google Maps n'a pu être associée avec une confiance suffisante.", systemImage: "questionmark.circle")393                .font(.footnote).foregroundStyle(Theme.ink3)394        } else if let note = p.moyenne ?? p.gmapsNote {395            VStack(alignment: .leading, spacing: 14) {396                SectionHeader(eyebrow: "Avis Google", title: "Note Google")397                VStack(alignment: .leading, spacing: 14) {398                    HStack(spacing: 16) {399                        Text(String(format: "%.1f", note).replacingOccurrences(of: ".", with: ",")).font(.display(40, weight: .semibold)).num().foregroundStyle(Theme.ink)400                        VStack(alignment: .leading, spacing: 4) {401                            Stars(rating: note, size: 15)402                            Text("\(Fmt.int(p.nAvis ?? p.gmapsAvis ?? 0)) avis").font(.footnote).foregroundStyle(Theme.ink3)403                        }404                        Spacer()405                    }406                    if !p.distribution.isEmpty {407                        let maxN = Double(p.distribution.values.max() ?? 1)408                        VStack(spacing: 5) {409                            ForEach([5, 4, 3, 2, 1], id: \.self) { star in410                                let n = p.distribution[star] ?? 0411                                HStack(spacing: 8) {412                                    Text("\(star)").font(.caption).num().foregroundStyle(Theme.ink3).frame(width: 10)413                                    GeometryReader { g in414                                        ZStack(alignment: .leading) {415                                            Capsule().fill(Theme.surface3)416                                            Capsule().fill(star >= 4 ? Theme.good : star == 3 ? Theme.fair : Theme.high)417                                                .frame(width: max(2, g.size.width * CGFloat(Double(n) / maxN)))418                                        }419                                    }420                                    .frame(height: 6)421                                    Text("\(n)").font(.caption).num().foregroundStyle(Theme.ink3).frame(width: 30, alignment: .trailing)422                                }423                                .accessibilityElement(children: .ignore)424                                .accessibilityLabel("\(star) étoiles : \(n) avis")425                            }426                        }427                    }428                    Text("Fiche Google associée par similarité de nom, de site web et de ville\(p.confiance.map { String(format: " (confiance %.0f %%)", $0 * 100) } ?? ""). Lou-Ka n'affiche que la note et le nombre d'avis publics, pas leur texte.")429                        .font(.caption).foregroundStyle(Theme.ink3)430                }431                .cardStyle()432            }433        }434    }435436    private var listingsSection: some View {437        VStack(alignment: .leading, spacing: 14) {438            SectionHeader(title: total.map { Fmt.plural($0, "logement à louer", "logements à louer") } ?? "Logements à louer") {439                Menu {440                    Picker("Trier", selection: $sort) { ForEach(SearchSort.available(near: false)) { Text($0.label).tag($0) } }441                } label: { Image(systemName: "arrow.up.arrow.down").foregroundStyle(Theme.ink2) }442                .accessibilityLabel("Trier")443            }444            if loading, listings.isEmpty {445                ForEach(0..<2, id: \.self) { _ in ListingCardSkeleton() }446            } else if listings.isEmpty {447                VStack(alignment: .leading, spacing: 10) {448                    Text("Aucun logement synchronisé en ce moment.").font(.subheadline).foregroundStyle(Theme.ink3)449                    if let u = entry?.bestURL {450                        Button { external = ExternalLink(url: u) } label: { Label("Voir les logements sur son site", systemImage: "arrow.up.right") }451                            .buttonStyle(SoftButtonStyle())452                    }453                }454            } else {455                LazyVGrid(columns: [GridItem(.adaptive(minimum: 300), spacing: 14)], spacing: 14) {456                    ForEach(listings) { l in457                        ListingLink(listing: l).onAppear { if l.uid == listings.last?.uid { Task { await more() } } }458                    }459                }460                if loadingMore { ProgressView().frame(maxWidth: .infinity).padding() }461            }462        }463    }464}465
Files main
Menu

Theme