SPB Git

Repository Public

Compare.tsx 17.9 KB 385 lines tsx

1// Comparateur : jusqu'à quatre propriétés côte à côte, meilleure valeur de chaque2// ligne marquée. La sélection reste sur l'appareil. Première colonne fixe,3// défilement horizontal sur petit écran.45import { type ReactNode } from "react";6import { Link } from "react-router";7import { useQueries, useQuery } from "@tanstack/react-query";8import { Check, ExternalLink, Plus, Trash2, X } from "lucide-react";9import { annualTaxes, fetchMortgageIntelligence, fetchProperty, fmtRate, priceOk, pricePerSqft, propertyKey, propertyPlace, vraiPrixVerdict, type Property } from "@/lib/api.marche";10import { cn } from "@/lib/cn";11import { fmtInt, fmtMoney, fmtPct } from "@/lib/format";12import { useTitle } from "@/lib/hooks";13import { clearCompare, COMPARE_MAX, toggleCompare, useCompare } from "@/lib/store";14import { BrandEmptyState, doorClick, listingPath } from "@/brand/compat";15import { SmartImage } from "@/components/SmartImage";16import { linkClass, PageHero } from "@/components/marche-ik/layout";17import { quickMonthly } from "@/components/marche-ik/mortgage";18import { VerdictLabel } from "@/components/marche-ik/PropertyCard";19import { sourceLabel, useSourceLabels } from "@/components/marche-ik/sources";20import { Button, ButtonLink, Skeleton } from "@/ui/primitives";2122interface Row {23  label: string;24  hint?: string;25  group?: string;26  /** valeur numérique servant à désigner la meilleure ; null = hors concours */27  rank?: (l: Property) => number | null;28  best?: "min" | "max";29  cell: (l: Property) => ReactNode;30}3132const dash = <span className="text-ink-3">—</span>;33const verdictOf = (l: Property) => vraiPrixVerdict(l.price, l.vraiprix?.value, l.vraiprix?.low, l.vraiprix?.high);34const plausibleArea = (l: Property) => (l.area_sqft != null && l.area_sqft >= 250 && l.area_sqft <= 20000 && l.area_sqft !== l.lot_sqft ? l.area_sqft : null);35const plausibleYear = (l: Property) => (l.year_built != null && l.year_built >= 1650 && l.year_built <= new Date().getFullYear() + 3 ? l.year_built : null);3637function buildRows(rate: number | null): Row[] {38  return [39    {40      group: "Prix",41      label: "Prix demandé",42      best: "min",43      rank: (l) => (priceOk(l.price) ? l.price : null),44      cell: (l) => (priceOk(l.price) ? <span className="num text-[1.06rem] font-semibold">{fmtMoney(l.price)}</span> : <span className="text-ink-3">Sur demande</span>),45    },46    {47      label: "Vrai prix",48      cell: (l) => {49        const v = verdictOf(l);50        return v ? <VerdictLabel verdict={v.verdict} className="px-2 py-1 text-[0.78rem]" /> : <span className="text-[0.86rem] text-ink-3">Pas de verdict</span>;51      },52    },53    {54      label: "Estimation",55      cell: (l) =>56        l.vraiprix?.value ? (57          <span className="num">58            <span className="font-medium">{fmtMoney(l.vraiprix.value)}</span>59            {l.vraiprix.low && l.vraiprix.high ? (60              <span className="block text-xs text-ink-3">61                {fmtInt(l.vraiprix.low)} à {fmtMoney(l.vraiprix.high)}62              </span>63            ) : null}64          </span>65        ) : (66          dash67        ),68    },69    {70      label: "Écart à l'estimation",71      best: "min",72      rank: (l) => verdictOf(l)?.deviation ?? null,73      cell: (l) => {74        const v = verdictOf(l);75        return v ? <span className="num font-medium">{fmtPct(v.deviation)}</span> : dash;76      },77    },78    {79      label: "Prix au pi²",80      best: "min",81      rank: pricePerSqft,82      cell: (l) => {83        const v = pricePerSqft(l);84        return v == null ? dash : <span className="num font-medium">{fmtInt(Math.round(v))} $</span>;85      },86    },87    { group: "Propriété", label: "Type", cell: (l) => (l.property_type ? <span className="font-medium">{l.property_type}</span> : dash) },88    {89      label: "Chambres",90      best: "max",91      rank: (l) => (l.bedrooms != null && l.bedrooms > 0 && l.bedrooms < 30 ? l.bedrooms : null),92      cell: (l) => (l.bedrooms != null && l.bedrooms > 0 ? <span className="num font-medium">{l.bedrooms}</span> : dash),93    },94    {95      label: "Salles de bain",96      best: "max",97      rank: (l) => (l.bathrooms != null && l.bathrooms > 0 && l.bathrooms < 20 ? l.bathrooms + (l.powder_rooms ?? 0) * 0.5 : null),98      cell: (l) =>99        l.bathrooms != null && l.bathrooms > 0 ? (100          <span className="num font-medium">101            {l.bathrooms}102            {l.powder_rooms ? <span className="font-sans text-[0.8rem] font-normal text-ink-3"> + {l.powder_rooms} salle{l.powder_rooms > 1 ? "s" : ""} d'eau</span> : null}103          </span>104        ) : (105          dash106        ),107    },108    {109      label: "Superficie habitable",110      best: "max",111      rank: plausibleArea,112      cell: (l) => (plausibleArea(l) ? <span className="num font-medium">{fmtInt(plausibleArea(l))} pi²</span> : dash),113    },114    {115      label: "Terrain",116      best: "max",117      rank: (l) => (l.lot_sqft != null && l.lot_sqft > 0 ? l.lot_sqft : null),118      cell: (l) =>119        l.lot_sqft != null && l.lot_sqft > 0 ? (120          <span className="num font-medium">121            {fmtInt(l.lot_sqft)} pi²{l.details.lot_sqft_source === "role" && <span className="block font-sans text-xs font-normal text-ink-3">selon le rôle d'évaluation</span>}122          </span>123        ) : (124          dash125        ),126    },127    {128      label: "Année de construction",129      best: "max",130      rank: plausibleYear,131      cell: (l) => (plausibleYear(l) ? <span className="num font-medium">{plausibleYear(l)}</span> : dash),132    },133    {134      group: "Coûts",135      label: "Taxes annuelles",136      hint: "municipales et scolaires publiées",137      best: "min",138      rank: (l) => {139        const t = annualTaxes(l);140        return t && t.municipal != null ? t.total : null;141      },142      cell: (l) => {143        const t = annualTaxes(l);144        if (!t) return dash;145        return (146          <span className="num">147            <span className="font-medium">{fmtMoney(Math.round(t.total))}</span>148            {(t.municipal == null || t.school == null) && <span className="block font-sans text-xs text-ink-3">{t.municipal == null ? "scolaires seulement" : "municipales seulement"}</span>}149          </span>150        );151      },152    },153    {154      label: "Versement hypothécaire",155      hint: rate != null ? `estimé par mois, à ${fmtRate(rate)}` : "estimé par mois",156      best: "min",157      rank: (l) => (rate != null && priceOk(l.price) ? quickMonthly(l.price, rate) : null),158      cell: (l) => (rate != null && priceOk(l.price) ? <span className="num font-medium">{fmtMoney(Math.round(quickMonthly(l.price, rate)))}</span> : dash),159    },160    {161      label: "Jours en ligne",162      hint: "depuis la première observation",163      cell: (l) => (l.days_on_market != null ? <span className="num">{fmtInt(l.days_on_market)}</span> : dash),164    },165  ];166}167168function bestIndex(row: Row, listings: (Property | undefined)[]): number | null {169  if (!row.rank || !row.best) return null;170  const vals = listings.map((l) => (l ? row.rank!(l) : null));171  const known = vals.filter((v): v is number => v != null);172  if (known.length < 2) return null;173  const target = row.best === "min" ? Math.min(...known) : Math.max(...known);174  if (known.every((v) => v === target)) return null;175  return vals.indexOf(target);176}177178export default function Compare() {179  useTitle("Comparateur de propriétés");180  const uids = useCompare();181  const names = useSourceLabels();182  const queries = useQueries({183    queries: uids.map((uid) => ({ queryKey: propertyKey(uid), queryFn: () => fetchProperty(uid), staleTime: 5 * 60_000, retry: false })),184  });185  const rates = useQuery({ queryKey: ["taux-intelligence"], queryFn: fetchMortgageIntelligence, staleTime: 5 * 60_000, enabled: uids.length > 0 });186  const best5 = rates.data?.products.find((p) => p.rate_type === "fixed" && p.term_months === 60);187  const rows = buildRows(best5?.best ?? null);188  const listings = queries.map((q) => q.data);189  const cols = uids.length;190  const sticky = "sticky left-0 z-10 bg-bg";191192  return (193    <>194      <PageHero195        eyebrow="Comparateur"196        title="Vos propriétés, côte à côte"197        text={`Jusqu'à ${COMPARE_MAX} propriétés comparées ligne par ligne. La meilleure valeur de chaque ligne est marquée.`}198      >199        {cols > 0 && (200          <div className="flex flex-wrap gap-2.5">201            <ButtonLink to="/recherche" variant="outline">202              <Plus className="size-4" /> Ajouter une propriété203            </ButtonLink>204            <Button variant="ghost" onClick={clearCompare}>205              <Trash2 className="size-4" /> Tout retirer206            </Button>207          </div>208        )}209      </PageHero>210211      {cols === 0 ? (212        <section className="container-x">213          <div className="grid gap-x-12 border-y border-line lg:grid-cols-[1fr_1.1fr] lg:items-center">214            <BrandEmptyState215              kind="many"216              title="Votre comparateur est vide"217              text="Ajoutez deux à quatre propriétés pour voir laquelle coûte le moins cher au pied carré, laquelle se situe sous son estimation et ce que chacune coûterait par mois."218              action={219                <div className="flex flex-wrap justify-center gap-2.5">220                  <ButtonLink to="/recherche" variant="primary">221                    Explorer la carte222                  </ButtonLink>223                  <ButtonLink to="/favoris" variant="outline">224                    Partir de mes favoris225                  </ButtonLink>226                </div>227              }228            />229            <ol className="pb-10 lg:py-10">230              {[231                ["Repérez l'icône de balance", "Sur chaque propriété (au survol de la photo sur ordinateur), sur sa fiche et dans vos favoris."],232                ["Ajoutez jusqu'à quatre propriétés", "Un bouton « Comparer » apparaît en bas de l'écran avec le nombre de propriétés choisies."],233                ["Lisez ligne par ligne", "Prix, vrai prix, superficie, terrain, taxes et versement estimé, dans le même ordre pour toutes."],234              ].map(([t, d], i) => (235                <li key={t} className="grid grid-cols-[2rem_1fr] gap-x-3 border-t border-line py-4 first:border-0">236                  <span className="num pt-0.5 text-[0.86rem] text-ink-3">{i + 1}</span>237                  <span>238                    <span className="block text-[0.95rem] font-medium">{t}</span>239                    <span className="block text-[0.88rem] leading-relaxed text-ink-3">{d}</span>240                  </span>241                </li>242              ))}243            </ol>244          </div>245        </section>246      ) : (247        <section>248          <div className="mx-auto max-w-[1280px] lg:px-10">249            <div className="overflow-x-auto overscroll-x-contain pb-4 lg:overflow-visible">250              <table className="w-full table-fixed border-separate border-spacing-0 text-left text-[0.92rem]" style={{ minWidth: 112 + cols * 176 }}>251                <colgroup>252                  <col className="w-28 lg:w-48" />253                  {uids.map((uid) => (254                    <col key={uid} />255                  ))}256                </colgroup>257                <thead>258                  <tr>259                    <th className={cn(sticky, "z-20 p-0 align-bottom")}>260                      <span className="num block px-4 pb-4 text-xs font-medium text-ink-3">261                        {cols} sur {COMPARE_MAX}262                      </span>263                    </th>264                    {uids.map((uid, i) => {265                      const l = listings[i];266                      const q = queries[i]!;267                      return (268                        <th key={uid} scope="col" className="bg-bg p-2.5 align-top font-normal">269                          <div className="relative">270                            <button271                              type="button"272                              aria-label="Retirer du comparateur"273                              onClick={() => toggleCompare(uid)}274                              className="absolute right-1.5 top-1.5 z-10 grid size-11 place-items-center"275                            >276                              <span className="grid size-8 place-items-center rounded-full border border-line bg-surface text-ink">277                                <X className="size-4" />278                              </span>279                            </button>280                            {q.isPending ? (281                              <div>282                                <Skeleton className="aspect-[4/3] w-full rounded-xl" />283                                <Skeleton className="mt-3 h-4 w-3/4" />284                              </div>285                            ) : !l || l.active === 0 ? (286                              <div className="grid aspect-[4/3] place-items-center rounded-xl bg-surface-2 p-4 text-center text-[0.86rem] leading-snug text-ink-3">Cette inscription n'est plus en ligne.</div>287                            ) : (288                              <Link to={listingPath(uid)} onClick={(e) => doorClick(e, { uid, image: l.images[0] ?? null, context: "favorite" })} className="group block">289                                <span data-door-source className="block overflow-hidden rounded-xl bg-surface-2">290                                  <SmartImage src={l.images[0]} alt="" className="aspect-[4/3] w-full" />291                                </span>292                                <span className="block pt-2.5">293                                  <span className="block truncate text-[0.92rem] font-medium text-ink group-hover:text-brand">{l.address || l.title || "Propriété"}</span>294                                  <span className="block truncate text-[0.8rem] text-ink-3">{propertyPlace(l) || l.region}</span>295                                </span>296                              </Link>297                            )}298                          </div>299                        </th>300                      );301                    })}302                  </tr>303                </thead>304                <tbody>305                  {rows.map((row) => {306                    const best = bestIndex(row, listings);307                    return [308                      row.group && (309                        <tr key={`g-${row.group}`}>310                          <th colSpan={cols + 1} scope="colgroup" className="p-0 text-left">311                            <span className="eyebrow sticky left-0 inline-block px-4 pb-2 pt-7">{row.group}</span>312                          </th>313                        </tr>314                      ),315                      <tr key={row.label}>316                        <th scope="row" className={cn(sticky, "border-t border-line px-4 py-3 text-[0.84rem] font-medium leading-snug text-ink-2")}>317                          {row.label}318                          {row.hint && <span className="block text-[0.72rem] font-normal leading-snug text-ink-3">{row.hint}</span>}319                        </th>320                        {uids.map((uid, i) => {321                          const l = listings[i];322                          const win = best === i;323                          return (324                            <td key={uid} className="border-t border-line px-2.5 py-1 align-middle">325                              <div className={cn("flex min-h-10 items-center justify-between gap-2 py-1.5", win && "text-brand")}>326                                <span className="min-w-0 flex-1">{l ? row.cell(l) : queries[i]?.isPending ? <Skeleton className="h-4 w-20" /> : dash}</span>327                                {win && <Check className="size-4 shrink-0 text-brand" aria-label="Meilleure valeur" />}328                              </div>329                            </td>330                          );331                        })}332                      </tr>,333                    ];334                  })}335                  <tr>336                    <th scope="row" className={cn(sticky, "border-y border-line px-4 py-4 text-[0.84rem] font-medium text-ink-2")}>337                      Source338                    </th>339                    {uids.map((uid, i) => {340                      const l = listings[i];341                      return (342                        <td key={uid} className="border-y border-line px-2.5 py-3 align-middle">343                          {l ? (344                            <span className="block min-w-0">345                              <span className="block truncate">{sourceLabel(l.source, names)}</span>346                              {l.url && (347                                <a href={l.url} target="_blank" rel="noopener noreferrer nofollow" className="inline-flex min-h-9 items-center gap-1.5 text-[0.8rem] text-brand hover:underline">348                                  Inscription originale <ExternalLink className="size-3.5" />349                                </a>350                              )}351                            </span>352                          ) : (353                            dash354                          )}355                        </td>356                      );357                    })}358                  </tr>359                </tbody>360              </table>361            </div>362            <p className="mt-4 max-w-3xl px-4 text-[0.8rem] leading-relaxed text-ink-3 lg:px-0">363              Un tiret signifie que l'inscription ne précise pas l'information. La meilleure valeur de chaque ligne est cochée ; pour l'année, c'est la construction la plus récente.{" "}364              {best5 ? (365                <>366                  Versement estimé avec le meilleur taux fixe de 5 ans relevé en ce moment ({fmtRate(best5.best)}, {best5.best_institution}), une mise de fonds de 20 % et un amortissement de 25 ans : une estimation, pas une offre.{" "}367                </>368              ) : rates.isError ? (369                "Le versement n'est pas estimé : les taux n'ont pas pu être chargés. "370              ) : null}371              <Link to="/taux#calculateur" className={linkClass}>372                Faire mon propre calcul373              </Link>{" "}374              ·{" "}375              <Link to="/vrai-prix" className={linkClass}>376                Comprendre le vrai prix377              </Link>378            </p>379          </div>380        </section>381      )}382    </>383  );384}385
Files main
Menu

Theme