Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Lou-Ka iOS9// File : LouKa/Features/Favorites/FavoritesView.swift10// Description : Favoris — logements enregistrés (avec note personnelle),11// recherches enregistrées, accès au comparateur. Sans12// compte, tout reste sur l'appareil ; avec un compte,13// favoris, notes et recherches sont synchronisés.14// Module : LouKa15// Repository : https://git.spboucher.ai/lou-ka-ios-v316// Project Website : https://www.lou-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 @State private var sortByPrice = false102 @State private var editing: FavoriteItem?103 /// Nombre de logements que chaque recherche enregistrée trouve aujourd'hui (calculé à l'ouverture de l'onglet).104 @State private var liveTotals: [UUID: Int] = [:]105106 private var sorted: [FavoriteItem] {107 sortByPrice ? favorites.sorted { ($0.lastPrice ?? $0.price ?? .infinity) < ($1.lastPrice ?? $1.price ?? .infinity) } : favorites108 }109110 var body: some View {111 ScrollView {112 LazyVStack(alignment: .leading, spacing: 26) {113 if !library.compareIDs.isEmpty {114 NavigationLink(value: Route.compare) {115 HStack(spacing: 14) {116 Image(systemName: "scalemass.fill").foregroundStyle(Theme.brandInk)117 .frame(width: 44, height: 44).background(Theme.brand, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))118 VStack(alignment: .leading, spacing: 2) {119 Text("Comparateur").font(.headline).foregroundStyle(Theme.ink)120 Text(Fmt.plural(library.compareIDs.count, "logement à comparer", "logements à comparer")).font(.footnote).foregroundStyle(Theme.ink3)121 }122 Spacer()123 Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink3)124 }125 .cardStyle(padding: 14)126 }127 .buttonStyle(.plain)128 }129130 if favorites.isEmpty {131 EmptyStateView(door: .heart, title: "Aucun favori pour l'instant",132 message: account.isSignedIn ? "Touchez le cœur d'un logement pour le retrouver ici et sur vos autres appareils."133 : "Touchez le cœur d'un logement pour le retrouver ici. Sans compte, vos favoris restent sur cet appareil.",134 actionTitle: "Explorer la carte") { app.tab = .explore }135 } else {136 VStack(alignment: .leading, spacing: 14) {137 SectionHeader(title: Fmt.plural(favorites.count, "favori", "favoris")) {138 SlidingSegmented(selection: $sortByPrice, options: [(false, "Récents"), (true, "Prix")], label: "Tri des favoris")139 }140 ForEach(Array(sorted.enumerated()), id: \.element.uid) { i, f in141 FavoriteRow(item: f) { editing = f }.staggered(i)142 }143 }144 }145146 if !searches.isEmpty {147 VStack(alignment: .leading, spacing: 12) {148 SectionHeader(title: "Recherches enregistrées")149 ForEach(searches) { s in150 HStack {151 Button { if let p = s.phrase, !p.isEmpty { app.explore(phrase: p) } else { app.explore(s.filters, sort: s.sort) } } label: {152 HStack(spacing: 12) {153 Image(systemName: "bookmark.fill").foregroundStyle(Theme.brand)154 VStack(alignment: .leading, spacing: 2) {155 Text(s.label).font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink).lineLimit(1)156 Text(searchCaption(s)).font(.caption).num().foregroundStyle(Theme.ink3)157 }158 Spacer()159 }160 .contentShape(Rectangle())161 }162 .buttonStyle(.plain)163 Button(role: .destructive) { library.delete(s) } label: {164 Image(systemName: "trash").font(.footnote).foregroundStyle(Theme.ink3).frame(width: 40, height: 40)165 }166 .accessibilityLabel("Supprimer la recherche \(s.label)")167 }168 .cardStyle(padding: 12)169 }170 }171 }172173 FavoritesAccountNote()174 }175 .padding(20)176 .frame(maxWidth: 760)177 .frame(maxWidth: .infinity)178 }179 .background(Theme.bg)180 .navigationTitle("Favoris")181 .sheet(item: $editing) { f in NoteEditor(item: f) }182 .task(id: favorites.count) { await refresh() }183 .refreshable { await account.sync.sync(); await refresh() }184 }185186 private func searchCaption(_ s: SavedSearchItem) -> String {187 let saved = s.savedAt.formatted(.dateTime.day().month().locale(Fmt.locale))188 guard let now = liveTotals[s.id] else {189 return "\(s.lastTotal.map { Fmt.plural($0, "logement", "logements") + " · " } ?? "")enregistrée le \(saved)"190 }191 var t = "\(Fmt.plural(now, "logement", "logements")) aujourd'hui"192 if let was = s.lastTotal, was != now { t += " (\(Fmt.int(was)) le \(saved))" }193 return t194 }195196 /// Rafraîchit l'état des favoris (toujours en ligne ? prix actuel ?) et le compte des recherches enregistrées.197 private func refresh() async {198 for s in searches.prefix(12) where liveTotals[s.id] == nil && (s.phrase ?? "").isEmpty {199 if let r = try? await APIClient.shared.search(s.filters, sort: s.sort, limit: 1) { liveTotals[s.id] = r.total }200 }201 for f in favorites.prefix(40) {202 do {203 let l = try await APIClient.shared.listingV3(f.uid)204 f.offline = false205 f.lastPrice = l.plausiblePrice206 // favori venu d'un autre appareil avec un aperçu incomplet : complété par la fiche207 if f.title.isEmpty || f.image == nil || f.unitType.isEmpty { f.fill(from: l); library.persist() }208 } catch APIError.notFound, APIError.gone {209 f.offline = true210 } catch {211 return // hors ligne : on garde le dernier état connu212 }213 }214 }215}216217private struct FavoriteRow: View {218 let item: FavoriteItem219 var onNote: () -> Void220 @Environment(Library.self) private var library221 @Environment(AppModel.self) private var app222 @Environment(DoorCenter.self) private var door223 @Environment(\.accessibilityReduceMotion) private var reduceMotion224 @State private var frame: CGRect = .zero225226 var body: some View {227 VStack(alignment: .leading, spacing: 0) {228 Button {229 let uid = item.uid230 door.open(uid: uid, image: item.image, from: CGRect(x: frame.minX, y: frame.minY, width: 118, height: min(frame.height, 130)),231 origin: .favorite, reduceMotion: reduceMotion) { app.open(.listing(uid)) }232 } label: {233 HStack(spacing: 0) {234 RemoteImage(source: item.image).frame(width: 118).frame(minHeight: 108).clipped()235 VStack(alignment: .leading, spacing: 5) {236 HStack(alignment: .firstTextBaseline, spacing: 8) {237 PriceText(price: item.lastPrice ?? item.price, size: 20)238 if let was = item.price, let now = item.lastPrice, now > was + 1 {239 Text("+\(Fmt.money(now - was))").font(.caption.weight(.semibold)).foregroundStyle(Theme.high)240 .padding(.horizontal, 7).padding(.vertical, 3).background(Theme.highSoft, in: RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous))241 .accessibilityLabel("Hausse de \(Fmt.money(now - was)) depuis l'enregistrement")242 }243 if let was = item.price, let now = item.lastPrice, now < was - 1 {244 Text("−\(Fmt.money(was - now))").font(.caption.weight(.semibold)).foregroundStyle(Theme.good)245 .padding(.horizontal, 7).padding(.vertical, 3).background(Theme.goodSoft, in: RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous))246 .accessibilityLabel("Baisse de \(Fmt.money(was - now)) depuis l'enregistrement")247 }248 }249 Text([item.unitType, item.displayTitle].filter { !$0.isEmpty }.joined(separator: " · ")).font(.subheadline.weight(.medium))250 .foregroundStyle(Theme.ink).lineLimit(1)251 Text(item.place).font(.footnote).foregroundStyle(Theme.ink3).lineLimit(1)252 if item.offline {253 Label("N'est plus en ligne", systemImage: "clock.badge.xmark").font(.caption.weight(.medium)).foregroundStyle(Theme.high)254 }255 }256 .padding(12)257 .frame(maxWidth: .infinity, alignment: .leading)258 }259 .fixedSize(horizontal: false, vertical: true)260 }261 .buttonStyle(PressScaleStyle())262 .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { frame = $0 }263 Divider().overlay(Theme.line)264 HStack(spacing: 4) {265 Button(action: onNote) {266 Label(item.note.isEmpty ? "Ajouter une note" : item.note, systemImage: "note.text")267 .font(.footnote).foregroundStyle(item.note.isEmpty ? Theme.ink3 : Theme.ink2).lineLimit(1)268 .frame(maxWidth: .infinity, alignment: .leading)269 }270 .buttonStyle(.plain)271 let inCompare = library.compareIDs.contains(item.uid)272 Button {273 if library.toggleCompare(item.uid) == .full { app.showToast("Le comparateur contient déjà \(Library.compareMax) logements") }274 } label: {275 Image(systemName: inCompare ? "scalemass.fill" : "scalemass").foregroundStyle(inCompare ? Theme.brand : Theme.ink3).frame(width: 40, height: 36)276 }277 .accessibilityLabel(inCompare ? "Retirer du comparateur" : "Ajouter au comparateur")278 Button {279 library.removeFavorite(item.uid)280 Haptics.tap()281 } label: {282 Image(systemName: "heart.slash").foregroundStyle(Theme.ink3).frame(width: 40, height: 36)283 }284 .accessibilityLabel("Retirer des favoris")285 }286 .padding(.horizontal, 12).padding(.vertical, 4)287 }288 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))289 .overlay(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous).strokeBorder(Theme.line, lineWidth: 1))290 .clipShape(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))291 }292}293294private struct NoteEditor: View {295 @Bindable var item: FavoriteItem296 @Environment(\.dismiss) private var dismiss297 @Environment(Library.self) private var library298 @State private var original: String?299 @FocusState private var focused: Bool300 var body: some View {301 NavigationStack {302 TextEditor(text: $item.note)303 .focused($focused)304 .scrollContentBackground(.hidden)305 .padding(12)306 .background(Theme.surface2, in: RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))307 .padding(20)308 .background(Theme.bg)309 .navigationTitle("Note personnelle")310 .navigationBarTitleDisplayMode(.inline)311 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() } } }312 .onAppear { focused = true; if original == nil { original = item.note } }313 }314 .presentationDetents([.medium])315 // note modifiée : datée et envoyée au compte, s'il y en a un316 .onDisappear { if let original, original != item.note { library.noteChanged(item.uid) } }317 }318}319