SPB Git

Repository Public

SalesRegistryView.swift 13.8 KB 306 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Vrai-Prix iOS9// File             : VraiPrix/Features/Sales/SalesRegistryView.swift10// Description      : registre des ventes réellement conclues — filtres (lieu,11//                    type, prix, période), pagination à la demande, chiffres de12//                    tête.13// Module           : VraiPrix14// Repository       : https://git.spboucher.ai/vrai-prix-ios-v315// Project Website  : https://www.vrai-prix.com16// Created          : 2026-11-2617// Last Modified    : 2026-11-2618//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 SalesRegistryView: View {94    @State var filters: SaleFilters95    /// onglet Ventes (vrai) ou registre ouvert depuis une municipalité (faux)96    let root: Bool9798    @Environment(AppModel.self) private var model99    @State private var rows: [Sale] = []100    @State private var page = 0101    @State private var pages = 1102    @State private var total = 0103    @State private var updatedTo: String?104    @State private var source: String?105    @State private var stale = false106    @State private var loading = false107    @State private var error: APIError?108    @State private var overview: SalesOverview?109    @State private var showFilters = false110    @State private var placeDraft = ""111112    var body: some View {113        ScrollView {114            LazyVStack(alignment: .leading, spacing: 0) {115                if root, let o = overview, filters.activeCount == 0 {116                    FigureGrid {117                        Figure(label: "Ventes, 30 jours", value: Fmt.int(o.n30))118                        Figure(label: "Prix médian, 30 jours", value: Fmt.money(o.median30))119                        Figure(label: "Ventes, 12 mois", value: Fmt.int(o.n365))120                        Figure(label: "Dernière publication", value: Fmt.day(o.maxDate, short: true))121                    }122                    .padding(.top, 6).padding(.bottom, 18)123                }124                controls125                if stale { StaleNotice().padding(.top, 10) }126                summary.padding(.top, 14).padding(.bottom, 4)127                Hairline()128                list129            }130            .pageColumn()131            .padding(.bottom, 32)132        }133        .background(Theme.bg)134        .navigationTitle(root ? "Ventes" : (filters.place.isEmpty ? "Registre des ventes" : filters.place))135        .navigationBarTitleDisplayMode(root ? .large : .inline)136        .sheet(isPresented: $showFilters) {137            SaleFiltersSheet(filters: $filters).presentationDetents([.medium, .large])138        }139        .task(id: filters) { await reload() }140        .task {141            placeDraft = filters.place142            if model.launchSheet == "salefilters" { showFilters = true }143            if overview == nil { overview = try? await APIClient.shared.salesOverview() }144        }145        .refreshable { await reload() }146    }147148    private var controls: some View {149        VStack(alignment: .leading, spacing: 10) {150            HStack(spacing: 8) {151                HStack(spacing: 8) {152                    Image(systemName: "magnifyingglass").foregroundStyle(Theme.ink3)153                    TextField("Ville ou rue", text: $placeDraft)154                        .textInputAutocapitalization(.words).autocorrectionDisabled().submitLabel(.search)155                        .onSubmit { filters.place = placeDraft.trimmingCharacters(in: .whitespaces) }156                        .accessibilityIdentifier("sales-place")157                    if !placeDraft.isEmpty {158                        Button { placeDraft = ""; filters.place = "" } label: {159                            Image(systemName: "xmark.circle.fill").foregroundStyle(Theme.ink3).frame(width: 30, height: 44)160                        }161                        .buttonStyle(.plain).accessibilityLabel("Effacer le lieu")162                    }163                }164                .padding(.horizontal, 12).frame(minHeight: 48)165                .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))166                .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(Theme.line2, lineWidth: 1))167                Button { showFilters = true } label: {168                    HStack(spacing: 5) {169                        Image(systemName: "slider.horizontal.3")170                        let n = filters.activeCount - (filters.place.isEmpty ? 0 : 1)171                        if n > 0 { Text(String(n)).font(.footnote.weight(.bold)).monospacedDigit() }172                    }173                    .foregroundStyle(Theme.ink).frame(minWidth: 48, minHeight: 48)174                    .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))175                    .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(Theme.line2, lineWidth: 1))176                }177                .buttonStyle(.plain)178                .accessibilityLabel("Filtres : type et prix")179                .accessibilityIdentifier("sales-filters")180            }181            SlidingSegmented(selection: $filters.period, options: SaleFilters.Period.allCases.map { ($0, $0.label) }, label: "Période")182        }183    }184185    private var summary: some View {186        VStack(alignment: .leading, spacing: 3) {187            Text(loading && rows.isEmpty ? "Recherche…" : "\(Fmt.int(total)) \(total == 1 ? "vente" : "ventes") · \(filters.period.long)\(describeFilters)")188                .font(.subheadline.weight(.medium)).num().foregroundStyle(Theme.ink)189                .fixedSize(horizontal: false, vertical: true)190                .accessibilityIdentifier("sales-count")191            if let u = updatedTo {192                Text("Transactions publiées jusqu'au \(Fmt.day(u)).").font(.footnote).num().foregroundStyle(Theme.ink3)193            }194        }195    }196197    private var describeFilters: String {198        var p: [String] = []199        if !filters.type.isEmpty { p.append(SaleFilters.types.first { $0.key == filters.type }?.label.lowercased() ?? filters.type) }200        if let a = filters.min, let b = filters.max { p.append("\(Fmt.compact(a)) à \(Fmt.compact(b))") }201        else if let a = filters.min { p.append("à partir de \(Fmt.compact(a))") }202        else if let b = filters.max { p.append("jusqu'à \(Fmt.compact(b))") }203        return p.isEmpty ? "" : " · " + p.joined(separator: " · ")204    }205206    @ViewBuilder207    private var list: some View {208        if let error, rows.isEmpty {209            ErrorState(error: error, subject: "Le registre des ventes") { Task { await reload() } }210        } else if rows.isEmpty, !loading {211            EmptyState(title: "Aucune vente pour ces critères",212                       message: "Élargissez la période, retirez un filtre ou vérifiez l'orthographe du lieu.",213                       actionLabel: filters.activeCount > 0 ? "Retirer les filtres" : nil) {214                placeDraft = ""; filters = SaleFilters(period: filters.period)215            }216        } else if rows.isEmpty {217            LoadingState(label: "Chargement du registre")218        } else {219            ForEach(Array(rows.enumerated()), id: \.element.id) { i, s in220                Button {221                    if let id = s.idProvinc { model.openProperty(id) }222                } label: {223                    HStack(spacing: 8) {224                        SaleRow(sale: s, showCity: true)225                        if s.idProvinc != nil { Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink3) }226                    }227                }228                .buttonStyle(.plain)229                .disabled(s.idProvinc == nil)230                .accessibilityIdentifier("sale-row-\(i)")231                .onAppear { if i >= rows.count - 6 { Task { await loadMore() } } }232                Hairline()233            }234            if page < pages {235                HStack { Spacer(); ProgressView(); Spacer() }.padding(.vertical, 18)236            } else if let source {237                Text("Source : \(source).").font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.top, 16)238            }239        }240    }241242    private func reload() async {243        loading = true; error = nil244        do {245            let f = try await APIClient.shared.sales(filters, page: 1)246            if Task.isCancelled { return }247            rows = f.value.rows; page = f.value.page; pages = f.value.pages; total = f.value.total248            updatedTo = f.value.updatedTo; source = f.value.source; stale = f.stale249        } catch is CancellationError {250            return251        } catch {252            rows = []; total = 0; self.error = apiError(error)253        }254        loading = false255    }256257    private func loadMore() async {258        guard !loading, page < pages else { return }259        loading = true260        defer { loading = false }261        let current = filters262        if let f = try? await APIClient.shared.sales(current, page: page + 1), current == filters {263            let known = Set(rows.map(\.id))264            rows += f.value.rows.filter { !known.contains($0.id) }265            page = f.value.page; pages = f.value.pages266        }267    }268}269270struct SaleFiltersSheet: View {271    @Binding var filters: SaleFilters272    @Environment(\.dismiss) private var dismiss273274    var body: some View {275        NavigationStack {276            ScrollView {277                VStack(alignment: .leading, spacing: 22) {278                    VStack(alignment: .leading, spacing: 10) {279                        Text("Type de propriété").eyebrowStyle()280                        FlowChips(options: SaleFilters.types, selection: $filters.type)281                    }282                    VStack(alignment: .leading, spacing: 10) {283                        Text("Prix vendu").eyebrowStyle()284                        PriceRangeFields(min: $filters.min, max: $filters.max)285                    }286                    VStack(alignment: .leading, spacing: 10) {287                        Text("Période").eyebrowStyle()288                        SlidingSegmented(selection: $filters.period, options: SaleFilters.Period.allCases.map { ($0, $0.label) }, label: "Période")289                    }290                }291                .padding(Theme.margin)292            }293            .background(Theme.bg)294            .navigationTitle("Filtres")295            .navigationBarTitleDisplayMode(.inline)296            .toolbar {297                ToolbarItem(placement: .topBarLeading) {298                    Button("Réinitialiser") { filters.type = ""; filters.min = nil; filters.max = nil }299                        .disabled(filters.type.isEmpty && filters.min == nil && filters.max == nil)300                }301                ToolbarItem(placement: .confirmationAction) { Button("Terminé") { dismiss() }.fontWeight(.semibold) }302            }303        }304    }305}306
Files main
Menu

Theme