SPB Git

Repository Public

Content.tsx 13.6 KB 278 lines tsx

1// Description, inclusions et commodités, détails pratiques.23import { motion } from "motion/react";4import { useMemo, useState } from "react";5import {6  AirVent, ArrowUpDown, Bath, BedDouble, Building, CalendarDays, Car, Check, CigaretteOff, Dumbbell, FileText, Flame, Home, Package,7  PawPrint, Refrigerator, Ruler, ShowerHead, Sofa, Sun, Tv, Users, WashingMachine, Waves, Wifi, Zap,8} from "lucide-react";9import { priceOk, type Listing } from "@/lib/api";10import { cn } from "@/lib/cn";11import { fmtAgo, fmtAvailability, fmtInt, fmtMoney } from "@/lib/format";12import { prettySource, useSourceNames } from "@/lib/hooks";13import { KV, MoreLink, Pill, Section } from "./kit";14import { bathroomsOf } from "./Overview";1516// --- Description ----------------------------------------------------------------17export function hasDescription(l: Listing) {18  return !!(l.digest?.texte_nettoye || l.digest?.sections?.length || l.description?.trim());19}2021function Paragraphs({ text }: { text: string }) {22  return (23    <>24      {text25        .split(/\n{2,}|\n(?=[A-ZÀ-Ý•\-–])/)26        .map((p) => p.trim())27        .filter(Boolean)28        .map((p, i) => (29          <p key={i} className="whitespace-pre-line">30            {p}31          </p>32        ))}33    </>34  );35}3637export function Description({ l }: { l: Listing }) {38  const [open, setOpen] = useState(false);39  const d = l.digest;40  const sections = (d?.sections ?? []).filter((s) => s.texte?.trim());41  const plain = (d?.texte_nettoye || l.description || "").trim();42  const length = sections.length ? sections.reduce((n, s) => n + s.texte.length, 0) : plain.length;43  const long = length > 620;44  if (!hasDescription(l)) return null;45  return (46    <Section id="description" title="Description" eyebrow="Le logement">47      {d?.en_bref && (48        <p className="mb-5 max-w-3xl border-l-2 border-accent pl-4 text-[1rem] leading-relaxed text-ink">49          <span className="font-semibold">En bref. </span>50          {d.en_bref}51        </p>52      )}53      <motion.div className={cn("relative", long && "overflow-hidden")} initial={false} animate={{ height: long && !open ? 256 : "auto" }} transition={{ duration: 0.36, ease: [0.6, 0, 0.16, 1] }}>54        <div className="max-w-3xl space-y-4 text-[1rem] leading-[1.7] text-ink-2">55          {sections.length > 0 ? (56            sections.map((s, i) => (57              <div key={i}>58                {sections.length > 1 && s.titre && s.titre !== "Description" && <h3 className="mb-1.5 text-[1.02rem] text-ink">{s.titre}</h3>}59                <div className="space-y-3">60                  <Paragraphs text={s.texte} />61                </div>62              </div>63            ))64          ) : (65            <Paragraphs text={plain} />66          )}67        </div>68        <div className={cn("pointer-events-none absolute inset-x-0 bottom-0 h-14 bg-gradient-to-t from-bg to-transparent transition-opacity duration-300", long && !open ? "opacity-100" : "opacity-0")} />69      </motion.div>70      {long && <MoreLink onClick={() => setOpen((o) => !o)}>{open ? "Réduire la description" : "Lire toute la description"}</MoreLink>}71      {(d?.incoherences?.length ?? 0) > 0 && (72        <p className="mt-4 rounded-[10px] bg-high-soft px-4 py-3 text-[0.9rem] text-high">Incohérence relevée dans l'annonce : {d!.incoherences.join(" ; ")}</p>73      )}74    </Section>75  );76}7778// --- Inclusions et commodités ---------------------------------------------------79type Lucide = typeof Check;8081/** Inclusions confirmées par les données structurées de la source. */82function confirmed(l: Listing): string[] {83  const d = l.details ?? {};84  const out: string[] = [];85  const inc = d.inclusions ?? {};86  if (inc.heating) out.push("Chauffage inclus");87  if (inc.electricity) out.push("Électricité incluse");88  if (inc.hot_water) out.push("Eau chaude incluse");89  if (inc.internet) out.push("Internet inclus");90  if (inc.cable) out.push("Câble inclus");91  const app = d.appliances ?? {};92  if (app.dishwasher) out.push("Lave-vaisselle");93  if (app.washer_dryer) out.push("Laveuse-sécheuse");94  if (app.fridge && app.stove) out.push("Électroménagers");95  else if (app.fridge) out.push("Réfrigérateur");96  if (d.ac) out.push("Climatisation");97  if (d.elevator) out.push("Ascenseur");98  if (d.balcony) out.push("Balcon");99  if (d.pool) out.push("Piscine");100  if (d.gym) out.push("Gym");101  if (d.laundry) out.push("Buanderie");102  if (d.storage) out.push("Rangement");103  const p = d.parking;104  if (p && typeof p === "object" ? p.available : p) {105    const o = typeof p === "object" ? p : null;106    out.push(`Stationnement${o?.type ? ` ${o.type}` : ""}${o?.included ? " inclus" : ""}`);107  }108  if (l.furnished) out.push("Meublé");109  if (d.smoking === false) out.push("Non-fumeur");110  return out;111}112113const FR: [RegExp, string][] = [114  [/^balcony$/i, "Balcon"], [/^storage$/i, "Rangement"], [/^(in-?unit|onsite|on-site) laundry$/i, "Buanderie"],115  [/^laundry$/i, "Buanderie"], [/^dishwasher$/i, "Lave-vaisselle"], [/^hardwood floors?$/i, "Planchers de bois franc"],116  [/^high ceilings?$/i, "Plafonds hauts"], [/^parking$/i, "Stationnement"], [/^gym|fitness/i, "Gym"],117  [/^pool$/i, "Piscine"], [/^elevator$/i, "Ascenseur"], [/^furnished$/i, "Meublé"], [/^heating$/i, "Chauffage"],118  [/^air conditioning|a\/c$/i, "Climatisation"], [/^pets? (allowed|friendly)$/i, "Animaux acceptés"],119  [/^wheelchair access(ible)?$/i, "Accès fauteuil roulant"], [/^doorman$/i, "Portier"], [/^garage$/i, "Garage"],120  [/^fridge|refrigerator$/i, "Réfrigérateur"], [/^oven|stove$/i, "Cuisinière"], [/^microwave$/i, "Micro-ondes"],121  [/^washer$/i, "Laveuse"], [/^dryer$/i, "Sécheuse"], [/^terrace|rooftop/i, "Terrasse"], [/^bike (storage|room)$/i, "Rangement à vélos"],122];123const toFr = (a: string) => {124  for (const [re, t] of FR) if (re.test(a.trim())) return t;125  return a.trim();126};127const norm = (s: string) => s.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/s\b/g, "");128129const ICONS: [RegExp, Lucide][] = [130  [/chauffage/i, Flame], [/electricit/i, Zap], [/eau chaude/i, ShowerHead], [/internet|wifi|wi-fi/i, Wifi], [/cable|tele/i, Tv],131  [/lave-vaisselle|electromenager|refrigerateur|cuisiniere|micro/i, Refrigerator], [/laveuse|secheuse|buanderie/i, WashingMachine],132  [/climatis/i, AirVent], [/ascenseur/i, ArrowUpDown], [/balcon|terrasse/i, Sun], [/piscine/i, Waves], [/gym/i, Dumbbell],133  [/rangement|locker|casier/i, Package], [/stationnement|garage/i, Car], [/meuble/i, Sofa], [/non-fumeur/i, CigaretteOff], [/animaux/i, PawPrint],134];135const iconFor = (label: string): Lucide => {136  const n = label.normalize("NFD").replace(/[̀-ͯ]/g, "");137  for (const [re, I] of ICONS) if (re.test(n)) return I;138  return Check;139};140141export function amenitiesOf(l: Listing) {142  const ok = confirmed(l);143  const others = Array.from(new Set((l.amenities ?? []).map(toFr).filter(Boolean))).filter(144    (a) => !ok.some((b) => norm(b).includes(norm(a)) || norm(a).includes(norm(b))),145  );146  return { ok, others };147}148149export function Amenities({ l }: { l: Listing }) {150  const [all, setAll] = useState(false);151  const { ok, others } = useMemo(() => amenitiesOf(l), [l]);152  const items = [...ok.map((t) => ({ t, ok: true })), ...others.map((t) => ({ t, ok: false }))];153  if (!items.length) return null;154  const inc = l.details?.inclusions ?? {};155  const noHidden = inc.heating && inc.electricity && inc.hot_water;156  const LIMIT = 12;157  const shown = all ? items : items.slice(0, LIMIT);158  return (159    <Section160      id="inclusions"161      eyebrow="Ce qui est compris"162      title="Inclusions et commodités"163      text={`${ok.length} confirmée${ok.length > 1 ? "s" : ""} par les données de la source${others.length ? ` · ${others.length} mentionnée${others.length > 1 ? "s" : ""} dans l'annonce` : ""}`}164    >165      {noHidden && (166        <div className="mb-5">167          <Pill tone="good">168            <Check className="size-3.5" strokeWidth={3} /> Chauffage, électricité et eau chaude inclus169          </Pill>170        </div>171      )}172      <ul className="grid grid-cols-1 gap-x-8 sm:grid-cols-2 xl:grid-cols-3">173        {shown.map((it) => {174          const Icon = iconFor(it.t);175          return (176            <li177              key={it.t}178              title={it.ok ? "Confirmé par les données structurées de la source" : "Mentionné dans l'annonce"}179              className="flex items-center gap-3 border-b border-line py-3"180            >181              <Icon className={cn("size-[18px] shrink-0", it.ok ? "text-brand" : "text-ink-3")} />182              <span className="min-w-0 flex-1 truncate text-[0.94rem] text-ink">{it.t}</span>183              {it.ok && <Check className="size-4 shrink-0 text-good" strokeWidth={2.4} aria-label="confirmé" />}184            </li>185          );186        })}187      </ul>188      {items.length > LIMIT && <MoreLink onClick={() => setAll((a) => !a)}>{all ? "Réduire" : `Voir les ${items.length} commodités`}</MoreLink>}189    </Section>190  );191}192193// --- Détails pratiques ----------------------------------------------------------194const CONSTRAINTS: Record<string, string> = {195  references_requises: "Références requises",196  enquete_credit: "Enquête de crédit",197  non_fumeur: "Non-fumeur",198  pas_animaux: "Animaux refusés",199  bail_12_mois: "Bail de 12 mois",200  depot_requis: "Dépôt requis",201  preuve_revenu: "Preuve de revenu",202  assurance_requise: "Assurance habitation requise",203};204/** Clé technique du résumé d'annonce → libellé lisible. */205function humanize(key: string): string {206  if (CONSTRAINTS[key]) return CONSTRAINTS[key]!;207  const t = key.replace(/_/g, " ").trim();208  return t.charAt(0).toUpperCase() + t.slice(1);209}210211export function Practical({ l }: { l: Listing }) {212  const names = useSourceNames();213  const f = l.digest?.faits;214  const conf = l.digest?.confiance ?? {};215  const d = l.details ?? {};216  const sdb = bathroomsOf(l);217  const dispo = fmtAvailability(l.availability_date, true);218  const p = d.parking;219  const po = p && typeof p === "object" ? p : null;220221  const facts: { icon: Lucide; k: string; v: string }[] = [];222  if (dispo) facts.push({ icon: CalendarDays, k: "Disponibilité", v: dispo });223  else if (l.availability) facts.push({ icon: CalendarDays, k: "Disponibilité", v: l.availability });224  if (f?.duree_bail_minimale_mois) facts.push({ icon: FileText, k: "Bail minimal", v: `${f.duree_bail_minimale_mois} mois` });225  if (l.pets) facts.push({ icon: PawPrint, k: "Animaux", v: l.pets === "oui" ? "Acceptés" : l.pets === "non" ? "Refusés" : "Sous conditions" });226  if (p != null && (po ? po.available != null : true)) {227    const has = po ? !!po.available : !!p;228    const txt = !has229      ? "Aucun"230      : [typeof p === "number" && p > 1 ? `${p} places` : "Disponible", po?.type, po?.included ? "inclus" : po?.price ? `${fmtMoney(po.price)} / mois` : null].filter(Boolean).join(" · ");231    facts.push({ icon: Car, k: "Stationnement", v: txt });232  }233  if (l.furnished != null) facts.push({ icon: Sofa, k: "Ameublement", v: l.furnished ? "Meublé" : "Non meublé" });234  if (l.bedrooms != null) facts.push({ icon: BedDouble, k: l.bedrooms > 1 ? "Chambres" : l.bedrooms === 0 ? "Aire ouverte" : "Chambre", v: l.bedrooms === 0 ? "Studio" : String(Math.round(l.bedrooms)) });235  if (sdb != null) facts.push({ icon: Bath, k: sdb > 1 ? "Salles de bain" : "Salle de bain", v: String(sdb) });236  else if (f?.salle_de_bain && conf.salle_de_bain !== "faible") facts.push({ icon: Bath, k: "Salle de bain", v: f.salle_de_bain === "commune" ? "Partagée" : "Privée" });237  if (f?.cuisine && conf.cuisine !== "faible") facts.push({ icon: Refrigerator, k: "Cuisine", v: f.cuisine === "commune" ? "Partagée" : "Privée" });238  if (l.area_sqft) facts.push({ icon: Ruler, k: "Superficie", v: `${fmtInt(l.area_sqft)} pi²` });239  if (d.floor != null) facts.push({ icon: Building, k: "Étage", v: `${d.floor}ᵉ` });240  if (f?.nb_occupants_total && conf.nb_occupants_total !== "faible") facts.push({ icon: Users, k: "Occupants", v: String(f.nb_occupants_total) });241  if (l.unit_type) facts.push({ icon: Home, k: "Type", v: l.unit_type });242243  const online = l.first_seen ? Math.max(0, Math.round((Date.now() / 1000 - l.first_seen) / 86400)) : null;244  const rows: [string, string][] = [["Publiée par", prettySource(l.source, names)]];245  if (l.price_label && priceOk(l.price) && l.price_label.replace(/\D/g, "") !== String(Math.round(l.price))) rows.push(["Prix affiché par la source", l.price_label]);246  if (online != null) rows.push(["En ligne sur Lou-Ka", online === 0 ? "depuis aujourd'hui" : `depuis ${online} jour${online > 1 ? "s" : ""}`]);247  rows.push(["Dernière synchronisation", fmtAgo(l.updated_at)]);248  if (f?.depot_mentionne && conf.depot_mentionne !== "faible") rows.push(["Dépôt mentionné", f.depot_mentionne]);249  if (f?.contraintes?.length) rows.push(["Conditions", f.contraintes.map(humanize).join(", ")]);250  const contact = d.contact;251  if (contact?.phone) rows.push(["Téléphone", contact.phone]);252253  return (254    <Section id="details" eyebrow="À savoir" title="Détails pratiques">255      <div className="grid grid-cols-1 gap-5 lg:grid-cols-2">256        {facts.length > 0 && (257          <ul className="grid grid-cols-2 gap-x-6 gap-y-4 self-start">258            {facts.map(({ icon: Icon, k, v }) => (259              <li key={k} className="border-t border-line pt-2.5">260                <div className="flex items-center gap-1.5 text-[0.78rem] text-ink-3">261                  <Icon className="size-3.5" />262                  {k}263                </div>264                <div className="mt-0.5 text-[0.96rem] font-medium leading-snug text-ink">{v}</div>265              </li>266            ))}267          </ul>268        )}269        <div className="self-start rounded-xl border border-line bg-surface px-5 py-1.5">270          {rows.map(([k, v]) => (271            <KV key={k} k={k} v={v} />272          ))}273        </div>274      </div>275    </Section>276  );277}278
Files main
Menu

Theme