SPB Git

Repository Public

AVendreClient.tsx 16.8 KB 364 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | ACADEMIC RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * PROJECT METADATA8 * -----------------------------------------------------------------------------9 * Project          : UQO Éval10 * File             : src/app/a-vendre/AVendreClient.tsx11 * Module           : app12 * Repository       : https://git.spboucher.ai/uqo-eval13 * Project Website  : https://www.uqo-eval.app14 * Created          : 2026-10-0215 * Last Modified    : 2026-10-0216 *17 * =============================================================================18 * SOFTWARE MAINTAINER & AFFILIATION19 * =============================================================================20 *21 * Maintainer       : Simon-Pierre Boucher22 * Position         : Professor of Finance23 * Institution      : Université du Québec en Outaouais (UQO)24 * Department       : Département des sciences administratives25 * Website          : https://spboucher.ai26 * Git              : https://git.spboucher.ai27 *28 * Research Contact : research@spboucher.ai29 * Direct Contact   : simon@spboucher.ai30 * Security/Admin   : admin@spboucher.ai31 *32 * The affiliation is descriptive. It is not an institutional endorsement,33 * a license grant or a determination of ownership.34 *35 * =============================================================================36 * COPYRIGHT, AUTHORSHIP & DATA37 * =============================================================================38 *39 * Copyright (c) the author(s) of this work.40 * Ownership is not asserted by this notice; see the repository records.41 *42 * This header identifies the maintainer of the software. Scientific43 * authorship of any associated paper is stated in the paper itself and44 * is not changed by this notice. Datasets and third-party materials45 * remain the property of their respective owners and licensors.46 *47 * This file is governed by the applicable project license, copyright48 * notices, institutional agreements and relevant law.49 *50 * =============================================================================51 * LICENSE & MAINTENANCE52 * =============================================================================53 *54 * License          : None specified (no license file in this repository)55 * Classification   : Public56 *57 * =============================================================================58 * END OF SP BOUCHER SOURCE HEADER59 * =============================================================================60 */6162// UQO Éval — onglet « À vendre » : recherche, filtres et grille d'annonces.63"use client";64import { useCallback, useEffect, useMemo, useRef, useState } from "react";65import Link from "next/link";66import { usePathname, useRouter, useSearchParams } from "next/navigation";67import { useLang } from "@/components/LangContext";68import ListingCardView, { groupLabel } from "@/components/avendre/ListingCardView";69import { money, num, pct } from "@/components/avendre/fmt";70import type { AVendreOverview, SearchResult, SortKey, TypeGroupKey } from "@/lib/immoka";7172const SORT_LABELS: Record<SortKey, { fr: string; en: string }> = {73  recent: { fr: "Plus récentes", en: "Newest" },74  price_asc: { fr: "Prix croissant", en: "Price ↑" },75  price_desc: { fr: "Prix décroissant", en: "Price ↓" },76  deal: { fr: "Estimation ≫ prix (aubaines ?)", en: "Estimate ≫ price (bargains?)" },77  premium: { fr: "Prix ≫ estimation (primes ?)", en: "Price ≫ estimate (premiums?)" },78  est_desc: { fr: "Estimation décroissante", en: "Estimate ↓" },79};8081interface Filters {82  q: string;83  muni: string;84  group: TypeGroupKey | "";85  min: string;86  max: string;87  beds: string;88  eval: boolean;89  sort: SortKey;90  page: number;91}9293function readFilters(sp: URLSearchParams): Filters {94  return {95    q: sp.get("q") ?? "",96    muni: sp.get("muni") ?? "",97    group: (sp.get("group") as TypeGroupKey | null) ?? "",98    min: sp.get("min") ?? "",99    max: sp.get("max") ?? "",100    beds: sp.get("beds") ?? "",101    eval: sp.get("eval") === "1",102    sort: (sp.get("sort") as SortKey | null) ?? "recent",103    page: Math.max(1, Number(sp.get("page") ?? 1) || 1),104  };105}106107function toQuery(f: Filters): string {108  const sp = new URLSearchParams();109  if (f.q) sp.set("q", f.q);110  if (f.muni) sp.set("muni", f.muni);111  if (f.group) sp.set("group", f.group);112  if (f.min) sp.set("min", f.min);113  if (f.max) sp.set("max", f.max);114  if (f.beds) sp.set("beds", f.beds);115  if (f.eval) sp.set("eval", "1");116  if (f.sort !== "recent") sp.set("sort", f.sort);117  if (f.page > 1) sp.set("page", String(f.page));118  return sp.toString();119}120121function Kpi({ label, value, hint }: { label: string; value: string; hint?: string }) {122  return (123    <div className="border-t border-[var(--line)] py-3">124      <p className="klabel">{label}</p>125      <p className="vp-display mt-1 text-[24px] font-bold leading-none tracking-[-0.02em]">{value}</p>126      {hint && <p className="mt-1 text-[11.5px] leading-snug text-ink-3">{hint}</p>}127    </div>128  );129}130131export default function AVendreClient({ overview }: { overview: AVendreOverview }) {132  const { lang } = useLang();133  const fr = lang === "fr";134  const router = useRouter();135  const pathname = usePathname();136  const sp = useSearchParams();137  const [f, setF] = useState<Filters>(() => readFilters(new URLSearchParams(sp.toString())));138  // résultat + requête qui l'a produit : « en chargement » = la requête courante n'est pas encore servie139  const [res, setRes] = useState<(SearchResult & { qs: string }) | null>(null);140  const loading = res == null || res.qs !== toQuery(f);141  const [qDraft, setQDraft] = useState(f.q);142  const abortRef = useRef<AbortController | null>(null);143144  // URL ↔ état (partageable, retour arrière naturel)145  const apply = useCallback(146    (patch: Partial<Filters>, resetPage = true) => {147      setF((prev) => {148        const next = { ...prev, ...patch, page: resetPage ? 1 : (patch.page ?? prev.page) };149        const qs = toQuery(next);150        router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });151        return next;152      });153    },154    [router, pathname]155  );156157  // recherche texte : débounce 350 ms158  useEffect(() => {159    const id = setTimeout(() => {160      if (qDraft !== f.q) apply({ q: qDraft });161    }, 350);162    return () => clearTimeout(id);163  }, [qDraft, f.q, apply]);164165  useEffect(() => {166    abortRef.current?.abort();167    const ctl = new AbortController();168    abortRef.current = ctl;169    const qs = toQuery(f);170    fetch(`/api/avendre${qs ? `?${qs}` : ""}`, { signal: ctl.signal })171      .then((r) => r.json())172      .then((d: SearchResult) => {173        if (!ctl.signal.aborted) setRes({ ...d, qs });174      })175      .catch(() => {});176    return () => ctl.abort();177  }, [f]);178179  const pages = res ? Math.max(1, Math.ceil(res.total / res.per)) : 1;180  const groups = useMemo(() => res?.facets.groups ?? overview.groups, [res, overview]);181  const munis = res?.facets.munis ?? overview.topMunis;182183  return (184    <div className="space-y-10 py-8">185      {/* ================= masthead ================= */}186      <section className="rise">187        <div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1 border-b-2 border-ink pb-2.5">188          <nav className="vp-mono flex flex-wrap items-center gap-2 text-[10.5px] uppercase tracking-[0.08em] text-ink-3">189            <Link href="/" className="text-ink-2 hover:text-accent-deep">190              UQO&nbsp;Éval191            </Link>192            <span aria-hidden="true">/</span>193            <span>{fr ? "À vendre" : "For sale"}</span>194          </nav>195          <span className="vp-mono text-[10px] uppercase tracking-[0.08em] text-ink-3">196            {fr ? "Source : Immo-Ka · copie du" : "Source: Immo-Ka · snapshot of"} {overview.copiedAt ?? "—"}197          </span>198        </div>199        <div className="mt-6 grid gap-x-12 gap-y-8 lg:grid-cols-[1.6fr_1fr]">200          <div>201            <span className="kicker">{fr ? "Atelier d'évaluation" : "Valuation workshop"}</span>202            <h1 className="vp-display mt-2 text-[clamp(28px,4.5vw,46px)] font-bold uppercase leading-[1.02] tracking-[-0.03em]">203              {fr ? "Évaluer une propriété à vendre" : "Value a property for sale"}204            </h1>205            <p className="mt-4 max-w-2xl text-[15px] leading-relaxed text-ink-2">206              {fr207                ? "Toutes les propriétés réellement à vendre au Québec, déjà mesurées par le moteur UQO Éval. Choisissez-en une, sélectionnez vos propres comparables, ajustez-les en dollars, réconciliez votre valeur — puis confrontez-la à la mesure du laboratoire et au prix demandé."208                : "Every property actually for sale in Québec, already measured by the UQO Éval engine. Pick one, select your own comparables, adjust them in dollars, reconcile your value — then confront it with the lab's measure and the asking price."}209            </p>210          </div>211          <aside className="grid grid-cols-2 gap-x-6 lg:grid-cols-1 lg:border-l lg:border-[var(--line)] lg:pl-10">212            <Kpi label={fr ? "Propriétés à vendre" : "Properties for sale"} value={num(overview.total, lang)} />213            <Kpi214              label={fr ? "Déjà évaluées par le moteur" : "Already valued by the engine"}215              value={num(overview.evaluated, lang)}216              hint={fr ? "jumelage spatial au rôle d'évaluation" : "spatially matched to the assessment roll"}217            />218            <Kpi label={fr ? "Prix demandé médian" : "Median asking price"} value={money(overview.medianPrice, lang)} />219            <Kpi220              label={fr ? "Ratio médian estimation / prix" : "Median estimate / price ratio"}221              value={overview.medianRatio != null ? overview.medianRatio.toLocaleString(fr ? "fr-CA" : "en-CA", { maximumFractionDigits: 3 }) : "—"}222              hint={fr ? "< 1 : le marché demande plus que la mesure" : "< 1: sellers ask more than the measure"}223            />224          </aside>225        </div>226      </section>227228      {/* ================= filtres ================= */}229      <section className="space-y-4">230        <div className="grid gap-4 md:grid-cols-[2fr_1fr_1fr]">231          <label className="block">232            <span className="klabel">{fr ? "Adresse, ville, secteur, n° MLS" : "Address, city, sector, MLS #"}</span>233            <input234              value={qDraft}235              onChange={(e) => setQDraft(e.target.value)}236              placeholder={fr ? "ex. Gatineau, rue Principale, Sherbrooke…" : "e.g. Gatineau, Main street, Sherbrooke…"}237              className="vp-input mt-1"238              type="search"239            />240          </label>241          <label className="block">242            <span className="klabel">{fr ? "Municipalité" : "Municipality"}</span>243            <select value={f.muni} onChange={(e) => apply({ muni: e.target.value })} className="vp-input mt-1 cursor-pointer">244              <option value="">{fr ? "Toutes" : "All"}</option>245              {f.muni && !munis.some((m) => m.name === f.muni) && <option value={f.muni}>{f.muni}</option>}246              {munis.map((m) => (247                <option key={m.name} value={m.name}>248                  {m.name} ({num(m.n, lang)})249                </option>250              ))}251            </select>252          </label>253          <label className="block">254            <span className="klabel">{fr ? "Tri" : "Sort"}</span>255            <select value={f.sort} onChange={(e) => apply({ sort: e.target.value as SortKey })} className="vp-input mt-1 cursor-pointer">256              {(Object.keys(SORT_LABELS) as SortKey[]).map((k) => (257                <option key={k} value={k}>258                  {fr ? SORT_LABELS[k].fr : SORT_LABELS[k].en}259                </option>260              ))}261            </select>262          </label>263        </div>264265        {/* groupes de types */}266        <div className="flex flex-wrap gap-x-4 gap-y-1 border-b border-[var(--line)]">267          <button type="button" className="vp-tab" aria-pressed={f.group === ""} onClick={() => apply({ group: "" })}>268            {fr ? "Tous" : "All"}269          </button>270          {groups.map((g) => (271            <button key={g.key} type="button" className="vp-tab" aria-pressed={f.group === g.key} onClick={() => apply({ group: g.key })}>272              {groupLabel(g.key, fr)} <span className="text-ink-3">{num(g.n, lang)}</span>273            </button>274          ))}275        </div>276277        <div className="grid gap-4 sm:grid-cols-2 md:grid-cols-4">278          <label className="block">279            <span className="klabel">{fr ? "Prix min ($)" : "Min price ($)"}</span>280            <input value={f.min} onChange={(e) => apply({ min: e.target.value.replace(/\D/g, "") })} inputMode="numeric" className="vp-input mt-1" placeholder="0" />281          </label>282          <label className="block">283            <span className="klabel">{fr ? "Prix max ($)" : "Max price ($)"}</span>284            <input value={f.max} onChange={(e) => apply({ max: e.target.value.replace(/\D/g, "") })} inputMode="numeric" className="vp-input mt-1" placeholder="∞" />285          </label>286          <label className="block">287            <span className="klabel">{fr ? "Chambres (min)" : "Bedrooms (min)"}</span>288            <select value={f.beds} onChange={(e) => apply({ beds: e.target.value })} className="vp-input mt-1 cursor-pointer">289              <option value="">—</option>290              {[1, 2, 3, 4, 5].map((n) => (291                <option key={n} value={n}>292                  {n}+293                </option>294              ))}295            </select>296          </label>297          <label className="flex items-end gap-2 pb-2 text-[13px]">298            <input type="checkbox" checked={f.eval} onChange={(e) => apply({ eval: e.target.checked })} className="h-4 w-4 accent-[var(--accent)]" />299            {fr ? "Seulement les annonces déjà évaluées" : "Only listings already valued"}300          </label>301        </div>302      </section>303304      {/* ================= résultats ================= */}305      <section>306        <div className="flex flex-wrap items-baseline justify-between gap-2 border-b-2 border-ink pb-2">307          <p className="vp-mono text-[11px] uppercase tracking-[0.08em] text-ink-2">308            {res ? (309              <>310                <b className="text-ink">{num(res.total, lang)}</b> {fr ? "propriétés" : "properties"}311                {res.summary.medianPrice != null && (312                  <>313                    {" · "}314                    {fr ? "prix médian" : "median price"} <b className="text-ink">{money(res.summary.medianPrice, lang)}</b>315                  </>316                )}317                {res.summary.medianRatio != null && (318                  <>319                    {" · "}320                    {fr ? "estimation vs prix (médiane)" : "estimate vs price (median)"}{" "}321                    <b className="text-ink">{pct((res.summary.medianRatio - 1) * 100, lang, 1)}</b>322                  </>323                )}324              </>325            ) : (326              fr ? "Chargement…" : "Loading…"327            )}328          </p>329          <p className="vp-mono text-[10.5px] uppercase tracking-[0.08em] text-ink-3">330            {fr ? "page" : "page"} {f.page} / {pages}331          </p>332        </div>333334        <div className={`mt-5 grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 ${loading ? "opacity-60" : ""}`}>335          {res?.items.map((c) => <ListingCardView key={c.uid} c={c} fr={fr} />)}336        </div>337        {res && res.items.length === 0 && (338          <p className="py-16 text-center text-ink-3">{fr ? "Aucune propriété ne correspond à ces filtres." : "No property matches these filters."}</p>339        )}340341        {pages > 1 && (342          <div className="mt-8 flex items-center justify-center gap-3">343            <button type="button" className="btn btn-ghost" disabled={f.page <= 1} onClick={() => apply({ page: f.page - 1 }, false)}>344              ← {fr ? "Précédent" : "Previous"}345            </button>346            <span className="vp-mono text-[11px] uppercase tracking-[0.08em] text-ink-2">347              {f.page} / {pages}348            </span>349            <button type="button" className="btn btn-ghost" disabled={f.page >= pages} onClick={() => apply({ page: f.page + 1 }, false)}>350              {fr ? "Suivant" : "Next"} →351            </button>352          </div>353        )}354      </section>355356      <p className="vp-mono border-t border-[var(--line)] pt-3 text-[10px] uppercase tracking-[0.05em] text-ink-3">357        {fr358          ? "Annonces : copie de la base Immo-Ka (groupe Ka), agrégées de sources publiques ; photos et descriptions appartiennent aux courtiers et vendeurs. Estimations UQO Éval à vocation pédagogique — pas une évaluation professionnelle (OEAQ)."359          : "Listings: copy of the Immo-Ka database (Ka group), aggregated from public sources; photos and descriptions belong to brokers and sellers. UQO Éval estimates are educational — not a professional appraisal (OEAQ)."}360      </p>361    </div>362  );363}364
Files main
Menu

Theme