Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka iOS9// File : ImmoKa/Features/Favorites/FavoritesView.swift10// Description : favoris (instantané et note personnelle), comparateur,11// recherches enregistrées et fiches récemment consultées.12// Sans compte, tout reste sur l'appareil ; avec un compte,13// favoris, notes et recherches sont synchronisés.14// Module : ImmoKa15// Repository : https://git.spboucher.ai/immo-ka-ios-v316// Project Website : https://www.immo-ka.com17// Created : 2026-11-2518// Last Modified : 2026-11-3019//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 SwiftData93import SwiftUI9495struct FavoritesView: View {96 @Environment(AppModel.self) private var app97 @Environment(Library.self) private var library98 @Environment(Account.self) private var account99 @Query(sort: \FavoriteItem.savedAt, order: .reverse) private var favorites: [FavoriteItem]100 @Query(sort: \SavedSearchItem.savedAt, order: .reverse) private var searches: [SavedSearchItem]101 @Query(sort: \SeenItem.at, order: .reverse) private var seen: [SeenItem]102 @State private var sortByPrice = false103 @State private var editing: FavoriteItem?104105 private var sorted: [FavoriteItem] {106 sortByPrice ? favorites.sorted { ($0.price ?? .infinity) < ($1.price ?? .infinity) } : favorites107 }108109 /// Fiches récemment consultées qui ne sont pas déjà en favori.110 private var recent: [SeenItem] { seen.filter { !library.favoriteIDs.contains($0.uid) } }111112 var body: some View {113 ScrollView {114 LazyVStack(alignment: .leading, spacing: 30) {115 if !library.compareIDs.isEmpty {116 NavigationLink(value: Route.compare) {117 HStack(spacing: 14) {118 Image(systemName: "rectangle.split.2x1").font(.system(size: 17)).foregroundStyle(Theme.brand).frame(width: 26)119 VStack(alignment: .leading, spacing: 2) {120 Text("Comparateur").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)121 Text(Fmt.plural(library.compareIDs.count, "propriété à comparer", "propriétés à comparer")).font(.footnote).num().foregroundStyle(Theme.ink3)122 }123 Spacer()124 Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink3)125 }126 .cardStyle(padding: 14)127 }128 .buttonStyle(.plain)129 .accessibilityIdentifier("favorites.compare")130 }131 if favorites.isEmpty {132 EmptyStateView(door: .heart, title: "Aucun favori pour l'instant",133 message: account.isSignedIn ? "Touchez le cœur d'une propriété pour la retrouver ici et sur vos autres appareils."134 : "Touchez le cœur d'une propriété pour la retrouver ici. Sans compte, vos favoris restent sur cet appareil.",135 actionTitle: "Explorer la carte") { app.tab = .explore }136 } else {137 VStack(alignment: .leading, spacing: 14) {138 SectionHeader(title: Fmt.plural(favorites.count, "favori", "favoris")) {139 SlidingSegmented(selection: $sortByPrice, options: [(false, "Récents"), (true, "Prix")], label: "Tri des favoris")140 }141 ForEach(Array(sorted.enumerated()), id: \.element.uid) { i, f in142 FavoriteRow(item: f) { editing = f }.staggered(i)143 }144 }145 .animation(.snappy, value: sortByPrice)146 }147 if !searches.isEmpty {148 VStack(alignment: .leading, spacing: 4) {149 SectionHeader(title: "Recherches enregistrées").padding(.bottom, 6)150 ForEach(searches) { s in151 HStack {152 Button { app.explore(s.filters, sort: s.sort) } label: {153 HStack(spacing: 12) {154 Image(systemName: "bookmark").foregroundStyle(Theme.brand).frame(width: 22)155 VStack(alignment: .leading, spacing: 2) {156 Text(s.label).font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink).lineLimit(1)157 Text("\(s.lastTotal.map { Fmt.plural($0, "propriété", "propriétés") + " · " } ?? "")\(s.savedAt.formatted(.dateTime.day().month().locale(Fmt.locale)))")158 .font(.caption).num().foregroundStyle(Theme.ink3)159 }160 Spacer()161 }162 .contentShape(Rectangle())163 }164 .buttonStyle(.plain)165 Button(role: .destructive) { withAnimation(.snappy) { library.delete(s) } } label: {166 Image(systemName: "trash").font(.footnote).foregroundStyle(Theme.ink3).frame(width: 44, height: 44)167 }168 .accessibilityLabel("Supprimer la recherche \(s.label)")169 }170 Divider().overlay(Theme.line)171 }172 }173 }174 if !recent.isEmpty {175 VStack(alignment: .leading, spacing: 12) {176 SectionHeader(title: "Récemment consultées") {177 if recent.count > 4 {178 NavigationLink(value: Route.recent) { Text("Tout voir").font(.subheadline.weight(.semibold)) }179 }180 }181 ForEach(recent.prefix(4), id: \.uid) { s in182 SnapshotRow(item: s, caption: "Consultée \(Fmt.ago(s.at.timeIntervalSince1970))")183 }184 }185 }186 FavoritesAccountNote()187 }188 .padding(20)189 .frame(maxWidth: 760)190 .frame(maxWidth: .infinity)191 }192 .background(Theme.bg)193 .navigationTitle("Favoris")194 .sheet(item: $editing) { f in NoteEditor(item: f) }195 .task(id: favorites.count) { await fillIncomplete() }196 .refreshable { await account.sync.sync(); await fillIncomplete() }197 }198199 /// Favoris venus d'un autre appareil avec un aperçu incomplet : complétés par la fiche, une fois.200 private func fillIncomplete() async {201 for f in favorites.prefix(40) where f.needsFill {202 guard let l = try? await APIClient.shared.fullListing(f.uid) else { continue }203 f.fill(from: l)204 library.persist()205 }206 }207}208209private struct FavoriteRow: View {210 let item: FavoriteItem211 var onNote: () -> Void212 @Environment(Library.self) private var library213 @Environment(AppModel.self) private var app214215 var body: some View {216 VStack(alignment: .leading, spacing: 0) {217 SnapshotRow(item: item, caption: priceChange) { EmptyView() }218 .padding(12)219 Divider().overlay(Theme.line)220 HStack(spacing: 4) {221 Button(action: onNote) {222 Label(item.note.isEmpty ? "Ajouter une note" : item.note, systemImage: "note.text")223 .font(.footnote).foregroundStyle(item.note.isEmpty ? Theme.ink3 : Theme.ink2).lineLimit(1)224 .frame(maxWidth: .infinity, alignment: .leading)225 .frame(minHeight: 40)226 }227 .buttonStyle(.plain)228 let inCompare = library.compareIDs.contains(item.uid)229 Button {230 if library.toggleCompare(item.uid) == .full { app.showToast("Le comparateur contient déjà \(Library.compareMax) propriétés") }231 Haptics.select()232 } label: {233 Image(systemName: inCompare ? "rectangle.split.2x1.fill" : "rectangle.split.2x1").foregroundStyle(inCompare ? Theme.brand : Theme.ink3).frame(width: 44, height: 40)234 }235 .accessibilityLabel(inCompare ? "Retirer du comparateur" : "Ajouter au comparateur")236 Button {237 withAnimation(.snappy) { library.removeFavorite(item.uid) }238 Haptics.tap()239 } label: {240 Image(systemName: "heart.slash").foregroundStyle(Theme.ink3).frame(width: 44, height: 40)241 }242 .accessibilityLabel("Retirer des favoris")243 }244 .padding(.horizontal, 12)245 }246 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))247 .overlay(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous).strokeBorder(Theme.line, lineWidth: 1))248 }249250 /// Variation du prix depuis l'enregistrement.251 private var priceChange: String? {252 guard let was = item.savedPrice, let now = item.price, abs(now - was) >= 1 else { return nil }253 return now < was ? "Baisse de \(Fmt.money(was - now)) depuis l'enregistrement" : "Hausse de \(Fmt.money(now - was)) depuis l'enregistrement"254 }255}256257private struct NoteEditor: View {258 @Bindable var item: FavoriteItem259 @Environment(\.dismiss) private var dismiss260 @Environment(Library.self) private var library261 @State private var original: String?262 @FocusState private var focused: Bool263264 var body: some View {265 NavigationStack {266 TextEditor(text: $item.note)267 .focused($focused)268 .scrollContentBackground(.hidden)269 .padding(12)270 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))271 .overlay(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous).strokeBorder(Theme.line2, lineWidth: 1))272 .padding(20)273 .background(Theme.bg)274 .navigationTitle("Note personnelle")275 .navigationBarTitleDisplayMode(.inline)276 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() } } }277 .onAppear { focused = true; if original == nil { original = item.note } }278 }279 .presentationDetents([.medium])280 // note modifiée : datée et envoyée au compte, s'il y en a un281 .onDisappear { if let original, original != item.note { library.noteChanged(item.uid) } }282 }283}284285/// Toutes les fiches récemment consultées.286struct RecentView: View {287 @Environment(Library.self) private var library288 @Environment(AppModel.self) private var app289 @Query(sort: \SeenItem.at, order: .reverse) private var seen: [SeenItem]290291 var body: some View {292 Group {293 if seen.isEmpty {294 EmptyStateView(door: .ajar, title: "Aucune fiche consultée",295 message: "Les propriétés que vous ouvrez sont gardées ici, sur votre appareil.",296 actionTitle: "Explorer la carte") { app.tab = .explore }297 } else {298 ScrollView {299 LazyVStack(alignment: .leading, spacing: 14) {300 ForEach(Array(seen.enumerated()), id: \.element.uid) { i, s in301 SnapshotRow(item: s, caption: "Consultée \(Fmt.ago(s.at.timeIntervalSince1970))").staggered(i)302 Divider().overlay(Theme.line)303 }304 }305 .padding(20)306 .frame(maxWidth: 760)307 .frame(maxWidth: .infinity)308 }309 }310 }311 .background(Theme.bg)312 .navigationTitle("Récemment consultées")313 .navigationBarTitleDisplayMode(.inline)314 .toolbar {315 if !seen.isEmpty {316 ToolbarItem(placement: .topBarTrailing) { Button("Effacer") { withAnimation { library.clearSeen() } } }317 }318 }319 }320}321