SPB Git

Repository Public

BrokersView.swift 37.5 KB 772 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka Admin iOS9// File             : ImmoKaAdmin/Features/BrokersView.swift10// Description      : demandes d'accès des courtiers immobiliers — liste par11//                    état, détail fait pour décider (permis à vérifier au12//                    registre de l'OACIQ, téléphone déclaré face au téléphone13//                    publié, indices du serveur), décisions (approuver, refuser14//                    et suspendre avec motif transmis au demandeur, rétablir,15//                    remettre en attente), rattachement à un courtier de16//                    l'annuaire, fiche personnalisée (aperçu, masquer,17//                    rétablir). Toute décision est confirmée. Tout ce que le18//                    demandeur a écrit est du texte brut.19// Module           : ImmoKaAdmin20// Repository       : https://git.spboucher.ai/immo-ka-admin-ios21// Project Website  : https://www.immo-ka.com22// Created          : 2026-11-3023// Last Modified    : 2026-12-0124//25// =============================================================================26// AUTHOR & PROFESSIONAL AFFILIATION27// =============================================================================28//29// Author           : Simon-Pierre Boucher30// Position         : Professor of Finance31// Institution      : Université du Québec en Outaouais (UQO)32// Department       : Département des sciences administratives33// Organization     : SP Boucher34//35// Website          : https://spboucher.ai36// Git              : https://git.spboucher.ai37//38// =============================================================================39// OFFICIAL CONTACT DIRECTORY40// =============================================================================41//42// General          : info@spboucher.ai43// Professional     : contact@spboucher.ai44// Direct           : simon@spboucher.ai45// Research         : research@spboucher.ai46// Development      : dev@spboucher.ai47// Support          : support@spboucher.ai48// Security/Admin   : admin@spboucher.ai49// Notifications    : notifications@spboucher.ai50//51// Preferred Contact: support@spboucher.ai52//53// =============================================================================54// COPYRIGHT & INTELLECTUAL PROPERTY55// =============================================================================56//57// Copyright (c) 202658// Simon-Pierre Boucher59//60// All rights reserved where applicable.61//62// This file is governed by the applicable project license,63// copyright notices, institutional agreements and relevant law.64//65// Unless expressly authorized by the applicable license or66// rights holder, copying, redistribution, sublicensing,67// publication and commercial exploitation are not permitted.68//69// Existing third-party rights and notices remain unaffected.70//71// =============================================================================72// CONFIDENTIALITY & SECURITY73// =============================================================================74//75// Classification   : Public76// Distribution     : Public repository; use is governed by the project license77// Security Contact : admin@spboucher.ai78//79// Access to this source does not independently grant permission80// to redistribute or disclose confidential materials.81//82// Do not embed credentials, private keys, access tokens,83// certificates or confidential personal information.84//85// =============================================================================86// LICENSE & MAINTENANCE87// =============================================================================88//89// License          : None specified (no license file in this repository)90// Maintainer       : Simon-Pierre Boucher91// Technical Contact: dev@spboucher.ai92//93// =============================================================================94// END OF SP BOUCHER SOURCE HEADER95// =============================================================================9697import SwiftUI9899/// Le registre public où se vérifie un permis de courtage ; ouvert dans Safari, hors de l'app.100enum OACIQ {101    static let registry = URL(string: "https://www.oaciq.com/fr/trouver-courtier")!102    static let reminder = "À vérifier dans le registre de l'OACIQ avant d'approuver."103}104105struct BrokersView: View {106    @Environment(AdminSession.self) private var session107    @State private var filter: BrokerFilter = {108        BrokerFilter(rawValue: UserDefaults.standard.string(forKey: "IKBrokers") ?? "") ?? .pending109    }()110    @State private var items: [BrokerRequest]?111    @State private var failure: String?112113    var body: some View {114        VStack(spacing: 0) {115            Picker("État des demandes", selection: $filter) {116                ForEach(BrokerFilter.allCases) { Text($0.label).tag($0) }117            }118            .pickerStyle(.menu)119            .frame(maxWidth: .infinity, alignment: .leading)120            .padding(.horizontal, 12).padding(.vertical, 4)121            .accessibilityIdentifier("brokers.filter")122            Divider().overlay(Theme.line)123            Loadable(value: items, failure: failure, retry: { Task { await load() } }) { items in124                List {125                    if items.isEmpty {126                        EmptyState(symbol: "checkmark.circle", title: filter == .pending ? "Aucune demande en attente" : "Aucune demande dans cet état").listRowBackground(Color.clear)127                    }128                    ForEach(items) { r in129                        NavigationLink(value: r) { BrokerRow(request: r) }.accessibilityIdentifier("brokers.row")130                    }131                }132                .listStyle(.plain)133                .refreshable { await load() }134            }135        }136        .background(Theme.bg)137        .navigationTitle("Courtiers")138        .navigationBarTitleDisplayMode(.inline)139        // la demande voyage avec la navigation : son détail reste à l'écran quand une décision la sort de la liste140        .navigationDestination(for: BrokerRequest.self) { r in141            BrokerDetailView(request: r) { Task { await load() } }142        }143        .task(id: filter) { items = nil; await load() }144    }145146    private func load() async {147        do {148            items = try await session.call { try await $0.brokers(filter) }149            failure = nil150            try? await session.load()151        } catch {152            if items == nil { failure = AdminError.message(error) }153        }154    }155}156157private struct BrokerRow: View {158    let request: BrokerRequest159    var body: some View {160        VStack(alignment: .leading, spacing: 5) {161            HStack(alignment: .firstTextBaseline) {162                Text(verbatim: request.name.isEmpty ? (request.company.isEmpty ? "Sans nom" : request.company) : request.name).font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink).lineLimit(2)163                Spacer(minLength: 8)164                request.status.tag165            }166            Text(verbatim: [request.permit.map { "Permis \($0)" } ?? "Permis illisible", request.shownAgency ?? "agence non indiquée"].joined(separator: " · ")).font(.footnote).foregroundStyle(Theme.ink2).lineLimit(2)167            Text(verbatim: request.email).font(.footnote).foregroundStyle(Theme.ink2).lineLimit(1)168            HStack(spacing: 8) {169                Text(verbatim: "demandé le \(Fmt.dateTime(request.requestedAt))").font(.caption).foregroundStyle(Theme.ink3)170                if !request.inDirectory { StatusTag(label: "Hors annuaire", symbol: "questionmark.circle", tone: .warn) }171            }172        }173        .padding(.vertical, 3)174        .accessibilityElement(children: .combine)175    }176}177178extension BrokerFlag.Tone {179    var color: Color {180        switch self {181        case .good: Theme.good182        case .warn: Theme.high183        case .neutral: Theme.ink2184        }185    }186    var symbol: String {187        switch self {188        case .good: "checkmark.circle"189        case .warn: "exclamationmark.circle"190        case .neutral: "info.circle"191        }192    }193    var tag: StatusTag.Tone {194        switch self {195        case .good: .good196        case .warn: .warn197        case .neutral: .neutral198        }199    }200}201202/// Rappel placé partout où l'on approuve : le permis se vérifie au registre public, hors d'Immo-Ka.203struct PermitReminder: View {204    let permit: String?205    var body: some View {206        VStack(alignment: .leading, spacing: 8) {207            if let permit {208                Text(verbatim: "Permis déclaré : \(permit). \(OACIQ.reminder)").font(.subheadline).foregroundStyle(Theme.ink)209            } else {210                Text(verbatim: "Aucun numéro de permis lisible dans cette demande. \(OACIQ.reminder)").font(.subheadline).foregroundStyle(Theme.ink)211            }212            OACIQLink()213        }214        .accessibilityIdentifier("permit.reminder")215    }216}217218/// Ouvre le registre dans Safari (un `Link` ne navigue jamais dans l'app).219struct OACIQLink: View {220    var body: some View {221        Link(destination: OACIQ.registry) {222            Label("Ouvrir le registre de l'OACIQ", systemImage: "arrow.up.right.square").font(.subheadline.weight(.medium))223        }224        .accessibilityHint("Ouvre Safari")225        .accessibilityIdentifier("permit.oaciq")226    }227}228229/// Décision demandée, en attente de confirmation.230private struct PendingDecision: Identifiable {231    var action: BrokerAction232    var id: String { action.rawValue }233}234235struct BrokerDetailView: View {236    @State var request: BrokerRequest237    var changed: () -> Void238    @Environment(AdminSession.self) private var session239    @Environment(Navigator.self) private var nav240    @State private var deciding: PendingDecision?241    @State private var attaching = false242    @State private var failure: String?243    @Environment(\.dynamicTypeSize) private var typeSize244245    var body: some View {246        Form {247            if let failure { Section { ErrorBanner(text: failure).listRowInsets(EdgeInsets()) } }248            Section {249                HStack { Text("État").foregroundStyle(Theme.ink); Spacer(); request.status.tag }250                    .accessibilityElement(children: .combine)251                    .accessibilityIdentifier("broker.status")252                if let reason = request.reason {253                    VStack(alignment: .leading, spacing: 3) {254                        Text("Motif transmis").font(.caption).foregroundStyle(Theme.ink3)255                        PlainText(text: reason, color: Theme.ink)256                    }257                }258            }259            permitSection260            phonesSection261            flagsSection262            Section("Demande") {263                InfoRow(label: "Nom", value: request.name.isEmpty ? "—" : request.name)264                InfoRow(label: "Courriel", value: request.email)265                if !request.role.isEmpty { InfoRow(label: "Fonction déclarée", value: request.role) }266                InfoRow(label: "Courtier déclaré", value: request.company.isEmpty ? "—" : request.company)267                InfoRow(label: "Agence déclarée", value: request.agency ?? "—")268                InfoRow(label: "Demande reçue", value: Fmt.dateTime(request.requestedAt))269                InfoRow(label: "Adresse confirmée", value: Fmt.dateTime(request.verifiedAt))270                if request.decidedAt != nil { InfoRow(label: "Décision", value: "\(Fmt.dateTime(request.decidedAt))\(request.decidedBy.map { "\npar \($0)" } ?? "")") }271                InfoRow(label: "Dernière connexion", value: Fmt.relative(request.lastLogin))272            }273            Section {274                if let dir = request.directory, let bid = request.brokerID {275                    InfoRow(label: "Courtier", value: dir.name)276                    InfoRow(label: "Agence", value: [dir.agency, dir.banner].compactMap { $0 }.joined(separator: " · ").isEmpty ? "agence inconnue" : [dir.agency, dir.banner].compactMap { $0 }.joined(separator: " · "))277                    InfoRow(label: "Inscriptions actives", value: Fmt.plural(dir.listings ?? 0, "propriété", "propriétés"))278                    InfoRow(label: "Identifiant", value: bid)279                    NavigationLink { FicheView(brokerID: bid, name: dir.name) } label: { Label("Fiche personnalisée", systemImage: "doc.richtext") }280                        .accessibilityIdentifier("broker.fiche")281                } else {282                    Label("Hors annuaire : à rattacher avant d'approuver.", systemImage: "questionmark.circle").font(.subheadline).foregroundStyle(Theme.high)283                        .accessibilityIdentifier("broker.unattached")284                }285                Button { attaching = true } label: { Label(request.brokerID == nil ? "Rattacher à un courtier de l'annuaire" : "Changer le rattachement", systemImage: "link") }286                    .accessibilityIdentifier("broker.attach")287            } header: {288                Text("Annuaire d'Immo-Ka")289            } footer: {290                if !request.canBeApproved { Text("Une demande doit être rattachée à un courtier de l'annuaire avant d'être approuvée.") }291            }292            Section("Décision") {293                ForEach(BrokerAction.available(for: request.status), id: \.rawValue) { action in294                    Button(role: action.isDestructive ? .destructive : nil) { deciding = PendingDecision(action: action) } label: {295                        Label(action.title, systemImage: symbol(action))296                    }297                    .disabled(action == .approve && !request.canBeApproved)298                    .accessibilityIdentifier("broker.action.\(action.rawValue)")299                }300            }301        }302        .navigationTitle(request.name.isEmpty ? "Demande" : request.name)303        .navigationBarTitleDisplayMode(.inline)304        .sheet(item: $deciding) { d in305            DecisionSheet(request: request, action: d.action) { reason in306                try await session.call { try await $0.decide(accountID: request.accountID, action: d.action, reason: reason) }307                await reload()308                nav.show(done(d.action))309            }310        }311        .sheet(isPresented: $attaching) {312            DirectorySearchSheet(request: request) { broker in313                try await session.call { try await $0.decide(accountID: request.accountID, action: .attach, brokerID: broker.brokerID) }314                await reload()315                nav.show("Demande rattachée à \(broker.name)")316            }317        }318    }319320    /// Le permis, en évidence : c'est la première chose à vérifier, et elle se vérifie hors d'Immo-Ka.321    private var permitSection: some View {322        Section {323            VStack(alignment: .leading, spacing: 6) {324                if let permit = request.permit {325                    Text(verbatim: permit).font(.system(.largeTitle, design: .monospaced).weight(.semibold)).foregroundStyle(Theme.ink)326                        .textSelection(.enabled)327                        .accessibilityLabel("Permis \(permit.map(String.init).joined(separator: " "))")328                        .accessibilityIdentifier("broker.permit")329                } else {330                    Text(verbatim: "Numéro illisible : « \(request.title ?? "vide") »").font(.headline).foregroundStyle(Theme.high)331                        .accessibilityIdentifier("broker.permit")332                }333                Text(OACIQ.reminder).font(.subheadline).foregroundStyle(Theme.ink2)334                    .accessibilityIdentifier("broker.permit.reminder")335            }336            .padding(.vertical, 2)337            OACIQLink()338        } header: {339            Text("Permis de courtage (OACIQ)")340        } footer: {341            Text("Immo-Ka ne vérifie pas le permis : cherchez ce numéro dans le registre et comparez le nom et l'agence.")342        }343    }344345    /// Les deux téléphones côte à côte, puis ce qu'il faut en conclure, écrit.346    private var phonesSection: some View {347        let verdict = request.phoneVerdict348        let declared = PhoneDigits.display(request.phone)349        let published = PhoneDigits.display(request.directory?.phone)350        return Section("Téléphones") {351            // côte à côte ; l'un sous l'autre seulement aux très grandes tailles de texte352            if typeSize.isAccessibilitySize {353                phone("Déclaré dans la demande", declared, empty: "non indiqué", id: "broker.phone.declared")354                phone("Publié sur ses inscriptions", published, empty: request.inDirectory ? "aucun" : "sans objet", id: "broker.phone.published")355            } else {356                HStack(alignment: .top, spacing: 12) {357                    phone("Déclaré dans la demande", declared, empty: "non indiqué", id: "broker.phone.declared")358                    Divider()359                    phone("Publié sur ses inscriptions", published, empty: request.inDirectory ? "aucun" : "sans objet", id: "broker.phone.published")360                }361            }362            Label { Text(verdict.text).font(.subheadline) } icon: { Image(systemName: verdict.tone.symbol) }363                .foregroundStyle(verdict.tone.color)364                .accessibilityElement(children: .combine)365                .accessibilityIdentifier("broker.phone.verdict")366        }367    }368369    private func phone(_ label: String, _ value: String, empty: String, id: String) -> some View {370        VStack(alignment: .leading, spacing: 3) {371            Text(label).font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)372            if value.isEmpty {373                Text(empty).font(.body).foregroundStyle(Theme.ink3)374            } else {375                Text(verbatim: value).font(.body.monospacedDigit().weight(.medium)).foregroundStyle(Theme.ink).textSelection(.enabled)376            }377        }378        .frame(maxWidth: .infinity, alignment: .leading)379        .accessibilityElement(children: .combine)380        .accessibilityIdentifier(id)381    }382383    private var flagsSection: some View {384        Section("Indices pour la validation") {385            if request.flags.isEmpty {386                Text("Aucun indice relevé par le serveur : ni téléphone concordant, ni messagerie grand public.").font(.subheadline).foregroundStyle(Theme.ink2)387                    .accessibilityIdentifier("broker.flags.none")388            }389            ForEach(request.describedFlags) { f in390                VStack(alignment: .leading, spacing: 5) {391                    StatusTag(label: f.label, symbol: f.tone.symbol, tone: f.tone.tag)392                    Text(f.text).font(.footnote).foregroundStyle(Theme.ink2)393                }394                .padding(.vertical, 2)395                .accessibilityElement(children: .combine)396                .accessibilityIdentifier("broker.flag.\(f.id)")397            }398        }399    }400401    private func symbol(_ a: BrokerAction) -> String {402        switch a {403        case .approve: "checkmark.seal"404        case .refuse: "xmark.octagon"405        case .suspend: "pause.circle"406        case .restore: "arrow.uturn.backward.circle"407        case .backToPending: "hourglass"408        case .attach: "link"409        }410    }411412    private func done(_ a: BrokerAction) -> String {413        switch a {414        case .approve: "Demande approuvée"415        case .refuse: "Demande refusée"416        case .suspend: "Accès suspendu"417        case .restore: "Accès rétabli"418        case .backToPending: "Demande remise en attente"419        case .attach: "Rattachement modifié"420        }421    }422423    /// Relit la demande après une décision (elle a pu changer d'état, donc de liste).424    private func reload() async {425        if let fresh = try? await session.call({ try await $0.brokers(.all) }).first(where: { $0.accountID == request.accountID }) { request = fresh }426        changed()427    }428}429430/// Confirmation d'une décision ; motif obligatoire pour refuser ou suspendre ; rappel du permis avant d'approuver.431private struct DecisionSheet: View {432    let request: BrokerRequest433    let action: BrokerAction434    var submit: (String?) async throws -> Void435    @Environment(\.dismiss) private var dismiss436    @State private var reason = ""437    @State private var busy = false438    @State private var failure: String?439440    private var ready: Bool { !action.needsReason || reason.trimmingCharacters(in: .whitespacesAndNewlines).count >= 3 }441442    var body: some View {443        NavigationStack {444            Form {445                if let failure { Section { ErrorBanner(text: failure).listRowInsets(EdgeInsets()) } }446                if action == .approve {447                    Section { PermitReminder(permit: request.permit) }448                }449                Section {450                    InfoRow(label: "Demandeur", value: [request.name, request.email].filter { !$0.isEmpty }.joined(separator: "\n"))451                    InfoRow(label: "Courtier", value: [request.directory?.name ?? request.company, request.shownAgency ?? ""].filter { !$0.isEmpty }.joined(separator: "\n"))452                } footer: {453                    Text(consequence)454                }455                if action.needsReason {456                    Section {457                        TextField("Motif", text: $reason, axis: .vertical).lineLimit(3...8).accessibilityIdentifier("decision.reason")458                    } header: {459                        Text("Motif (obligatoire)")460                    } footer: {461                        Text("Ce motif est transmis tel quel au demandeur, dans le courriel qu'il reçoit.")462                    }463                }464            }465            .navigationTitle(action.title)466            .navigationBarTitleDisplayMode(.inline)467            .toolbar {468                ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() }.accessibilityIdentifier("decision.cancel") }469                // dans la barre : toujours visible, quelle que soit la hauteur de la feuille470                ToolbarItem(placement: .confirmationAction) {471                    Button {472                        busy = true; failure = nil473                        Task {474                            defer { busy = false }475                            do { try await submit(action.needsReason ? reason : nil); dismiss() } catch { failure = AdminError.message(error) }476                        }477                    } label: {478                        if busy { ProgressView() } else { Text(action.title).fontWeight(.semibold) }479                    }480                    .tint(action.isDestructive ? Theme.bad : Theme.brand)481                    .disabled(!ready || busy)482                    .accessibilityLabel("\(action.title) la demande")483                    .accessibilityIdentifier("decision.confirm")484                }485            }486        }487        .presentationDetents(action == .approve ? [.large] : [.medium, .large])488    }489490    private var consequence: String {491        switch action {492        case .approve: "Cette personne pourra publier la fiche du courtier, y ajouter des images et répondre aux acheteurs en son nom. Elle est prévenue par courriel."493        case .refuse: "La personne est déconnectée et prévenue par courriel, avec votre motif."494        case .suspend: "La personne perd l'accès au portail des courtiers, elle est déconnectée et prévenue par courriel, avec votre motif."495        case .restore: "La personne retrouve son accès au portail des courtiers. Elle est prévenue par courriel."496        case .backToPending: "La demande revient dans la liste à valider. Aucun courriel n'est envoyé."497        case .attach: "Seul le rattachement change. Aucun courriel n'est envoyé."498        }499    }500}501502/// Recherche dans l'annuaire pour rattacher une demande à un courtier.503private struct DirectorySearchSheet: View {504    let request: BrokerRequest505    var choose: (DirectoryBroker) async throws -> Void506    @Environment(AdminSession.self) private var session507    @Environment(\.dismiss) private var dismiss508    @State private var query = ""509    @State private var results: [DirectoryBroker] = []510    @State private var searching = false511    @State private var searchFailed = false512    @State private var candidate: DirectoryBroker?513    @State private var failure: String?514    @State private var busy = false515516    var body: some View {517        NavigationStack {518            List {519                if let failure { ErrorBanner(text: failure).listRowInsets(EdgeInsets()) }520                Section {521                    if searchFailed {522                        Text("La recherche a échoué. Modifiez le texte pour réessayer.").font(.subheadline).foregroundStyle(Theme.bad)523                    } else if results.isEmpty && !searching {524                        Text(query.trimmingCharacters(in: .whitespaces).count < 2 ? "Écrivez au moins deux lettres du nom du courtier." : "Aucun courtier de l'annuaire ne correspond.")525                            .font(.subheadline).foregroundStyle(Theme.ink3)526                    }527                    ForEach(results) { m in528                        Button { candidate = m } label: {529                            VStack(alignment: .leading, spacing: 2) {530                                Text(verbatim: m.name).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)531                                Text(verbatim: "\(agency(m)) · \(Fmt.plural(m.listings ?? 0, "propriété", "propriétés"))").font(.caption).foregroundStyle(Theme.ink3)532                            }533                        }534                        .disabled(busy)535                        .accessibilityIdentifier("directory.row")536                    }537                } footer: {538                    Text("Choisissez le courtier de l'annuaire dont cette personne gérera la fiche et les messages : vérifiez que le nom et l'agence correspondent à son permis.")539                }540            }541            .listStyle(.plain)542            .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: "Nom du courtier")543            .navigationTitle("Rattacher")544            .navigationBarTitleDisplayMode(.inline)545            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } } }546            .task(id: query) {547                let q = query.trimmingCharacters(in: .whitespaces)548                guard q.count >= 2 else { results = []; searchFailed = false; return }549                searching = true550                try? await Task.sleep(for: .milliseconds(300))551                if Task.isCancelled { return }552                do { results = try await session.api.searchDirectory(q); searchFailed = false } catch { if !Task.isCancelled { results = []; searchFailed = true } }553                searching = false554            }555            .onAppear { if query.isEmpty { query = String(request.company.prefix(40)) } }556            .alert("Rattacher la demande ?", isPresented: Binding(get: { candidate != nil }, set: { if !$0 { candidate = nil } }), presenting: candidate) { m in557                Button("Rattacher") {558                    busy = true; failure = nil559                    Task {560                        defer { busy = false }561                        do { try await choose(m); dismiss() } catch { failure = AdminError.message(error) }562                    }563                }564                Button("Annuler", role: .cancel) {}565            } message: { m in566                Text(verbatim: "La demande de « \(request.name.isEmpty ? request.email : request.name) » sera rattachée à « \(m.name) » (\(agency(m))). Aucun courriel n'est envoyé.")567            }568        }569    }570571    private func agency(_ m: DirectoryBroker) -> String {572        let a = [m.agency, m.banner].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")573        return a.isEmpty ? "agence inconnue" : a574    }575}576577// MARK: - Fiche personnalisée578579struct FicheView: View {580    let brokerID: String581    let name: String582    @Environment(AdminSession.self) private var session583    @Environment(Navigator.self) private var nav584    @State private var fiche: AdminFiche?585    @State private var failure: String?586    @State private var showDraft = false587    @State private var hiding = false588    @State private var confirmRestore = false589    @State private var actionError: String?590591    var body: some View {592        Loadable(value: fiche, failure: failure, retry: { Task { await load() } }) { f in593            Form {594                if let actionError { Section { ErrorBanner(text: actionError).listRowInsets(EdgeInsets()) } }595                Section {596                    HStack {597                        Text("Visibilité")598                        Spacer()599                        if f.hidden { StatusTag(label: "Masquée", symbol: "eye.slash", tone: .bad) }600                        else if f.published != nil { StatusTag(label: "Publiée", symbol: "eye", tone: .good) }601                        else { StatusTag(label: "Jamais publiée", symbol: "doc", tone: .neutral) }602                    }603                    .accessibilityElement(children: .combine)604                    if f.hidden, let r = f.hiddenReason {605                        VStack(alignment: .leading, spacing: 3) { Text("Motif du masquage").font(.caption).foregroundStyle(Theme.ink3); PlainText(text: r, color: Theme.ink) }606                    }607                    if f.publishedAt != nil { InfoRow(label: "Publiée le", value: Fmt.dateTime(f.publishedAt)) }608                    if f.draftUpdatedAt != nil { InfoRow(label: "Brouillon modifié le", value: Fmt.dateTime(f.draftUpdatedAt)) }609                    if f.dirty { Label("Le brouillon diffère de la version publiée.", systemImage: "pencil.line").font(.footnote).foregroundStyle(Theme.ink2) }610                    InfoRow(label: "Images téléversées", value: Fmt.int(f.mediaCount))611                    if f.hidden {612                        Button { confirmRestore = true } label: { Label("Rétablir la fiche", systemImage: "eye") }.accessibilityIdentifier("fiche.restore")613                    } else if f.published != nil {614                        Button(role: .destructive) { hiding = true } label: { Label("Masquer la fiche", systemImage: "eye.slash") }.accessibilityIdentifier("fiche.hide")615                    }616                } footer: {617                    Text("Masquer retire la fiche personnalisée du site et des applications ; le courtier garde son accès et ses messages.")618                }619                if !f.team.isEmpty {620                    Section("Comptes approuvés pour ce courtier") {621                        ForEach(f.team) { m in622                            VStack(alignment: .leading, spacing: 2) {623                                Text(verbatim: m.name.isEmpty ? m.email : m.name).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink)624                                Text(verbatim: [m.title, m.email].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")).font(.caption).foregroundStyle(Theme.ink3)625                            }626                            .accessibilityElement(children: .combine)627                        }628                    }629                }630                Section {631                    Picker("Version", selection: $showDraft) { Text("Publiée").tag(false); Text("Brouillon").tag(true) }.pickerStyle(.segmented)632                        .accessibilityIdentifier("fiche.version")633                }634                if let c = showDraft ? f.draft : f.published, !c.isEmpty {635                    FicheContentSections(content: c)636                } else {637                    Section { Text(showDraft ? "Le brouillon est vide." : "Aucune version publiée.").font(.subheadline).foregroundStyle(Theme.ink3) }638                }639            }640            .refreshable { await load() }641        }642        .navigationTitle(name)643        .navigationBarTitleDisplayMode(.inline)644        .task { await load() }645        .sheet(isPresented: $hiding) {646            ReasonSheet(title: "Masquer la fiche", prompt: "Motif du masquage", footer: "La fiche de « \(name) » disparaît du site et des applications dès maintenant. Le motif est consigné au journal.", confirm: "Masquer") { reason in647                try await session.call { try await $0.hideFiche(brokerID: brokerID, hidden: true, reason: reason) }648                await load()649                nav.show("Fiche masquée")650            }651        }652        .alert("Rétablir la fiche ?", isPresented: $confirmRestore) {653            Button("Rétablir") {654                actionError = nil655                Task {656                    do { try await session.call { try await $0.hideFiche(brokerID: brokerID, hidden: false, reason: "") }; await load(); nav.show("Fiche rétablie") }657                    catch { actionError = AdminError.message(error) }658                }659            }660            Button("Annuler", role: .cancel) {}661        } message: {662            Text(verbatim: "La fiche publiée de « \(name) » redevient visible sur le site et dans les applications.")663        }664    }665666    private func load() async {667        do { fiche = try await session.call { try await $0.fiche(brokerID: brokerID) }; failure = nil } catch { if fiche == nil { failure = AdminError.message(error) } }668    }669}670671/// Contenu d'une fiche, pour relecture : tout est du texte brut, aucun lien n'est cliquable.672private struct FicheContentSections: View {673    let content: FicheContent674    var body: some View {675        let c = content676        if c.tagline != nil || c.about != nil {677            Section("Présentation") {678                if let t = c.tagline { PlainText(text: t, font: .headline, color: Theme.ink) }679                if let a = c.about { PlainText(text: a) }680                if let f = c.founded { InfoRow(label: "Fondée en", value: String(f)) }681                if !c.languages.isEmpty { InfoRow(label: "Langues", value: c.languages.joined(separator: ", ")) }682            }683        }684        if c.phone != nil || c.email != nil || c.website != nil || c.bookingURL != nil || c.address != nil || !c.hours.isEmpty || !c.social.isEmpty {685            Section("Coordonnées et liens") {686                if let v = c.phone { InfoRow(label: "Téléphone", value: v) }687                if let v = c.email { InfoRow(label: "Courriel", value: v) }688                if let v = c.website { InfoRow(label: "Site", value: v) }689                if let v = c.bookingURL { InfoRow(label: "Rendez-vous", value: v) }690                if let v = c.address { InfoRow(label: "Adresse", value: v) }691                ForEach(c.hours) { InfoRow(label: $0.title, value: $0.text) }692                ForEach(c.social) { InfoRow(label: $0.title, value: $0.text) }693            }694        }695        pairs("Chiffres clés", c.highlights)696        if !c.services.isEmpty { Section("Services") { ForEach(c.services, id: \.self) { PlainText(text: $0, color: Theme.ink) } } }697        pairs("Politiques", c.policies)698        pairs("Questions fréquentes", c.faq)699        pairs("Équipe", c.team)700        if !c.galleryCaptions.isEmpty { Section("Légendes de la galerie") { ForEach(c.galleryCaptions, id: \.self) { PlainText(text: $0) } } }701        if c.autoReply != nil || c.responseTime != nil {702            Section("Messagerie") {703                if let r = c.responseTime { InfoRow(label: "Délai annoncé", value: r) }704                if let a = c.autoReply { VStack(alignment: .leading, spacing: 3) { Text("Réponse automatique").font(.caption).foregroundStyle(Theme.ink3); PlainText(text: a) } }705            }706        }707        pairs("Réponses rapides", c.quickReplies)708    }709710    @ViewBuilder711    private func pairs(_ title: String, _ items: [FicheContent.Pair]) -> some View {712        if !items.isEmpty {713            Section(title) {714                ForEach(items) { p in715                    VStack(alignment: .leading, spacing: 3) {716                        if !p.title.isEmpty { PlainText(text: p.title, font: .subheadline.weight(.semibold), color: Theme.ink) }717                        if !p.text.isEmpty { PlainText(text: p.text) }718                    }719                }720            }721        }722    }723}724725/// Feuille d'un motif obligatoire, avec confirmation.726struct ReasonSheet: View {727    let title: String728    let prompt: String729    let footer: String730    let confirm: String731    var submit: (String) async throws -> Void732    @Environment(\.dismiss) private var dismiss733    @State private var reason = ""734    @State private var busy = false735    @State private var failure: String?736737    var body: some View {738        NavigationStack {739            Form {740                if let failure { Section { ErrorBanner(text: failure).listRowInsets(EdgeInsets()) } }741                Section {742                    TextField(prompt, text: $reason, axis: .vertical).lineLimit(3...8).accessibilityIdentifier("reason.text")743                } header: {744                    Text("\(prompt) (obligatoire)")745                } footer: {746                    Text(verbatim: footer)747                }748            }749            .navigationTitle(title)750            .navigationBarTitleDisplayMode(.inline)751            .toolbar {752                ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }753                ToolbarItem(placement: .confirmationAction) {754                    Button {755                        busy = true; failure = nil756                        Task {757                            defer { busy = false }758                            do { try await submit(reason); dismiss() } catch { failure = AdminError.message(error) }759                        }760                    } label: {761                        if busy { ProgressView() } else { Text(confirm).fontWeight(.semibold) }762                    }763                    .tint(Theme.bad)764                    .disabled(reason.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || busy)765                    .accessibilityIdentifier("reason.confirm")766                }767            }768        }769        .presentationDetents([.medium, .large])770    }771}772
Files main
Menu

Theme