SPB Git

Repository Public

ProDirectoryView.swift 10.2 KB 225 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKa/Features/Pros/ProDirectoryView.swift10// Description      : annuaires de professionnels autour de l'achat —11//                    inspecteurs en bâtiment et déménageurs — avec recherche,12//                    régions, tri, appel téléphonique et site.13// Module           : ImmoKa14// Repository       : https://git.spboucher.ai/immo-ka-ios-v315// Project Website  : https://www.immo-ka.com16// Created          : 2026-11-2517// Last Modified    : 2026-11-2518//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import SwiftUI9293struct ProDirectoryView: View {94    enum Kind {95        case inspectors, movers96        var title: String { self == .inspectors ? "Inspecteurs en bâtiment" : "Déménageurs" }97        var noun: (String, String) { self == .inspectors ? ("inspecteur", "inspecteurs") : ("déménageur", "déménageurs") }98        var intro: String {99            self == .inspectors100                ? "Une inspection préachat protège votre décision. Voici les inspecteurs en bâtiment recensés au Québec, par région."101                : "Pour le jour où vous aurez les clés : les entreprises de déménagement recensées au Québec, par région."102        }103    }104105    let kind: Kind106    @State private var directory: ProDirectory?107    @State private var error: Error?108    @State private var query = ""109    @State private var region: String?110    @State private var byName = false111    @State private var external: ExternalLink?112113    private var filtered: [ProEntry] {114        guard let d = directory else { return [] }115        let q = Fmt.slug(query)116        var out = d.entries.filter { e in117            (region == nil || e.region == region) && (q.isEmpty || Fmt.slug(e.name).contains(q) || Fmt.slug(e.city).contains(q))118        }119        if byName { out.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } }120        // note d'abord, à nombre d'avis suffisant ; les fiches sans avis ensuite121        else { out.sort { score($0) > score($1) } }122        return out123    }124125    private func score(_ e: ProEntry) -> Double {126        guard let r = e.rating, let n = e.reviews, n > 0 else { return -1 }127        // moyenne bayésienne : une note de 5 sur 2 avis ne passe pas devant 4,8 sur 200128        return (r * Double(n) + 4.2 * 8) / (Double(n) + 8)129    }130131    var body: some View {132        ScrollView {133            LazyVStack(alignment: .leading, spacing: 0) {134                if let d = directory {135                    VStack(alignment: .leading, spacing: 16) {136                        Text(kind.intro).font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)137                        RegionChips(regions: d.regions, selection: $region)138                        HStack {139                            Text(Fmt.plural(filtered.count, kind.noun.0, kind.noun.1)).font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)140                            Spacer()141                            SlidingSegmented(selection: $byName, options: [(false, "Avis"), (true, "Nom")], label: "Tri de l'annuaire")142                        }143                    }144                    .padding(.bottom, 8)145                    Divider().overlay(Theme.line)146                    let list = filtered147                    ForEach(Array(list.enumerated()), id: \.element.id) { i, e in148                        ProRow(entry: e, external: $external).staggered(i)149                    }150                    if list.isEmpty {151                        EmptyStateView(door: .closed, title: "Aucun résultat", message: "Essayez un autre nom, une ville ou une autre région.")152                    }153                } else if let error {154                    ErrorStateView(error: error) { Task { await load() } }155                } else {156                    ForEach(0..<8, id: \.self) { _ in Skeleton(height: 64, radius: 8).padding(.vertical, 6) }157                }158            }159            .padding(.horizontal, 20).padding(.vertical, 12)160            .frame(maxWidth: 760)161            .frame(maxWidth: .infinity)162            .animation(.snappy, value: byName)163            .animation(.snappy, value: region)164        }165        .background(Theme.bg)166        .navigationTitle(kind.title)167        .navigationBarTitleDisplayMode(.inline)168        .searchable(text: $query, prompt: "Nom ou ville")169        .task { if directory == nil { await load() } }170        .safariSheet($external)171    }172173    private func load() async {174        error = nil175        do {176            directory = try await (kind == .inspectors ? APIClient.shared.inspecteurs() : APIClient.shared.demenageurs())177        } catch is CancellationError {} catch { self.error = error }178    }179}180181private struct ProRow: View {182    let entry: ProEntry183    @Binding var external: ExternalLink?184185    var body: some View {186        let e = entry187        VStack(alignment: .leading, spacing: 0) {188            HStack(alignment: .top, spacing: 12) {189                VStack(alignment: .leading, spacing: 4) {190                    Text(e.name).font(.editorial(18)).foregroundStyle(Theme.ink).lineLimit(2)191                    Text([e.city, e.region].filter { !$0.isEmpty }.joined(separator: " · ")).font(.footnote).foregroundStyle(Theme.ink3).lineLimit(1)192                    if let r = e.rating {193                        HStack(spacing: 6) {194                            Stars(rating: r, size: 11)195                            Text(String(format: "%.1f", r).replacingOccurrences(of: ".", with: ",")).font(.caption.weight(.semibold)).num().foregroundStyle(Theme.ink)196                            if let n = e.reviews { Text("\(Fmt.int(n)) avis").font(.caption).num().foregroundStyle(Theme.ink3) }197                        }198                        .accessibilityElement(children: .ignore)199                        .accessibilityLabel(String(format: "Note %.1f sur 5", r) + (e.reviews.map { ", \($0) avis" } ?? ""))200                    }201                }202                Spacer(minLength: 8)203                HStack(spacing: 6) {204                    if let tel = e.phoneURL {205                        Link(destination: tel) {206                            Image(systemName: "phone").font(.system(size: 15, weight: .medium)).foregroundStyle(Theme.brand)207                                .frame(width: 44, height: 44).background(Theme.brandSoft, in: Circle())208                        }209                        .accessibilityLabel("Appeler \(e.name)\(e.phone.map { " au \($0)" } ?? "")")210                    }211                    if let link = ExternalLink(e.website) {212                        Button { external = link } label: {213                            Image(systemName: "safari").font(.system(size: 15, weight: .medium)).foregroundStyle(Theme.ink2)214                                .frame(width: 44, height: 44).background(Theme.surface2, in: Circle())215                        }216                        .accessibilityLabel("Site de \(e.name)")217                    }218                }219            }220            .padding(.vertical, 12)221            Divider().overlay(Theme.line)222        }223    }224}225
Files main
Menu

Theme