SPB Git

Repository Public

Sources.tsx 14.2 KB 316 lines tsx

1// Sources : d'où viennent les inscriptions, combien sont lues et publiées, et2// quand chaque source a été lue pour la dernière fois.34import { memo, useMemo, useState } from "react";5import { Link } from "react-router";6import { useQuery } from "@tanstack/react-query";7import { ArrowRight, ExternalLink } from "lucide-react";8import { fetchSiteStats, fetchSources, isQuebecSource, kindOfSource, type EntryKind, type SourceRow } from "@/lib/api.annuaires";9import { cn } from "@/lib/cn";10import { fmtAgo, fmtInt, plural } from "@/lib/format";11import { useDebounced, useTitle } from "@/lib/hooks";12import { BrandEmptyState } from "@/brand/compat";13import { Button } from "@/ui/primitives";14import { ChipRow, ErrorState, FilterTab, norm, PageHead, prettyHost, rowClass, Rows, RowsSkeleton, SearchField, SortSelect, Toolbar, useDirectory } from "@/components/annuaire-ik/shared";1516type State = "active" | "idle" | "todo" | "off";17const STATES: Record<State, { label: string; dot: string; hint: string }> = {18  active: { label: "Synchronisée", dot: "bg-good", hint: "Inscriptions lues automatiquement, plusieurs fois par jour." },19  idle: { label: "Sans inscription publiée", dot: "bg-fair", hint: "Source lue, mais aucune inscription publiée en ce moment." },20  todo: { label: "À venir", dot: "bg-ink-3", hint: "Source recensée, pas encore synchronisée : lien direct vers son site." },21  off: { label: "Inactive", dot: "bg-high", hint: "Lecture suspendue." },22};2324const KINDS: Record<EntryKind, string> = { banniere: "Bannières", agence: "Agences", direct: "Vente directe", plateforme: "Plateformes" };2526const TYPE_LABEL: Record<string, string> = {27  franchise: "Bannière de courtage",28  agence: "Agence immobilière",29  luxe: "Agence, propriétés de prestige",30  fsbo: "Vente directe, sans courtier",31  portail: "Portail d'annonces",32  "petites annonces": "Petites annonces",33  "agrégateur": "Agrégateur",34  "répertoire": "Répertoire de projets neufs",35  chambre: "Chambre immobilière",36  "équipe": "Équipe de courtiers",37  annuaire: "Annuaire de courtiers",38};39const KIND_FALLBACK: Record<EntryKind, string> = { banniere: "Bannière de courtage", agence: "Agence immobilière", direct: "Vente directe, sans courtier", plateforme: "Petites annonces" };4041interface Item {42  s: SourceRow;43  state: State;44  kind: EntryKind;45  /** inscriptions publiées (après dédoublonnage et contrôle de qualité) ; `null` : inconnu */46  published: number | null;47  typeLabel: string;48  hay: string;49}5051function stateOf(s: SourceRow, published: number | null): State {52  const st = (s.status ?? "").toLowerCase();53  if (st.startsWith("inactif") || st.startsWith("pause")) return "off";54  if (st.startsWith("actif")) return (published ?? s.active_listings) > 0 ? "active" : "idle";55  return "todo";56}5758type Sort = "publiees" | "lues" | "nom" | "synchro";59const SORTS: { value: Sort; label: string }[] = [60  { value: "publiees", label: "Inscriptions publiées" },61  { value: "lues", label: "Inscriptions lues" },62  { value: "nom", label: "Nom" },63  { value: "synchro", label: "Dernière lecture" },64];6566// colonnes (grand écran) : source · état et dernière lecture · lues · publiées · lien67const COLS = "md:grid md:grid-cols-[minmax(0,1fr)_11.5rem_5.5rem_5.5rem_1.25rem] md:items-center md:gap-x-6";6869const SourceLine = memo(function SourceLine({ it, to }: { it: Item; to: string | null }) {70  const { s, state, published } = it;71  const meta = STATES[state];72  const live = state === "active" || state === "idle";73  const read = s.last_sync ? `Lue ${fmtAgo(s.last_sync)}` : meta.label;74  const status = state === "active" ? read : s.last_sync && state !== "todo" ? `${meta.label} · ${read.toLowerCase()}` : meta.label;75  const body = (76    <>77      <div className="min-w-0">78        <div className="flex items-baseline justify-between gap-4">79          <span className="truncate text-[0.98rem] text-ink transition-colors duration-150 group-hover:text-brand">{s.name}</span>80          <span className="num shrink-0 text-[0.9rem] md:hidden">81            {live && published != null && (82              <>83                <span className="font-semibold text-ink">{fmtInt(published)}</span>84                <span className="text-[0.8rem] text-ink-3"> publiées</span>85              </>86            )}87          </span>88        </div>89        <p className="mt-0.5 truncate text-[0.82rem] text-ink-3">90          {it.typeLabel}91          {s.url ? ` · ${prettyHost(s.url)}` : ""}92        </p>93        <p className="num mt-0.5 flex items-center gap-1.5 text-[0.8rem] text-ink-3 md:hidden">94          <span className={cn("size-1.5 shrink-0 rounded-full", meta.dot)} aria-hidden />95          <span className="truncate">96            {status}97            {live && s.active_listings > 0 ? ` · ${fmtInt(s.active_listings)} lues` : ""}98          </span>99        </p>100      </div>101      <div className="hidden items-center gap-2 text-[0.84rem] text-ink-3 md:flex">102        <span className={cn("size-1.5 shrink-0 rounded-full", meta.dot)} aria-hidden />103        <span className="truncate">{status}</span>104      </div>105      <div className="num hidden text-right text-[0.9rem] md:block">{live ? <span className="text-ink-2">{fmtInt(s.active_listings)}</span> : <span className="text-ink-3">—</span>}</div>106      <div className="num hidden text-right text-[0.92rem] md:block">107        {live && published != null ? <span className="font-semibold text-ink">{fmtInt(published)}</span> : <span className="text-ink-3">—</span>}108      </div>109      <span className="hidden text-ink-3 transition-colors duration-150 group-hover:text-ink md:block" aria-hidden>110        {to ? <ArrowRight className="size-4" /> : <ExternalLink className="size-4" />}111      </span>112    </>113  );114  const cls = cn(rowClass, "!py-3", COLS);115  const href = s.listing_url || s.url;116  return (117    <div role="listitem">118      {to ? (119        <Link to={to} className={cls} title={meta.hint}>120          {body}121        </Link>122      ) : href ? (123        <a href={href} target="_blank" rel="noopener noreferrer" className={cls} title={meta.hint} aria-label={`${s.name}, voir le site (nouvel onglet)`}>124          {body}125        </a>126      ) : (127        <div className={cls} title={meta.hint}>128          {body}129        </div>130      )}131    </div>132  );133});134135export default function Sources() {136  useTitle("Sources des inscriptions");137  const q = useQuery({ queryKey: ["ik-sources"], queryFn: fetchSources, staleTime: 3e5 });138  const stats = useQuery({ queryKey: ["ik-stats"], queryFn: fetchSiteStats, staleTime: 3e5 });139  const dir = useDirectory();140  const [input, setInput] = useState("");141  const [state, setState] = useState<State | null>(null);142  const [kind, setKind] = useState<EntryKind | null>(null);143  const [sort, setSort] = useState<Sort>("publiees");144  const needle = norm(useDebounced(input, 120).trim());145146  const published = useMemo(() => {147    const rows = stats.data?.qualite?.par_source;148    return rows ? new Map(rows.map((r) => [r.source, r.publiees])) : null;149  }, [stats.data]);150151  // Immo-Ka couvre le Québec : les connecteurs hors province ne sont pas listés152  const index = useMemo<Item[]>(153    () =>154      (q.data ?? []).filter(isQuebecSource).map((s) => {155        const pub = published ? (published.get(s.id) ?? 0) : null;156        const k = kindOfSource(s, s.id);157        return {158          s,159          state: stateOf(s, pub),160          kind: k,161          published: pub,162          typeLabel: TYPE_LABEL[(s.type ?? "").toLowerCase()] ?? KIND_FALLBACK[k],163          hay: norm(`${s.name} ${s.type ?? ""} ${s.coverage ?? ""} ${s.url ?? ""}`),164        };165      }),166    [q.data, published],167  );168169  const counts = useMemo(() => {170    const st: Record<State, number> = { active: 0, idle: 0, todo: 0, off: 0 };171    const kd: Record<EntryKind, number> = { banniere: 0, agence: 0, direct: 0, plateforme: 0 };172    let read = 0;173    let pub = 0;174    let latest = 0;175    for (const x of index) {176      st[x.state] += 1;177      kd[x.kind] += 1;178      read += x.s.active_listings;179      pub += x.published ?? 0;180      latest = Math.max(latest, x.s.last_sync ?? 0);181    }182    return { st, kd, read, pub, latest };183  }, [index]);184185  const rows = useMemo(() => {186    const r = index.filter((x) => (!needle || x.hay.includes(needle)) && (!state || x.state === state) && (!kind || x.kind === kind));187    if (sort === "nom") r.sort((a, b) => a.s.name.localeCompare(b.s.name, "fr"));188    else if (sort === "synchro") r.sort((a, b) => (b.s.last_sync ?? 0) - (a.s.last_sync ?? 0));189    else if (sort === "lues") r.sort((a, b) => b.s.active_listings - a.s.active_listings || a.s.name.localeCompare(b.s.name, "fr"));190    else r.sort((a, b) => (b.published ?? b.s.active_listings) - (a.published ?? a.s.active_listings) || a.s.name.localeCompare(b.s.name, "fr"));191    return r;192  }, [index, needle, state, kind, sort]);193194  const filtered = !!needle || !!state || !!kind;195  const total = stats.data?.total ?? (published ? counts.pub : null);196197  return (198    <>199      <PageHead200        eyebrow="Transparence"201        title="D'où viennent les inscriptions"202        text="Immo-Ka lit directement les sites des bannières de courtage, des agences, des services de vente directe et des plateformes d'annonces, plusieurs fois par jour. Chaque propriété renvoie vers son inscription d'origine. Voici toutes les sources, ce qui y est lu, ce qui est publié et le moment de la dernière lecture."203        facts={204          !!q.data &&205          !stats.isPending && [206            { value: fmtInt(index.length), label: "sources suivies" },207            { value: fmtInt(counts.st.active), label: "avec des inscriptions publiées" },208            { value: total != null ? fmtInt(total) : "—", label: "inscriptions publiées" },209            { value: counts.latest ? fmtAgo(counts.latest) : "—", label: "dernière lecture" },210          ]211        }212      />213214      <Toolbar>215        <div className="flex flex-wrap items-center gap-2">216          <SearchField value={input} onChange={setInput} placeholder="Chercher une source" className="min-w-0 flex-1 basis-64" />217          <SortSelect value={sort} onChange={setSort} options={SORTS} />218        </div>219        <ChipRow label="État de la source">220          {(Object.keys(STATES) as State[]).map((k) => (221            <FilterTab key={k} active={state === k} onClick={() => setState(state === k ? null : k)} count={q.data ? counts.st[k] : undefined}>222              <span className={cn("size-1.5 rounded-full", STATES[k].dot)} aria-hidden />223              {STATES[k].label}224            </FilterTab>225          ))}226          <span className="mx-1 w-px shrink-0 self-stretch bg-line" aria-hidden />227          {(Object.keys(KINDS) as EntryKind[]).map((k) => (228            <FilterTab key={k} active={kind === k} onClick={() => setKind(kind === k ? null : k)} count={q.data ? counts.kd[k] : undefined}>229              {KINDS[k]}230            </FilterTab>231          ))}232        </ChipRow>233      </Toolbar>234235      <div className="container-x pt-6">236        {q.isError ? (237          <ErrorState onRetry={() => q.refetch()} />238        ) : q.isPending ? (239          <RowsSkeleton rows={12} tall />240        ) : rows.length === 0 ? (241          <BrandEmptyState242            kind="closed"243            title="Aucune source trouvée"244            text="Essayez un autre nom ou retirez un filtre."245            action={246              filtered && (247                <Button248                  variant="outline"249                  onClick={() => {250                    setInput("");251                    setState(null);252                    setKind(null);253                  }}254                >255                  Effacer les filtres256                </Button>257              )258            }259          />260        ) : (261          <>262            <p className="num mb-4 min-h-[1.3rem] text-[0.86rem] text-ink-3" aria-live="polite">263              {plural(rows.length, "source", "sources")}264              {state ? ` · ${STATES[state].hint}` : ""}265            </p>266            <div className={cn("hidden border-b border-line-2 pb-2 text-[0.76rem] text-ink-3", COLS)} aria-hidden>267              <span>Source</span>268              <span>Dernière lecture</span>269              <span className="text-right">Lues</span>270              <span className="text-right">Publiées</span>271              <span />272            </div>273            <Rows resetKey={`${state}|${kind}|${sort}`}>274              {rows.map((x) => {275                const e = dir.data?.bySource.get(x.s.id);276                // la fiche de l'annuaire quand elle montre quelque chose, sinon le site277                const to = e && (e.listings > 0 || e.oaciqSlug || e.agencies > 0) ? e.path : null;278                return <SourceLine key={x.s.id} it={x} to={to} />;279              })}280            </Rows>281282            <div className="mt-12 grid max-w-4xl gap-x-12 gap-y-6 border-t border-line pt-7 md:grid-cols-2">283              <div>284                <h2 className="text-[1.25rem]">Lues, puis publiées</h2>285                <p className="mt-2 text-[0.9rem] leading-relaxed text-ink-2">286                  {published && counts.read > 0 ? (287                    <>288                      Sur <span className="num font-medium text-ink">{fmtInt(counts.read)}</span> inscriptions lues dans ces sources,{" "}289                      <span className="num font-medium text-ink">{fmtInt(counts.pub)}</span> sont publiées.{" "}290                    </>291                  ) : null}292                  Une même propriété offerte par plusieurs sources n'est affichée qu'une fois. Une inscription sans prix plausible, sans ville ou sans type de propriété attend293                  d'être complétée par une prochaine lecture avant d'être publiée.294                </p>295              </div>296              <div>297                <h2 className="text-[1.25rem]">Il manque une source ?</h2>298                <p className="mt-2 text-[0.9rem] leading-relaxed text-ink-2">299                  <Link to="/contact" className="text-brand underline underline-offset-[3px]">300                    Écrivez-nous301                  </Link>{" "}302                  : nous l'ajouterons à la liste. L'annuaire complet des agences et de leurs courtiers se trouve sur la page{" "}303                  <Link to="/agences" className="text-brand underline underline-offset-[3px]">304                    Courtiers, agences et bannières305                  </Link>306                  .307                </p>308              </div>309            </div>310          </>311        )}312      </div>313    </>314  );315}316
Files main
Menu

Theme