SPB Git

Repository Public

EntryPage.tsx 15.0 KB 340 lines tsx

1// Fiche d'une entrée de l'annuaire (agence ou bannière) : en-tête d'identité,2// courtiers, agences rattachées, propriétés à vendre.34import { useMemo, useState, type ReactNode } from "react";5import { Link } from "react-router";6import { useQuery } from "@tanstack/react-query";7import { ExternalLink } from "lucide-react";8import { fetchBrokers, KIND_LABEL, type Directory, type DirEntry, type InventoryPart } from "@/lib/api.annuaires";9import { cn } from "@/lib/cn";10import { fmtAgo, fmtInt, plural } from "@/lib/format";11import { useDebounced } from "@/lib/hooks";12import { BrandEmptyState } from "@/brand/compat";13import { ListingCardSkeleton } from "@/components/ListingCard";14import { buttonClass, ButtonLink, Skeleton } from "@/ui/primitives";15import { ColumnHead, EntryRow } from "./EntryRow";16import { Inventory } from "./Inventory";17import {18  BackLink,19  ChipRow,20  coverageShort,21  entryQuery,22  ErrorState,23  Facts,24  FactsPlaceholder,25  FilterTab,26  listSome,27  MedianValue,28  norm,29  prettyHost,30  Rows,31  RowsSkeleton,32  SearchField,33  SectionHead,34  type Fact,35} from "./shared";3637const BACK = { to: "/agences", label: "Courtiers, agences et bannières" };3839// --- États de page --------------------------------------------------------------40export function EntryLoading() {41  return (42    <>43      <header className="container-x pb-7 pt-5 lg:pt-10">44        <BackLink to={BACK.to}>{BACK.label}</BackLink>45        <div className="space-y-4 pt-1">46          <Skeleton className="h-4 w-40" />47          <Skeleton className="h-10 w-2/3 max-w-xl" />48          <Skeleton className="h-5 w-1/2 max-w-sm" />49        </div>50        <FactsPlaceholder className="mt-6" />51      </header>52      <div className="container-x">53        <div className="grid grid-cols-1 gap-x-5 gap-y-8 border-t border-line pt-7 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">54          {Array.from({ length: 8 }, (_, i) => (55            <ListingCardSkeleton key={i} />56          ))}57        </div>58      </div>59    </>60  );61}6263export function EntryMissing({ what, error, onRetry }: { what: "agence" | "banniere"; error?: boolean; onRetry?: () => void }) {64  return (65    <div className="container-x py-12">66      {error ? (67        <ErrorState onRetry={onRetry} />68      ) : (69        <BrandEmptyState70          kind="closed"71          title={what === "agence" ? "Agence introuvable" : "Bannière introuvable"}72          text="Cette fiche n'existe pas ou n'existe plus dans l'annuaire."73          action={74            <ButtonLink to={BACK.to} variant="primary">75              Parcourir l'annuaire76            </ButtonLink>77          }78        />79      )}80    </div>81  );82}8384// --- En-tête ----------------------------------------------------------------------85export function EntryHeader({ e, agencyOk, lead }: { e: DirEntry; agencyOk: boolean | undefined; lead?: ReactNode }) {86  const q = entryQuery(e, agencyOk);87  const state = e.listings > 0 ? "Inventaire synchronisé" : e.followed ? "Aucune inscription en ce moment" : null;88  const facts: Fact[] = [89    ...(e.listings > 0 ? [{ value: fmtInt(e.listings), label: e.listings > 1 ? "inscriptions actives" : "inscription active" }] : []),90    ...(q || e.median != null ? [{ value: <MedianValue q={q} n={e.listings} known={e.median} />, label: "prix médian demandé" }] : []),91    ...(e.agencies > 0 ? [{ value: fmtInt(e.agencies), label: e.agencies > 1 ? "agences" : "agence" }] : []),92    ...(e.brokers ? [{ value: fmtInt(e.brokers), label: e.brokers > 1 ? "courtiers" : "courtier" }] : []),93    ...(e.citiesTotal > 1 ? [{ value: fmtInt(e.citiesTotal), label: "villes" }] : e.regions.length > 1 ? [{ value: fmtInt(e.regions.length), label: "régions" }] : []),94    ...(e.lastSync && e.kind !== "agence" ? [{ value: fmtAgo(e.lastSync), label: "dernière lecture" }] : []),95  ].slice(0, 4);9697  return (98    <header className="container-x pb-7 pt-5 lg:pt-10">99      <BackLink to={BACK.to}>{BACK.label}</BackLink>100      <div className="flex flex-wrap items-end justify-between gap-x-10 gap-y-5">101        <div className="min-w-0 max-w-2xl">102          <div className="eyebrow">103            {KIND_LABEL[e.kind]}104            {state && <span> · {state}</span>}105          </div>106          <h1 className="mt-2.5 text-[1.85rem] leading-[1.08] sm:text-[2.5rem]">{e.name}</h1>107          {(e.banner || e.regions.length > 0 || e.coverage) && (108            <p className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-[0.94rem] text-ink-2">109              {e.banner && (110                <Link to={e.banner.path} className="inline-flex min-h-6 items-center underline decoration-line-2 underline-offset-[3px] hover:text-brand">111                  Bannière {e.banner.name}112                </Link>113              )}114              {e.kind !== "agence" && coverageShort(e.coverage) ? (115                <span>{coverageShort(e.coverage)}</span>116              ) : (117                e.regions.length > 0 && <span>{listSome(e.regions, 4)}</span>118              )}119            </p>120          )}121          {lead && <p className="mt-3 text-[0.95rem] leading-relaxed text-ink-2">{lead}</p>}122          {e.cities.length > 0 && (123            <p className="mt-3 text-[0.92rem] leading-relaxed text-ink-2">124              <span className="text-ink-3">Inscriptions à </span>125              {e.cities.slice(0, 6).join(", ")}126              {e.citiesTotal > Math.min(6, e.cities.length) && <span className="num text-ink-3"> et {fmtInt(e.citiesTotal - Math.min(6, e.cities.length))} autres villes</span>}127            </p>128          )}129        </div>130        {e.site && (131          <div className="flex w-full flex-wrap gap-2 sm:w-auto">132            <a href={e.site} target="_blank" rel="noopener noreferrer" className={buttonClass("primary", "md", "min-w-0 flex-1 sm:flex-none")}>133              <span className="truncate">{prettyHost(e.site)}</span>134              <ExternalLink className="size-4 shrink-0 opacity-80" />135            </a>136          </div>137        )}138      </div>139      {facts.length > 0 && <Facts className="mt-6" items={facts} />}140    </header>141  );142}143144// --- Courtiers (registre OACIQ) ------------------------------------------------145const BROKERS_FIRST = 24;146147export function BrokersSection({ e }: { e: DirEntry }) {148  const q = useQuery({ queryKey: ["ik-courtiers", e.oaciqSlug], queryFn: () => fetchBrokers(e.oaciqSlug!), enabled: !!e.oaciqSlug, staleTime: 36e5 });149  const [input, setInput] = useState("");150  const [city, setCity] = useState<string | null>(null);151  const [all, setAll] = useState(false);152  const needle = norm(useDebounced(input, 120).trim());153154  const brokers = q.data ?? [];155  const cities = useMemo(() => {156    const m = new Map<string, number>();157    for (const b of brokers) if (b.city) m.set(b.city, (m.get(b.city) ?? 0) + 1);158    return [...m.entries()].sort((a, b) => b[1] - a[1]);159  }, [brokers]);160  const rows = useMemo(161    () => brokers.filter((b) => (!city || b.city === city) && (!needle || norm(`${b.name} ${b.city}`).includes(needle))),162    [brokers, city, needle],163  );164165  if (!e.oaciqSlug || (!q.isPending && !q.isError && brokers.length === 0)) return null;166  const n = q.data ? brokers.length : (e.brokers ?? 0);167  const shown = all || needle || city ? rows : rows.slice(0, BROKERS_FIRST);168169  return (170    <section aria-labelledby="courtiers-titre">171      <SectionHead172        id="courtiers-titre"173        title="Ses courtiers"174        text={`${plural(n, "courtier titulaire", "courtiers titulaires")} d'un permis, selon le registre de l'OACIQ${cities.length > 1 ? `, dans ${fmtInt(cities.length)} villes` : ""}.`}175        aside={n > BROKERS_FIRST ? <SearchField value={input} onChange={setInput} placeholder="Chercher un courtier" className="w-full sm:w-72" /> : undefined}176      />177      {cities.length > 1 && (178        <div className="mt-5">179          <ChipRow label="Ville du courtier">180            <FilterTab active={!city} onClick={() => setCity(null)}>181              Toutes les villes182            </FilterTab>183            {cities.slice(0, 10).map(([c, k]) => (184              <FilterTab key={c} active={city === c} onClick={() => setCity(city === c ? null : c)} count={k}>185                {c}186              </FilterTab>187            ))}188          </ChipRow>189        </div>190      )}191      <div className="mt-5">192        {q.isError ? (193          <ErrorState onRetry={() => q.refetch()} text="La liste des courtiers n'a pas pu être récupérée." />194        ) : q.isPending ? (195          <RowsSkeleton rows={6} />196        ) : rows.length === 0 ? (197          <p className="border-b border-line py-6 text-[0.92rem] text-ink-3">Aucun courtier ne correspond à cette recherche.</p>198        ) : (199          <>200            <Rows resetKey={`${city}|${all}`} className="grid grid-cols-1 gap-x-10 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">201              {shown.map((b, i) => (202                <div key={`${b.name}|${b.city}|${i}`} role="listitem" className="flex min-h-11 items-baseline justify-between gap-3 border-b border-line py-2.5">203                  <span className="min-w-0 truncate text-[0.95rem] text-ink">{b.name}</span>204                  <span className="shrink-0 truncate text-[0.82rem] text-ink-3">{b.city}</span>205                </div>206              ))}207            </Rows>208            {!needle && !city && rows.length > BROKERS_FIRST && (209              <button type="button" onClick={() => setAll((v) => !v)} className={buttonClass("outline", "md", "mt-5")} aria-expanded={all}>210                {all ? "Afficher moins de courtiers" : `Afficher les ${fmtInt(rows.length)} courtiers`}211              </button>212            )}213          </>214        )}215      </div>216    </section>217  );218}219220// --- Agences d'une bannière --------------------------------------------------------221const AGENCIES_FIRST = 10;222223export function AgenciesSection({ e, dir, agencyOk }: { e: DirEntry; dir: Directory; agencyOk: boolean | undefined }) {224  const [all, setAll] = useState(false);225  const members = useMemo(226    () =>227      dir.entries228        .filter((a) => a.banner?.id === e.id && a.kind === "agence")229        .sort((a, b) => b.listings - a.listings || (b.brokers ?? 0) - (a.brokers ?? 0) || a.name.localeCompare(b.name, "fr")),230    [dir, e.id],231  );232  if (!members.length) return null;233  const shown = all ? members : members.slice(0, AGENCIES_FIRST);234  return (235    <section aria-labelledby="agences-titre">236      <SectionHead id="agences-titre" title="Ses agences" text={`${plural(members.length, "agence", "agences")} sous la bannière ${e.name}, avec leurs courtiers et leurs inscriptions actives.`} />237      <div className="mt-5">238        <ColumnHead first="Agence" />239        <Rows resetKey={String(all)}>240          {shown.map((a) => (241            <EntryRow key={a.path} e={a} agencyOk={agencyOk} hideBanner />242          ))}243        </Rows>244        {members.length > AGENCIES_FIRST && (245          <button type="button" onClick={() => setAll((v) => !v)} className={buttonClass("outline", "md", "mt-5")} aria-expanded={all}>246            {all ? "Afficher moins d'agences" : `Afficher les ${fmtInt(members.length)} agences`}247          </button>248        )}249      </div>250    </section>251  );252}253254// --- Propriétés --------------------------------------------------------------------255const partLabel = (p: InventoryPart) => p.sourceName;256257export function EntryInventory({ e, agencyOk }: { e: DirEntry; agencyOk: boolean | undefined }) {258  const parts = useMemo(() => e.inventory.filter((p) => p.count > 0).sort((a, b) => b.count - a.count), [e]);259  const [sel, setSel] = useState(0);260  const part = parts[Math.min(sel, parts.length - 1)];261262  if (!part) {263    return (264      <section className="border-t border-line pt-7">265        <h2 className="text-[1.5rem] sm:text-[1.75rem]">{e.followed ? "Aucune propriété affichée en ce moment" : e.site ? "Ses inscriptions sont publiées sur son site" : "Inventaire non synchronisé"}</h2>266        <p className="mt-2 max-w-xl text-[0.96rem] leading-relaxed text-ink-2">267          {e.followed268            ? `Immo-Ka suit les inscriptions de ${e.name}, mais aucune n'est publiée pour l'instant. L'inventaire est relu plusieurs fois par jour.`269            : `Les inscriptions de ${e.name} ne sont pas encore agrégées par Immo-Ka.${e.site ? " Consultez directement son site pour connaître les propriétés offertes." : ""}`}270        </p>271        {e.site && (272          <a href={e.site} target="_blank" rel="noopener noreferrer" className={buttonClass(e.followed ? "outline" : "primary", "lg", "mt-5")}>273            Voir le site <ExternalLink className="size-4" />274          </a>275        )}276      </section>277    );278  }279280  // bureau d'une bannière : il faut le filtre `agency` du serveur281  if (part.agency && agencyOk !== true) {282    return (283      <section aria-labelledby="proprietes-titre">284        <SectionHead id="proprietes-titre" title="Propriétés à vendre" text={<span className="num">{plural(e.listings, "inscription active", "inscriptions actives")}</span>} />285        {agencyOk === undefined ? (286          <div className="mt-6 grid grid-cols-1 gap-x-5 gap-y-8 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">287            {Array.from({ length: 4 }, (_, i) => (288              <ListingCardSkeleton key={i} />289            ))}290          </div>291        ) : (292          <div className="mt-5 max-w-xl">293            <p className="text-[0.96rem] leading-relaxed text-ink-2">294              Les inscriptions de cette agence sont publiées dans l'inventaire de {e.banner ? `la bannière ${e.banner.name}` : part.sourceName}. Le détail agence par agence n'est295              pas encore offert.296            </p>297            {e.banner && (298              <ButtonLink to={`${e.banner.path}#proprietes-titre`} variant="primary" size="lg" className="mt-5">299                Voir les propriétés {e.banner.name}300              </ButtonLink>301            )}302          </div>303        )}304      </section>305    );306  }307308  return (309    <Inventory310      query={{ source: part.source, agency: part.agency }}311      known={part.count}312      filters={313        parts.length > 1 && (314          <ChipRow label="Provenance des inscriptions">315            {parts.map((p, i) => (316              <FilterTab key={`${p.source}|${p.agency ?? ""}`} active={i === sel} onClick={() => setSel(i)} count={fmtInt(p.count)}>317                {partLabel(p)}318              </FilterTab>319            ))}320          </ChipRow>321        )322      }323      emptyText={`${e.name} n'a aucune propriété publiée pour l'instant. L'inventaire est relu plusieurs fois par jour.`}324    />325  );326}327328/** Note de source, en pied de fiche. */329export function EntryFootnote({ e, generated }: { e: DirEntry; generated: string | null }) {330  const date = generated ? new Date(generated + "T12:00:00").toLocaleDateString("fr-CA", { day: "numeric", month: "long", year: "numeric" }) : null;331  return (332    <p className={cn("max-w-3xl text-[0.82rem] leading-relaxed text-ink-3")}>333      {e.kind === "agence" || e.kind === "banniere"334        ? `Agences et courtiers : registre public des titulaires de permis de l'OACIQ${date ? `, relevé le ${date}` : ""}. Pour vérifier le dossier d'un courtier, consultez le registre officiel sur oaciq.com. `335        : ""}336      Les inscriptions et le prix médian sont ceux des propriétés agrégées par Immo-Ka, qui n'a aucun lien d'affaires avec {e.name.replace(/\.$/, "")}.337    </p>338  );339}340
Files main
Menu

Theme