SPB Git

Repository Public

Analyses.tsx 18.0 KB 371 lines tsx

1// Analyses : juste valeur, coût réel, historique de l'annonce.23import { DrawOnView } from "@/lib/motion";4import { useState } from "react";5import { useQuery } from "@tanstack/react-query";6import { Link } from "react-router";7import { ArrowRight, Check, Gauge, History as HistoryIcon, HelpCircle, Receipt, Zap } from "lucide-react";8import {9  fetchCoutReel, fetchHistorique, fetchHydro, fetchRecyclees, priceOk,10  type CoutReel, type CoutReelLigne, type FairValueDetail, type HydroEstimate, type Listing,11} from "@/lib/api";12import { cn } from "@/lib/cn";13import { fmtInt, fmtMoney, fmtPct } from "@/lib/format";14import { prettySource, useInView, useSourceNames } from "@/lib/hooks";15import { FairValueGauge, VERDICT, VerdictPill } from "@/components/Verdict";16import { fmtDay, fmtMonth, Lines, MoreLink, Panel, Pill, SourceLine, Tile } from "./kit";1718// --- Juste valeur ---------------------------------------------------------------19const CONF: Record<string, string> = { fort: "Confiance élevée", moyen: "Confiance moyenne", faible: "Confiance faible" };2021function Histogram({ fv, price }: { fv: FairValueDetail; price: number }) {22  const bins = fv.histogram ?? [];23  if (bins.length < 3) return null;24  const max = Math.max(...bins.map((b) => b.n), 1);25  const lo = bins[0]!.x0;26  const hi = bins[bins.length - 1]!.x1;27  const pos = (x: number) => `${Math.min(100, Math.max(0, ((x - lo) / (hi - lo)) * 100))}%`;28  const color = fv.verdict ? VERDICT[fv.verdict].color : "var(--brand)";29  return (30    <div className="mt-7">31      <div className="mb-2 text-[0.84rem] font-medium text-ink-2">32        Loyers de {fmtInt(fv.segment_n)} logements comparables du même secteur33      </div>34      <div className="relative">35        <DrawOnView className="flex h-28 items-end gap-[3px]" role="img" label="Distribution des loyers des logements comparables du même secteur">36          {bins.map((b, bi) => {37            const mine = price >= b.x0 && price < b.x1;38            const inBand = b.x1 > fv.fv_low && b.x0 < fv.fv_high;39            return (40              <div41                key={b.x0}42                title={`${fmtMoney(b.x0)} à ${fmtMoney(b.x1)} : ${b.n} logements`}43                className={cn("lk-draw-col flex-1 rounded-t-[5px]", mine ? "" : inBand ? "bg-brand/45" : "bg-surface-3")}44                style={{ height: `${Math.max(4, (b.n / max) * 100)}%`, background: mine ? color : undefined, ["--i" as string]: bi }}45              />46            );47          })}48        </DrawOnView>49        {price >= lo && price <= hi && (50          <div className="pointer-events-none absolute -top-1 bottom-0 w-px" style={{ left: pos(price), background: color }} />51        )}52      </div>53      <div className="num mt-1.5 flex justify-between text-[0.72rem] text-ink-3">54        <span>{fmtMoney(lo)}</span>55        <span>{fmtMoney(Math.round((lo + hi) / 2))}</span>56        <span>{fmtMoney(hi)}</span>57      </div>58      <div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-[0.76rem] text-ink-3">59        <span className="inline-flex items-center gap-1.5">60          <span className="size-2.5 rounded-sm" style={{ background: color }} /> Ce logement61        </span>62        <span className="inline-flex items-center gap-1.5">63          <span className="size-2.5 rounded-sm bg-brand/45" /> Fourchette de juste valeur64        </span>65      </div>66    </div>67  );68}6970export function FairValuePanel({ l, fv, loading }: { l: Listing; fv: FairValueDetail | undefined; loading: boolean }) {71  if (!priceOk(l.price) && !loading) return null;72  if (loading)73    return (74      <Panel icon={<Gauge className="size-5" />} title="Juste valeur du loyer">75        <Lines n={4} />76      </Panel>77    );78  if (!fv || !priceOk(l.price)) return null;79  const dev = fv.deviation;80  const diff = Math.round(l.price - fv.fv);81  return (82    <Panel83      icon={<Gauge className="size-5" />}84      title="Juste valeur du loyer"85      aside={fv.verdict ? <VerdictPill verdict={fv.verdict} deviation={dev} size="md" /> : <Pill>Prix atypique</Pill>}86    >87      {fv.verdict ? (88        <p className="text-[1.05rem] leading-relaxed text-ink">89          {fv.verdict === "marche" ? (90            <>Ce loyer correspond au marché : la valeur estimée est de <b className="num">{fmtMoney(fv.fv)}</b> par mois.</>91          ) : (92            <>93              Ce loyer est <b className={cn("num", VERDICT[fv.verdict].tone)}>{fmtMoney(Math.abs(diff))}</b> {diff < 0 ? "sous" : "au-dessus de"} la valeur94              estimée de <b className="num">{fmtMoney(fv.fv)}</b> par mois ({fmtPct(dev)}).95            </>96          )}97        </p>98      ) : (99        <p className="text-[0.98rem] leading-relaxed text-ink-2">100          La valeur estimée est de <b className="num text-ink">{fmtMoney(fv.fv)}</b> par mois. L'écart avec le prix affiché est trop grand pour rendre un101          verdict fiable : le prix est peut-être partiel (par chambre, par semaine) ou erroné. Vérifiez l'annonce originale.102        </p>103      )}104      {fv.verdict && <FairValueGauge price={l.price} fv={fv.fv} low={fv.fv_low} high={fv.fv_high} verdict={fv.verdict} />}105      <div className="mt-4 grid grid-cols-3 gap-2.5">106        <Tile value={fmtMoney(fv.fv)} label="Valeur estimée" />107        <Tile value={`${fmtInt(fv.fv_low)} à ${fmtMoney(fv.fv_high)}`} label="Fourchette" className="[&>div:first-child]:text-[0.95rem] sm:[&>div:first-child]:text-[1.2rem]" />108        <Tile value={fmtInt(fv.comps)} label="Comparables proches" />109      </div>110      <Histogram fv={fv} price={l.price} />111      <SourceLine>112        {CONF[fv.confidence] ?? "Confiance non précisée"} · estimation Lou-Ka à partir de logements de même grandeur dans le même secteur.{" "}113        <Link to="/juste-valeur" className="font-medium text-brand hover:underline">114          Comprendre la méthode115        </Link>116      </SourceLine>117    </Panel>118  );119}120121// --- Coût réel ------------------------------------------------------------------122function CostLine({ ln }: { ln: CoutReelLigne }) {123  const s = ln.statut;124  return (125    <li className="flex items-start justify-between gap-4 border-b border-line py-3 last:border-0">126      <div className="min-w-0">127        <div className="text-[0.95rem] font-medium text-ink">{ln.poste}</div>128        {(ln.note || ln.source) && <div className="mt-0.5 text-[0.78rem] leading-snug text-ink-3">{ln.note || ln.source}</div>}129      </div>130      <div className="num shrink-0 text-right text-[0.95rem] font-semibold">131        {s === "included" ? (132          <span className="inline-flex items-center gap-1 text-good">133            <Check className="size-4" strokeWidth={3} /> inclus134          </span>135        ) : s === "unknown" || ln.montant == null ? (136          <span className="inline-flex items-center gap-1 font-medium text-ink-3">137            <HelpCircle className="size-4" /> inconnu138          </span>139        ) : (140          <span className={s === "estimated" ? "text-brand" : "text-ink"}>141            {s === "estimated" ? "≈ " : ""}142            {fmtMoney(ln.montant)}143          </span>144        )}145      </div>146    </li>147  );148}149150function Hydro({ l, initial }: { l: Listing; initial: HydroEstimate | undefined }) {151  const [solved, setSolved] = useState<HydroEstimate | null>(null);152  const [busy, setBusy] = useState(false);153  const h = solved ?? initial;154  if (!h) return null;155  const visible = h.disponible || h.en_attente || !/captcha|configuré|incomplète/.test(h.raison || "");156  if (!visible) return null;157  const run = () => {158    setBusy(true);159    fetchHydro(l.address || l.title, { uid: l.uid, lat: l.lat, lng: l.lng }, true)160      .then(setSolved)161      .catch(() => undefined)162      .finally(() => setBusy(false));163  };164  return (165    <div className="mt-4 flex flex-wrap items-center justify-between gap-3 rounded-[10px] bg-surface-2 px-4 py-3.5">166      <div className="flex min-w-0 items-start gap-3">167        <Zap className="mt-0.5 size-4.5 shrink-0 text-high" />168        <div className="text-[0.9rem] leading-snug">169          {h.disponible && h.cout_mensuel != null ? (170            <>171              <span className="font-semibold text-ink">172                Électricité à cette adresse : <span className="num">{fmtMoney(h.cout_mensuel)}</span> par mois173              </span>174              <div className="num text-[0.78rem] text-ink-3">175                {h.cout_annuel != null ? `environ ${fmtMoney(h.cout_annuel)} par an` : ""}176                {h.kwh_annuel ? ` · ${fmtInt(h.kwh_annuel)} kWh` : ""} · estimation publique d'Hydro-Québec177              </div>178            </>179          ) : h.en_attente ? (180            <span className="text-ink-2">Estimation d'Hydro-Québec en cours de calcul pour cette adresse.</span>181          ) : (182            <span className="text-ink-2">Hydro-Québec publie une estimation de consommation par adresse.</span>183          )}184        </div>185      </div>186      {!h.disponible && !h.en_attente && (187        <button type="button" onClick={run} disabled={busy} className="h-9 shrink-0 rounded-[8px] border border-line-2 px-3 text-[0.84rem] font-medium text-ink transition-colors duration-150 hover:border-ink-3 disabled:opacity-60">188          {busy ? "Calcul…" : "Estimer"}189        </button>190      )}191    </div>192  );193}194195export function TrueCostPanel({ l }: { l: Listing }) {196  const [ref, inView] = useInView<HTMLDivElement>("300px");197  const q = useQuery({ queryKey: ["cout-reel", l.uid], queryFn: () => fetchCoutReel(l.uid), enabled: inView, staleTime: 6e5, retry: 0 });198  const hydro = useQuery({199    queryKey: ["hydro", l.uid],200    queryFn: () => fetchHydro(l.address || l.title, { uid: l.uid, lat: l.lat, lng: l.lng }),201    enabled: inView && !!(l.address || l.title),202    staleTime: 6e5,203    retry: 0,204  });205  if (q.isError) return <div ref={ref} />;206  const d: CoutReel | undefined = q.data;207  if (d && (!d.lignes?.length || d.loyer == null)) return <div ref={ref} />;208  const extra = d && d.total_estime != null && d.loyer != null ? d.total_estime - d.loyer : 0;209  return (210    <div ref={ref}>211      <Panel212        icon={<Receipt className="size-5" />}213        title="Coût réel par mois"214        aside={d && d.total_estime != null ? <span className="num text-[1.6rem] font-semibold tracking-tight">{fmtMoney(d.total_estime)}</span> : undefined}215      >216        {!d ? (217          <Lines n={5} />218        ) : (219          <>220            <p className="text-[0.95rem] leading-relaxed text-ink-2">221              {extra > 0 ? (222                <>223                  Au loyer s'ajoutent environ <b className="num text-ink">{fmtMoney(extra)}</b> de frais non inclus.224                </>225              ) : (226                <>Aucun frais supplémentaire connu ne s'ajoute au loyer affiché.</>227              )}228              {d.postes_inconnus.length > 0 && <> {d.postes_inconnus.length > 1 ? "Postes non précisés" : "Poste non précisé"} par l'annonce : {d.postes_inconnus.join(", ").toLowerCase()}.</>}229            </p>230            <ul className="mt-3">231              {d.lignes.map((ln) => (232                <CostLine key={ln.poste} ln={ln} />233              ))}234            </ul>235            <div className="mt-3 flex items-baseline justify-between gap-4 rounded-[10px] bg-surface-2 px-4 py-3.5">236              <span className="text-[0.95rem] font-semibold text-ink">Total estimé</span>237              <span className="num text-right">238                <span className="text-[1.15rem] font-semibold">{fmtMoney(d.total_estime)}</span>239                {d.annuel_estime != null && <span className="ml-2 text-[0.8rem] text-ink-3">{fmtMoney(d.annuel_estime)} par an</span>}240              </span>241            </div>242            {d.pi2 && (243              <p className="mt-3 text-[0.9rem] text-ink-2">244                Soit <b className="num text-ink">{d.pi2.valeur.toLocaleString("fr-CA", { minimumFractionDigits: 2, maximumFractionDigits: 2 })} $</b> le pied carré245                {d.pi2.percentile_ville != null && (246                  <>247                    , plus cher que <b className="num text-ink">{Math.round(d.pi2.percentile_ville)} %</b> des logements comparables248                    {d.pi2.portee_ville ? ` (${d.pi2.portee_ville.replace(/\.$/, "")})` : ""}249                  </>250                )}251                .252              </p>253            )}254            <Hydro l={l} initial={hydro.data} />255            <SourceLine>Loyer affiché, plus les frais non inclus observés ou estimés avec leur source. Un poste inconnu reste inconnu, jamais chiffré au hasard.</SourceLine>256          </>257        )}258      </Panel>259    </div>260  );261}262263// --- Historique -----------------------------------------------------------------264const EVENT: Record<string, string> = {265  description: "Description modifiée",266  superficie: "Superficie modifiée",267  dispo: "Disponibilité modifiée",268  inclusions: "Inclusions modifiées",269  photos: "Photos modifiées",270  disparition: "Annonce retirée",271  reapparition: "Annonce republiée",272};273274export function HistoryPanel({ l }: { l: Listing }) {275  const [ref, inView] = useInView<HTMLDivElement>("300px");276  const [all, setAll] = useState(false);277  const names = useSourceNames();278  const q = useQuery({ queryKey: ["historique", l.uid], queryFn: () => fetchHistorique(l.uid), enabled: inView, staleTime: 6e5, retry: 0 });279  const rec = useQuery({ queryKey: ["recyclees", l.uid], queryFn: () => fetchRecyclees(l.uid), enabled: inView, staleTime: 6e5, retry: 0 });280  if (q.isError) return <div ref={ref} />;281  const d = q.data;282  const matches = rec.data?.matches ?? [];283  const items = d ? (all ? d.timeline : d.timeline.slice(0, 5)) : [];284  const changed = d && d.prix_initial != null && d.prix_actuel != null && d.prix_initial !== d.prix_actuel;285  return (286    <div ref={ref}>287      <Panel icon={<HistoryIcon className="size-5" />} title="Historique de l'annonce">288        {!d ? (289          <Lines n={4} />290        ) : (291          <>292            <div className="grid grid-cols-3 gap-2.5">293              <Tile value={fmtDay(d.premiere_observation)} label="Suivie depuis" className="[&>div:first-child]:text-[1rem] sm:[&>div:first-child]:text-[1.2rem]" />294              <Tile value={`${fmtInt(d.jours_en_ligne)} j`} label="En ligne" />295              <Tile value={fmtInt(d.modifications)} label={d.modifications > 1 ? "Modifications" : "Modification"} />296            </div>297            {changed && (298              <p className="mt-4 flex flex-wrap items-center gap-2 text-[0.96rem] text-ink-2">299                <span className="num">{fmtMoney(d.prix_initial)}</span>300                <ArrowRight className="size-4 text-ink-3" />301                <b className="num text-ink">{fmtMoney(d.prix_actuel)}</b>302                {d.variation != null && Math.abs(d.variation) < 0.6 && <Pill tone={d.variation < 0 ? "good" : "warn"}>{fmtPct(d.variation)}</Pill>}303              </p>304            )}305            {items.length > 0 ? (306              <ol className="mt-5 space-y-0">307                {items.map((it, i) => (308                  <li key={`${it.ts}-${it.type}-${i}`} className="relative flex gap-3.5 pb-4 last:pb-0">309                    {i < items.length - 1 && <span className="absolute bottom-0 left-[5px] top-3 w-px bg-line-2" aria-hidden />}310                    <span className={cn("relative mt-1.5 size-[11px] shrink-0 rounded-full border-2 border-surface", it.type === "prix" ? "bg-brand" : it.type === "disparition" ? "bg-bad" : "bg-ink-3")} />311                    <div className="min-w-0 text-[0.92rem] leading-snug">312                      <div className="text-ink">313                        {it.type === "prix" ? (314                          it.prix_avant != null ? (315                            <>316                              Prix {it.prix_avant > (it.prix ?? 0) ? "baissé" : "monté"} de <span className="num">{fmtMoney(it.prix_avant)}</span> à{" "}317                              <b className="num">{fmtMoney(it.prix)}</b>318                            </>319                          ) : (320                            <>321                              Premier prix observé : <b className="num">{fmtMoney(it.prix)}</b>322                            </>323                          )324                        ) : (325                          (EVENT[it.type] ?? it.type)326                        )}327                      </div>328                      <div className="text-[0.78rem] text-ink-3">{fmtDay(it.ts)}</div>329                    </div>330                  </li>331                ))}332              </ol>333            ) : (334              <p className="mt-4 text-[0.92rem] text-ink-3">Aucune modification observée depuis la première synchronisation.</p>335            )}336            {d.timeline.length > 5 && <MoreLink onClick={() => setAll((a) => !a)}>{all ? "Réduire" : `Voir les ${d.timeline.length} événements`}</MoreLink>}337338            {matches.length > 0 && (339              <div className="mt-6 border-t border-line pt-5">340                <h4 className="text-[0.98rem]">Annonces antérieures probables de ce logement</h4>341                <ul className="mt-3 space-y-2.5">342                  {matches.slice(0, 3).map((m) => (343                    <li key={m.uid} className="rounded-[10px] bg-surface-2 px-4 py-3 text-[0.9rem]">344                      <div className="flex flex-wrap items-center gap-x-3 gap-y-1">345                        <Pill tone="warn" className="!py-1 !text-[0.72rem]">346                          Republication probable · {Math.round(m.confiance)} %347                        </Pill>348                        <span className="text-ink">349                          {m.prix != null && (350                            <>351                              affichée <b className="num">{fmtMoney(m.prix)}</b>352                            </>353                          )}354                          {m.derniere_observation != null && <> jusqu'en {fmtMonth(m.derniere_observation)}</>}355                          {m.source ? ` · ${prettySource(m.source, names)}` : ""}356                        </span>357                      </div>358                      {m.signaux.length > 0 && <div className="mt-1.5 text-[0.78rem] text-ink-3">{m.signaux.join(" · ")}</div>}359                    </li>360                  ))}361                </ul>362              </div>363            )}364            <SourceLine>Observations directes des synchronisations Lou-Ka : prix, description, photos, retraits et retours. Aucune estimation.</SourceLine>365          </>366        )}367      </Panel>368    </div>369  );370}371
Files main
Menu

Theme