SPB Git

Repository Public

Manager.tsx 21.3 KB 472 lines tsx

1// Fiche d'un gestionnaire : identité, chiffres, logements à louer, avis Google.23import { useMemo, useState } from "react";4import { Link, useParams } from "react-router";5import { useInfiniteQuery, useQuery } from "@tanstack/react-query";6import { ExternalLink, Map as MapIcon, Phone } from "lucide-react";7import { fetchGestionnaire, fetchManagers, fetchSearch, type Gestionnaire, type ManagerEntry, type SearchSort } from "@/lib/api";8import { cn } from "@/lib/cn";9import { fmtAgo, fmtInt, fmtMoney, plural } from "@/lib/format";10import { useTitle } from "@/lib/hooks";11import { LoukaEmptyState } from "@/brand/EmptyState";12import { ErrorState, Facts, prettyHost, Rating, regionKey, SectionHead, SortSelect, telHref } from "@/components/annuaire/shared";13import { ListingCard, ListingCardSkeleton } from "@/components/ListingCard";14import { buttonClass, ButtonLink, Skeleton } from "@/ui/primitives";1516const SORTS: { value: SearchSort; label: string }[] = [17  { value: "recent", label: "Plus récents" },18  { value: "prix", label: "Prix croissant" },19  { value: "prix_desc", label: "Prix décroissant" },20  { value: "deal", label: "Meilleurs prix" },21];2223const fr1 = (n: number) => n.toFixed(1).replace(".", ",");24const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);2526function fmtReviewDate(d: string | null): string {27  if (!d) return "";28  const t = Date.parse(d);29  return Number.isNaN(t) ? d : new Date(t).toLocaleDateString("fr-CA", { day: "numeric", month: "long", year: "numeric" });30}3132// --- Avis Google ----------------------------------------------------------------33function Reviews({ g }: { g: Gestionnaire }) {34  const gm = g.google_maps;35  const avis = g.avis;36  const [all, setAll] = useState(false);3738  if (!gm) return null;39  if (gm.statut === "non_associe") {40    return (41      <section>42        <SectionHead43          id="avis-titre"44          title="Avis non affichés"45          text="Aucune fiche Google Maps n'a pu être associée à ce gestionnaire avec une confiance suffisante. Plutôt que de risquer d'afficher les avis d'une autre entreprise, Lou-Ka n'en montre aucun."46        />47      </section>48    );49  }5051  const note = avis?.moyenne ?? gm.note ?? null;52  const n = avis?.n ?? gm.nombre_avis ?? 0;53  const dist = avis?.distribution ?? {};54  const max = Math.max(1, ...Object.values(dist));55  const themes = Object.entries(avis?.themes ?? {})56    .sort((a, b) => b[1].mentions - a[1].mentions)57    .slice(0, 8);58  const maxMentions = Math.max(1, ...themes.map(([, t]) => t.mentions));59  const delta = avis?.moyenne_12m != null && avis.moyenne != null ? avis.moyenne_12m - avis.moyenne : null;60  const recents = g.avis_recents ?? [];61  const shown = all ? recents : recents.slice(0, 4);62  const line = "flex items-baseline justify-between gap-4 border-b border-line py-2.5 text-[0.9rem]";6364  return (65    <section aria-labelledby="avis-titre">66      <SectionHead67        id="avis-titre"68        title="Avis Google"69        text={g.derniere_synchro ? `Synchronisés ${fmtAgo(g.derniere_synchro)}.` : undefined}70      />7172      <div className="mt-6 grid gap-x-12 gap-y-9 lg:grid-cols-3">73        {/* note et distribution */}74        <div>75          <div className="flex items-baseline gap-2.5">76            <span className="num text-[2.4rem] font-semibold leading-none tracking-tight">{note != null ? fr1(note) : "—"}</span>77            <span className="text-[0.9rem] text-ink-3">sur 5 · {plural(n, "avis", "avis")}</span>78          </div>79          <ul className="mt-5 space-y-2">80            {["5", "4", "3", "2", "1"].map((k) => {81              const v = dist[k] ?? 0;82              return (83                <li key={k} className="num grid grid-cols-[0.75rem_1fr_2rem] items-center gap-3 text-[0.8rem] text-ink-3">84                  <span>{k}</span>85                  <span className="h-1.5 overflow-hidden rounded-full bg-surface-3">86                    <span className="block h-full rounded-full bg-ink-2" style={{ width: `${(v / max) * 100}%` }} />87                  </span>88                  <span className="text-right">{v}</span>89                </li>90              );91            })}92          </ul>93        </div>9495        {/* signaux */}96        <div>97          <h3 className="font-sans text-[0.86rem] font-medium tracking-normal text-ink-3">En bref</h3>98          <dl className="mt-1">99            {avis?.pct_positif != null && (100              <div className={line}>101                <dt className="text-ink-2">Avis positifs (4 et 5 étoiles)</dt>102                <dd className="num font-medium text-good">{avis.pct_positif} %</dd>103              </div>104            )}105            {avis?.pct_negatif != null && (106              <div className={line}>107                <dt className="text-ink-2">Avis négatifs (1 et 2 étoiles)</dt>108                <dd className="num font-medium text-bad">{avis.pct_negatif} %</dd>109              </div>110            )}111            {avis?.moyenne_12m != null && (112              <div className={line}>113                <dt className="text-ink-2">114                  Moyenne des 12 derniers mois115                  {avis.n_12m != null && <span className="num text-ink-3"> ({avis.n_12m} avis)</span>}116                </dt>117                <dd className="num whitespace-nowrap font-medium text-ink">118                  {fr1(avis.moyenne_12m)}119                  {delta != null && Math.abs(delta) >= 0.15 && (120                    <span className={cn("ml-1.5 text-[0.8rem]", delta > 0 ? "text-good" : "text-bad")}>121                      {delta > 0 ? "+" : "−"}122                      {fr1(Math.abs(delta))}123                    </span>124                  )}125                </dd>126              </div>127            )}128            {avis?.avec_reponse_proprietaire != null && (129              <div className={line}>130                <dt className="text-ink-2">Avis avec réponse du gestionnaire</dt>131                <dd className="num font-medium text-ink">{avis.avec_reponse_proprietaire}</dd>132              </div>133            )}134          </dl>135          {!!avis?.plaintes_frequentes?.length && (136            <p className="mt-4 text-[0.86rem] leading-relaxed text-ink-2">137              <span className="text-ink-3">Plaintes les plus fréquentes : </span>138              {avis.plaintes_frequentes.slice(0, 6).map((p) => p.toLowerCase()).join(", ")}.139            </p>140          )}141        </div>142143        {/* thèmes */}144        <div>145          <h3 className="font-sans text-[0.86rem] font-medium tracking-normal text-ink-3">Thèmes abordés</h3>146          {themes.length ? (147            <ul className="mt-3.5 space-y-3">148              {themes.map(([name, t]) => (149                <li key={name}>150                  <div className="flex items-baseline justify-between gap-3 text-[0.9rem]">151                    <span className="text-ink-2">{cap(name)}</span>152                    <span className="num text-[0.78rem] text-ink-3">{plural(t.mentions, "mention", "mentions")}</span>153                  </div>154                  <div className="mt-1.5 flex h-1.5 overflow-hidden rounded-full bg-surface-3" style={{ width: `${Math.max(18, (t.mentions / maxMentions) * 100)}%` }}>155                    <span className="h-full bg-bad" style={{ width: `${(t.negatif / t.mentions) * 100}%` }} />156                    <span className="h-full bg-good" style={{ width: `${(t.positif / t.mentions) * 100}%` }} />157                  </div>158                </li>159              ))}160              <li className="flex gap-4 pt-1 text-[0.78rem] text-ink-3">161                <span className="inline-flex items-center gap-1.5">162                  <span className="size-2 rounded-full bg-bad" /> Négatif163                </span>164                <span className="inline-flex items-center gap-1.5">165                  <span className="size-2 rounded-full bg-good" /> Positif166                </span>167              </li>168            </ul>169          ) : (170            <p className="mt-3.5 text-[0.9rem] text-ink-3">Pas assez d'avis rédigés pour dégager des thèmes.</p>171          )}172        </div>173      </div>174175      {shown.length > 0 && (176        <ul className="mt-9 grid grid-cols-1 gap-x-12 border-t border-line md:grid-cols-2">177          {shown.map((r, i) => (178            <li key={i} className="border-b border-line py-5">179              <figure>180                <div className="flex flex-wrap items-baseline justify-between gap-2 text-[0.82rem] text-ink-3">181                  <span>182                    <span className="font-medium text-ink">{r.auteur ?? "Anonyme"}</span>183                    {r.note != null && <span className="num"> · {fr1(r.note)} sur 5</span>}184                  </span>185                  <span>{fmtReviewDate(r.date)}</span>186                </div>187                {r.texte ? (188                  <blockquote className="mt-2 line-clamp-6 text-[0.93rem] leading-relaxed text-ink-2">{r.texte}</blockquote>189                ) : (190                  <p className="mt-2 text-[0.9rem] text-ink-3">Note sans commentaire.</p>191                )}192                {(!!r.analyse?.topics?.length || r.reponse_proprietaire) && (193                  <figcaption className="mt-2.5 text-[0.8rem] text-ink-3">194                    {r.analyse?.topics?.slice(0, 3).map(cap).join(" · ")}195                    {r.reponse_proprietaire && <span className="text-good">{r.analyse?.topics?.length ? " · " : ""}Réponse du gestionnaire</span>}196                  </figcaption>197                )}198              </figure>199            </li>200          ))}201        </ul>202      )}203      {recents.length > 4 && (204        <button type="button" onClick={() => setAll((v) => !v)} className={buttonClass("outline", "md", "mt-5")}>205          {all ? "Afficher moins d'avis" : `Afficher les ${recents.length} avis récents`}206        </button>207      )}208209      <p className="mt-6 max-w-3xl text-[0.8rem] leading-relaxed text-ink-3">210        Avis publics de la fiche Google Maps « {gm.nom} »{gm.adresse ? ` (${gm.adresse})` : ""}, associée à ce gestionnaire par similarité de nom, domaine web et ville211        {gm.confiance_association != null ? `, avec une confiance de ${Math.round(gm.confiance_association * 100)} %` : ""}. Les thèmes sont déduits automatiquement du212        texte des avis ; ils peuvent comporter des erreurs.213      </p>214    </section>215  );216}217218// --- Logements du gestionnaire ---------------------------------------------------219function Inventory({ id, name }: { id: string; name: string }) {220  const [sort, setSort] = useState<SearchSort>("recent");221  const q = useInfiniteQuery({222    queryKey: ["manager-listings", id, sort],223    queryFn: ({ pageParam, signal }) => fetchSearch({ source: id, sort, page: pageParam, page_size: 24, include: "liste" }, signal),224    initialPageParam: 1,225    getNextPageParam: (last) => (last.page * last.page_size < last.total ? last.page + 1 : undefined),226    staleTime: 12e4,227  });228  const listings = useMemo(() => q.data?.pages.flatMap((p) => p.listings) ?? [], [q.data]);229  const total = q.data?.pages[0]?.total;230  const unpositioned = q.data?.pages[0]?.unpositioned ?? 0;231  const grid = "lk-stagger grid grid-cols-1 gap-x-5 gap-y-8 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4";232233  return (234    <section aria-labelledby="logements-titre">235      <SectionHead236        id="logements-titre"237        title="Logements à louer"238        text={239          total != null && total > 0240            ? `${plural(total, "logement localisé", "logements localisés")}${unpositioned > 0 ? ` · ${fmtInt(unpositioned)} sans adresse précise` : ""}`241            : undefined242        }243        aside={244          <div className="flex flex-wrap items-center gap-2">245            <SortSelect value={sort} onChange={setSort} options={SORTS} />246            <ButtonLink to={`/recherche?source=${encodeURIComponent(id)}`} variant="outline">247              <MapIcon className="size-4" /> Voir sur la carte248            </ButtonLink>249          </div>250        }251      />252253      <div className="mt-6">254        {q.isError ? (255          <ErrorState onRetry={() => q.refetch()} />256        ) : q.isPending ? (257          <div className={grid}>258            {Array.from({ length: 8 }, (_, i) => (259              <ListingCardSkeleton key={i} />260            ))}261          </div>262        ) : listings.length === 0 ? (263          <LoukaEmptyState264            kind="closed"265            title="Aucun logement affiché en ce moment"266            text={267              unpositioned > 0268                ? `${plural(unpositioned, "logement est publié", "logements sont publiés")} sans adresse précise et ${unpositioned > 1 ? "n'apparaissent" : "n'apparaît"} donc pas ici.`269                : `${name} n'a aucune disponibilité publiée pour l'instant. L'inventaire est vérifié plusieurs fois par jour.`270            }271          />272        ) : (273          <>274            <div className={grid}>275              {listings.map((l, i) => (276                <ListingCard key={l.uid} listing={l} eager={i < 4} />277              ))}278              {q.isFetchingNextPage && Array.from({ length: 4 }, (_, i) => <ListingCardSkeleton key={`s${i}`} />)}279            </div>280            {q.hasNextPage && (281              <div className="mt-9 flex flex-col items-center gap-2">282                <button type="button" onClick={() => q.fetchNextPage()} disabled={q.isFetchingNextPage} className={buttonClass("outline", "lg")}>283                  {q.isFetchingNextPage ? "Chargement…" : "Afficher plus de logements"}284                </button>285                {total != null && (286                  <span className="num text-[0.8rem] text-ink-3">287                    {fmtInt(listings.length)} sur {fmtInt(total)}288                  </span>289                )}290              </div>291            )}292            {!q.hasNextPage && unpositioned > 0 && (293              <p className="mt-8 text-[0.86rem] text-ink-3">294                {plural(unpositioned, "autre logement est publié", "autres logements sont publiés")} sans adresse précise, donc hors de cette liste.295              </p>296            )}297          </>298        )}299      </div>300    </section>301  );302}303304// --- Page -----------------------------------------------------------------------305export default function Manager() {306  const { sourceId = "" } = useParams();307  const dir = useQuery({ queryKey: ["managers"], queryFn: fetchManagers, staleTime: 6e5 });308  const fiche = useQuery({309    queryKey: ["manager", sourceId],310    queryFn: () => fetchGestionnaire(sourceId),311    staleTime: 6e5,312    retry: false,313  });314  const entry: ManagerEntry | undefined = dir.data?.managers.find((m) => m.id === sourceId);315  const g = fiche.data;316317  const name = g?.nom ?? entry?.name ?? "";318  useTitle(name ? `${name} : logements à louer` : "Gestionnaire immobilier");319320  const loading = (fiche.isPending || dir.isPending) && !g && !entry;321  // inconnu partout : ni fiche détaillée, ni entrée d'annuaire322  if (!loading && !g && !entry && !dir.isPending && !fiche.isPending) {323    return (324      <div className="container-x py-16">325        {dir.isError && fiche.isError && !/404/.test(String(fiche.error)) ? (326          <ErrorState327            onRetry={() => {328              dir.refetch();329              fiche.refetch();330            }}331          />332        ) : (333          <LoukaEmptyState334            kind="closed"335            title="Gestionnaire introuvable"336            text="Cette fiche n'existe pas ou n'existe plus dans l'annuaire."337            action={338              <ButtonLink to="/gestionnaires" variant="primary">339                Parcourir l'annuaire340              </ButtonLink>341            }342          />343        )}344      </div>345    );346  }347348  const site = g?.site_web || entry?.url || "";349  const listingSite = entry?.listing_url || site;350  const phone = g?.telephone || entry?.phone || "";351  const address = g?.google_maps?.adresse || entry?.address || "";352  const active = g?.annonces_actives ?? entry?.active_listings ?? 0;353  const note = g?.avis?.moyenne ?? g?.google_maps?.note ?? entry?.rating ?? null;354  const nAvis = g?.avis?.n ?? g?.google_maps?.nombre_avis ?? entry?.reviews ?? null;355  // sans fiche détaillée ni inventaire : page réduite qui renvoie vers le site356  const reduced = !loading && !g && !!entry;357358  const stateLabel =359    entry?.state === "pause" ? "Synchronisation en pause" : entry && (entry.state === "connecte" || entry.state === "couvert") ? "Inventaire synchronisé" : null;360361  return (362    <>363      <header className="container-x pb-7 pt-6 lg:pt-10">364        <Link to="/gestionnaires" className="mb-3 inline-flex min-h-11 items-center gap-1.5 text-[0.88rem] text-ink-3 transition-colors duration-150 hover:text-ink">365          <span aria-hidden>←</span> Tous les gestionnaires366        </Link>367368        {loading ? (369          <div className="space-y-4">370            <Skeleton className="h-10 w-2/3 max-w-xl" />371            <Skeleton className="h-5 w-1/2 max-w-sm" />372          </div>373        ) : (374          <>375            <div className="flex flex-wrap items-end justify-between gap-x-10 gap-y-5">376              <div className="min-w-0 max-w-2xl">377                <div className="eyebrow">378                  {entry?.kind === "courtage" ? "Bannière de courtage" : "Gestionnaire immobilier"}379                  {stateLabel && <span className={entry?.state === "pause" ? "text-high" : ""}> · {stateLabel}</span>}380                </div>381                <h1 className="mt-2.5 text-[1.85rem] leading-[1.08] sm:text-[2.5rem]">{name}</h1>382                <p className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-[0.94rem] text-ink-2">383                  {entry?.region && <span>{regionKey(entry.region)}</span>}384                  {note != null && (385                    <a href="#avis-titre" className="inline-flex min-h-6 items-center underline decoration-line-2 underline-offset-[3px] hover:decoration-ink-3">386                      <Rating value={note} reviews={nAvis} className="!text-[0.94rem]" />387                    </a>388                  )}389                </p>390                {address && <p className="mt-1 text-[0.88rem] text-ink-3">{address}</p>}391              </div>392              <div className="flex w-full flex-wrap gap-2 sm:w-auto">393                {site && (394                  <a href={listingSite} target="_blank" rel="noopener noreferrer" className={buttonClass("primary", "md", "min-w-0 flex-1 sm:flex-none")}>395                    <span className="truncate">{prettyHost(site)}</span>396                    <ExternalLink className="size-4 shrink-0 opacity-80" />397                  </a>398                )}399                {phone && (400                  <a href={telHref(phone)} className={buttonClass("outline", "md", "num flex-1 sm:flex-none")}>401                    <Phone className="size-4" /> {phone}402                  </a>403                )}404              </div>405            </div>406407            {active > 0 && (408              <Facts409                className="mt-6"410                items={[411                  { value: fmtInt(active), label: active > 1 ? "logements à louer" : "logement à louer" },412                  ...(entry?.buildings ? [{ value: fmtInt(entry.buildings), label: entry.buildings > 1 ? "immeubles" : "immeuble" }] : []),413                  ...(entry?.price_median != null ? [{ value: fmtMoney(entry.price_median), label: "loyer médian" }] : []),414                  ...(entry?.price_min != null ? [{ value: fmtMoney(entry.price_min), label: "loyer le plus bas" }] : []),415                  ...(entry?.cities_total ? [{ value: fmtInt(entry.cities_total), label: entry.cities_total > 1 ? "villes" : "ville" }] : []),416                ]}417              />418            )}419420            {entry && (entry.cities.length > 0 || entry.sectors) && (421              <p className="mt-4 max-w-3xl text-[0.92rem] leading-relaxed text-ink-2">422                {entry.cities.length > 0 ? (423                  <>424                    <span className="text-ink-3">Présent à </span>425                    {entry.cities.map((c, i) => (426                      <span key={c}>427                        {i > 0 && ", "}428                        <Link429                          to={`/recherche?source=${encodeURIComponent(entry.id)}&city=${encodeURIComponent(c)}`}430                          className="inline-block py-1 underline decoration-line-2 underline-offset-[3px] hover:text-brand"431                        >432                          {c}433                        </Link>434                      </span>435                    ))}436                    {entry.cities_total > entry.cities.length && <span className="num text-ink-3"> et {entry.cities_total - entry.cities.length} autres</span>}437                  </>438                ) : (439                  <>440                    <span className="text-ink-3">Secteurs desservis : </span>441                    {entry.sectors}442                  </>443                )}444              </p>445            )}446          </>447        )}448      </header>449450      <div className="container-x space-y-16">451        {reduced && entry.active_listings === 0 ? (452          <section className="border-t border-line pt-7">453            <h2 className="text-[1.5rem]">Les disponibilités sont publiées sur son site</h2>454            <p className="mt-2 max-w-xl text-[0.96rem] leading-relaxed text-ink-2">455              L'inventaire de {name} n'est pas encore synchronisé par Lou-Ka. Consultez directement sa page de location pour connaître les logements offerts.456            </p>457            {listingSite && (458              <a href={listingSite} target="_blank" rel="noopener noreferrer" className={buttonClass("primary", "lg", "mt-5")}>459                Voir le site <ExternalLink className="size-4" />460              </a>461            )}462          </section>463        ) : (464          !loading && <Inventory id={sourceId} name={name} />465        )}466467        {g && <Reviews g={g} />}468      </div>469    </>470  );471}472
Files main
Menu

Theme