SPB Git

Repository Public

Sources.tsx 10.2 KB 230 lines tsx

1// Sources : d'où viennent les annonces, et quand chacune a été lue pour la dernière fois.23import { useMemo, useState } from "react";4import { Link } from "react-router";5import { useQuery } from "@tanstack/react-query";6import { ArrowRight, ExternalLink } from "lucide-react";7import { fetchManagers, fetchSources, type Source } from "@/lib/api";8import { cn } from "@/lib/cn";9import { fmtAgo, fmtInt, plural } from "@/lib/format";10import { useDebounced, useTitle } from "@/lib/hooks";11import { LoukaEmptyState } from "@/brand/EmptyState";12import {13  ChipRow,14  ErrorState,15  FilterTab,16  norm,17  PageHead,18  prettyHost,19  regionKey,20  RowsSkeleton,21  SearchField,22  SortSelect,23  Toolbar,24  useProgressive,25} from "@/components/annuaire/shared";2627type SourceRow = Source;2829type State = "active" | "idle" | "site" | "pause";30const STATES: Record<State, { label: string; dot: string; hint: string }> = {31  active: { label: "Synchronisée", dot: "bg-good", hint: "Annonces lues automatiquement, plusieurs fois par jour." },32  idle: { label: "Sans annonce", dot: "bg-fair", hint: "Source lue, aucun logement publié en ce moment." },33  site: { label: "Sur son site", dot: "bg-ink-3", hint: "Inventaire non synchronisé : lien direct vers le site." },34  pause: { label: "En pause", dot: "bg-high", hint: "Lecture suspendue temporairement." },35};3637function stateOf(s: Source): State {38  const st = (s.status || "").toLowerCase();39  if (st.startsWith("pause") || st.startsWith("suspendu") || st.startsWith("inactif") || st.startsWith("retir")) return "pause";40  if (st.startsWith("actif") || st.startsWith("couvert")) return s.active_listings > 0 ? "active" : "idle";41  return "site";42}4344type Sort = "logements" | "nom" | "synchro";45const SORTS: { value: Sort; label: string }[] = [46  { value: "logements", label: "Logements" },47  { value: "nom", label: "Nom" },48  { value: "synchro", label: "Dernière lecture" },49];5051// colonnes (grand écran) : source · état et dernière lecture · logements · lien52const COLS = "md:grid md:grid-cols-[minmax(0,1fr)_11rem_6rem_1.25rem] md:items-center md:gap-x-6";5354function Row({ s, state, hasPage }: { s: SourceRow; state: State; hasPage: boolean }) {55  const meta = STATES[state];56  const internal = state === "active" || state === "idle";57  const read = s.last_sync ? `Lue ${fmtAgo(s.last_sync)}` : meta.label;58  const body = (59    <>60      <div className="min-w-0">61        <div className="flex items-baseline justify-between gap-4">62          <span className="truncate text-[0.98rem] text-ink transition-colors duration-150 group-hover:text-brand">{s.name}</span>63          <span className="num shrink-0 text-[0.9rem] font-semibold text-ink md:hidden">{state === "site" || state === "pause" ? "" : fmtInt(s.active_listings)}</span>64        </div>65        <p className="mt-0.5 truncate text-[0.82rem] text-ink-3">66          {regionKey(s.region)}67          {s.url ? ` · ${prettyHost(s.url)}` : ""}68        </p>69        <p className="mt-0.5 flex items-center gap-1.5 text-[0.8rem] text-ink-3 md:hidden">70          <span className={cn("size-1.5 shrink-0 rounded-full", meta.dot)} aria-hidden />71          {state === "active" ? read : `${meta.label}${s.last_sync && state === "idle" ? ` · ${read.toLowerCase()}` : ""}`}72        </p>73      </div>74      <div className="hidden items-center gap-2 text-[0.84rem] text-ink-3 md:flex">75        <span className={cn("size-1.5 shrink-0 rounded-full", meta.dot)} aria-hidden />76        <span className="truncate">{state === "active" || (state === "idle" && s.last_sync) ? read : meta.label}</span>77      </div>78      <div className="num hidden text-right text-[0.92rem] md:block">79        {state === "site" || state === "pause" ? <span className="text-ink-3">—</span> : <span className="font-semibold text-ink">{fmtInt(s.active_listings)}</span>}80      </div>81      <span className="hidden text-ink-3 transition-colors duration-150 group-hover:text-ink md:block" aria-hidden>82        {internal ? <ArrowRight className="size-4" /> : <ExternalLink className="size-4" />}83      </span>84    </>85  );86  const cls = cn("group block border-b border-line py-3 transition-colors duration-150 hover:border-ink-3", COLS);87  const href = s.listing_url || s.url;88  if (internal || !href) {89    return (90      // gestionnaire : sa fiche · plateforme d'annonces : ses logements sur la carte91      <li>92        <Link to={hasPage ? `/g/${s.id}` : `/recherche?source=${encodeURIComponent(s.id)}`} className={cls} title={meta.hint}>93          {body}94        </Link>95      </li>96    );97  }98  return (99    <li>100      <a href={href} target="_blank" rel="noopener noreferrer" className={cls} title={meta.hint} aria-label={`${s.name}, voir le site (nouvel onglet)`}>101        {body}102      </a>103    </li>104  );105}106107export default function Sources() {108  useTitle("Sources agrégées");109  const q = useQuery({ queryKey: ["sources"], queryFn: fetchSources, staleTime: 3e5 });110  const dir = useQuery({ queryKey: ["managers"], queryFn: fetchManagers, staleTime: 6e5 });111  const pages = useMemo(() => new Set((dir.data?.managers ?? []).map((m) => m.id)), [dir.data]);112  const [text, setText] = useState("");113  const [region, setRegion] = useState<string | null>(null);114  const [state, setState] = useState<State | null>(null);115  const [sort, setSort] = useState<Sort>("logements");116  const needle = norm(useDebounced(text, 120).trim());117118  // Lou-Ka couvre le Québec : les sources hors province ne sont pas listées119  const index = useMemo(120    () =>121      ((q.data?.sources ?? []) as SourceRow[])122        .filter((s) => !(s.region ?? "").toLowerCase().startsWith("ontario"))123        .map((s) => ({ s, state: stateOf(s), region: regionKey(s.region), hay: norm(`${s.name} ${s.region ?? ""} ${s.sectors} ${s.url}`) })),124    [q.data],125  );126127  const regions = useMemo(() => {128    const m = new Map<string, number>();129    for (const x of index) m.set(x.region, (m.get(x.region) ?? 0) + 1);130    return [...m.entries()].sort((a, b) => b[1] - a[1]);131  }, [index]);132133  const counts = useMemo(() => {134    const c: Record<State, number> = { active: 0, idle: 0, site: 0, pause: 0 };135    for (const x of index) c[x.state] += 1;136    return c;137  }, [index]);138139  const rows = useMemo(() => {140    const r = index.filter((x) => (!needle || x.hay.includes(needle)) && (!region || x.region === region) && (!state || x.state === state));141    if (sort === "nom") r.sort((a, b) => a.s.name.localeCompare(b.s.name, "fr"));142    else if (sort === "synchro") r.sort((a, b) => (b.s.last_sync ?? 0) - (a.s.last_sync ?? 0));143    else r.sort((a, b) => b.s.active_listings - a.s.active_listings || a.s.name.localeCompare(b.s.name, "fr"));144    return r;145  }, [index, needle, region, state, sort]);146147  const { count, sentinel } = useProgressive(rows.length, `${needle}|${region}|${state}|${sort}`, 80);148  const total = useMemo(() => index.reduce((n, x) => n + x.s.active_listings, 0), [index]);149  const latest = useMemo(() => index.reduce((t, x) => Math.max(t, x.s.last_sync ?? 0), 0), [index]);150151  return (152    <>153      <PageHead154        eyebrow="Transparence"155        title="D'où viennent les annonces"156        text="Lou-Ka lit directement les sites des gestionnaires immobiliers et des plateformes d'annonces, plusieurs fois par jour. Chaque logement renvoie vers son annonce d'origine. Voici toutes les sources et le moment de leur dernière lecture."157        facts={158          !!q.data && [159            { value: fmtInt(index.length), label: "sources suivies" },160            { value: fmtInt(counts.active), label: "avec des annonces actives" },161            { value: fmtInt(total), label: "annonces lues" },162            ...(latest ? [{ value: fmtAgo(latest), label: "dernière lecture" }] : []),163          ]164        }165      />166167      <Toolbar>168        <div className="flex flex-wrap items-center gap-2">169          <SearchField value={text} onChange={setText} placeholder="Chercher une source" className="min-w-0 flex-1 basis-64" />170          <SortSelect value={sort} onChange={setSort} options={SORTS} />171        </div>172        <ChipRow label="État de la source">173          {(Object.keys(STATES) as State[]).map((k) => (174            <FilterTab key={k} active={state === k} onClick={() => setState(state === k ? null : k)} count={counts[k]}>175              <span className={cn("size-1.5 rounded-full", STATES[k].dot)} aria-hidden />176              {STATES[k].label}177            </FilterTab>178          ))}179        </ChipRow>180        <ChipRow label="Région">181          <FilterTab active={!region} onClick={() => setRegion(null)}>182            Toutes les régions183          </FilterTab>184          {regions.map(([r, n]) => (185            <FilterTab key={r} active={region === r} onClick={() => setRegion(region === r ? null : r)} count={n}>186              {r}187            </FilterTab>188          ))}189        </ChipRow>190      </Toolbar>191192      <div className="container-x pt-6">193        {q.isError ? (194          <ErrorState onRetry={() => q.refetch()} />195        ) : q.isPending ? (196          <RowsSkeleton rows={12} />197        ) : rows.length === 0 ? (198          <LoukaEmptyState kind="closed" title="Aucune source trouvée" text="Essayez un autre nom ou retirez un filtre." />199        ) : (200          <>201            <p className="num mb-4 text-[0.86rem] text-ink-3" aria-live="polite">202              {plural(rows.length, "source", "sources")}203              {state ? ` · ${STATES[state].hint}` : ""}204            </p>205            <div className={cn("hidden border-b border-line-2 pb-2 text-[0.76rem] text-ink-3", COLS)} aria-hidden>206              <span>Source</span>207              <span>Dernière lecture</span>208              <span className="text-right">Logements actifs</span>209              <span />210            </div>211            <ul key={`${region}|${state}|${sort}`} className="lk-stagger lk-stagger--swap">212              {rows.slice(0, count).map((x) => (213                <Row key={x.s.id} s={x.s} state={x.state} hasPage={pages.has(x.s.id)} />214              ))}215            </ul>216            {sentinel}217            <p className="mt-10 max-w-2xl text-[0.9rem] leading-relaxed text-ink-3">218              Il manque un gestionnaire ou une plateforme ?{" "}219              <Link to="/contact" className="text-brand underline underline-offset-[3px]">220                Écrivez-nous221              </Link>222              , nous l'ajouterons à la liste.223            </p>224          </>225        )}226      </div>227    </>228  );229}230
Files main
Menu

Theme