SPB Git

Repository Public

api.marche.ts 15.8 KB 465 lines typescript

1// Appels et types du domaine « marché » d'Immo-Ka : statistiques, taux2// hypothécaires, vrai prix, et la lecture tolérante d'une propriété pour les3// favoris et le comparateur. Tout fonctionne avec l'API v1 (lecture seule).4// Les données sont sales : chaque décodeur masque ce qui manque, rien n'est inventé.56async function get<T>(path: string): Promise<T> {7  const res = await fetch(path, { headers: { Accept: "application/json" } });8  if (!res.ok) throw new Error(`API ${res.status}`);9  return (await res.json()) as T;10}1112// --- Tableau de bord du marché (/api/stats/dashboard) -------------------------------13export interface Pt {14  t: string;15  v: number;16}17export interface Kpi {18  id: string;19  label: string;20  value: number;21  unit?: string;22  delta_pct?: number;23  direction?: "up" | "down" | "flat";24  spark?: Pt[];25}26export interface Serie {27  id: string;28  title: string;29  unit: string;30  kind: "line" | "bar" | "area" | string;31  points: Pt[];32  compare?: Pt[];33}34export interface BreakItem {35  label: string;36  value: number;37  delta_pct?: number;38}39export interface Breakdown {40  id: string;41  title: string;42  kind?: string;43  items: BreakItem[];44}45export interface Distribution {46  id: string;47  title: string;48  unit?: string;49  bins: { label: string; value: number }[];50}51export interface TableSpec {52  id: string;53  title: string;54  columns: string[];55  rows: (string | number | null)[][];56}57export interface MultiSerie {58  id: string;59  title: string;60  unit: string;61  series: { label: string; points: Pt[] }[];62}63export interface Gauge {64  id: string;65  label: string;66  value: number;67  max?: number;68  unit?: string;69}70export interface RecordFact {71  label: string;72  value: string;73  date?: string;74}75export interface DashPanel {76  id: string;77  title: string;78  subtitle?: string;79  kpis?: Kpi[];80  breakdowns?: Breakdown[];81  distributions?: Distribution[];82  tables?: TableSpec[];83}84export interface Dashboard {85  updated: string;86  period: { from: string; to: string; label: string; observed_from?: string };87  kpis: Kpi[];88  gauges?: Gauge[];89  series: Serie[];90  multiseries?: MultiSerie[];91  breakdowns: Breakdown[];92  distributions?: Distribution[];93  geo?: { title: string; items: BreakItem[] };94  tables: TableSpec[];95  records: RecordFact[];96  panels?: DashPanel[];97}9899/** Périodes acceptées par l'API. La collecte ayant commencé en août 2026, « 12m » couvre tout l'historique. */100export type Period = "7j" | "30j" | "3m" | "12m";101102export const fetchDashboard = (period: Period) => get<Dashboard>(`/api/stats/dashboard?period=${period}`);103104/** Rapport PDF du marché (généré par le serveur). */105export const reportUrl = (period: Period, mode: "complet" | "synthese" = "complet") => `/api/stats/report?period=${period}&mode=${mode}`;106107// --- Statistiques générales (/api/stats) ------------------------------------------------108export interface VpBanniere {109  banniere: string;110  n: number;111  median_delta_pct: number;112  p25: number;113  p75: number;114  pct_sur10: number;115  pct_juste: number;116  pct_sous5: number;117}118export interface Qualite {119  actives: number;120  publiees: number;121  quarantaine: number;122  completude_moyenne: number | null;123  anomalies: Record<string, number>;124}125export interface SiteStats {126  total: number;127  sources: number;128  cities: number;129  avg_price: number | null;130  vraiprix?: { ensemble: VpBanniere | null; bannieres: VpBanniere[] };131  qualite?: Qualite;132  recent_syncs?: { source: string; ts: number; ok: number }[];133}134export const fetchSiteStats = () => get<SiteStats>("/api/stats");135136// --- Rapport sur mesure (/api/stats/catalog, /api/stats/report/custom) ----------------137export interface CatalogBlock {138  key: string;139  section: string;140  title: string;141  renders: string[];142  default_render: string;143  count?: number;144}145export const fetchCatalog = (period: Period) => get<{ blocks: CatalogBlock[] }>(`/api/stats/catalog?period=${period}`);146147/** Compose un PDF à partir des blocs choisis et renvoie le fichier. */148export async function buildCustomReport(period: Period, title: string, blocks: { key: string; render: string }[]): Promise<Blob> {149  const res = await fetch("/api/stats/report/custom", {150    method: "POST",151    headers: { "Content-Type": "application/json" },152    body: JSON.stringify({ title, period, blocks }),153  });154  if (!res.ok) throw new Error(`API ${res.status}`);155  return await res.blob();156}157158// --- Taux hypothécaires (/api/mortgage/*) -------------------------------------------------159export type RateType = "fixed" | "variable";160export interface MortgageRate {161  provider: string;162  institution: string;163  product_name: string | null;164  rate_type: string;165  term_months: number;166  kind: "posted" | "special" | string;167  rate: number;168  apr: number | null;169  insured_status: "insured" | "insurable" | "uninsured" | "unknown" | string;170  conditions?: string | null;171  source_url: string | null;172  last_checked: number;173  age_minutes: number;174  stale: boolean;175}176export interface MortgageBest extends MortgageRate {177  median_rate: number | null;178  institutions_count: number;179  per_institution: MortgageRate[];180}181export interface MortgageMarket {182  rate_type: string;183  term_months: number;184  best: number;185  best_provider: string;186  best_institution: string;187  best_kind: string;188  median: number | null;189  spread: number | null;190  institutions_count: number;191  var_7d: number | null;192  var_30d: number | null;193  var_90d: number | null;194  lowest_6m: number | null;195}196export interface MortgageIntelligence {197  products: MortgageMarket[];198  prime_rates: { institution: string; rate: number; product_name: string; age_minutes: number }[];199}200export interface MortgageHistoryRow {201  provider: string;202  institution: string;203  product_name: string | null;204  kind: string;205  rate: number;206  insured_status: string;207  valid_from: number;208  valid_to: number | null;209  last_checked: number;210  source_url: string | null;211}212export interface MortgageProviderHealth {213  provider: string;214  institution: string;215  source_url: string | null;216  level: "OK" | "WARNING" | "ERROR" | string;217  age_minutes: number;218  current_products: number;219  last_data_at: number | null;220}221222export const fetchMortgageIntelligence = () => get<MortgageIntelligence>("/api/mortgage/intelligence");223export const fetchMortgageBest = (rateType: RateType, termMonths: number) =>224  get<MortgageBest>(`/api/mortgage/rates/best?rate_type=${rateType}&term_months=${termMonths}`);225export const fetchMortgageHistory = (rateType: RateType, termMonths: number, days = 365) =>226  get<{ count: number; days: number; history: MortgageHistoryRow[] }>(227    `/api/mortgage/rates/history?rate_type=${rateType}&term_months=${termMonths}&days=${days}`,228  );229export const fetchMortgageProviders = () => get<{ providers: MortgageProviderHealth[]; stale_hours_threshold?: number }>("/api/mortgage/providers");230231/** 4.19 → « 4,19 % » */232export const fmtRate = (r: number | null | undefined): string => (r == null ? "—" : `${r.toFixed(2).replace(".", ",")} %`);233234export const TERMS: { months: number; label: string }[] = [235  { months: 12, label: "1 an" },236  { months: 24, label: "2 ans" },237  { months: 36, label: "3 ans" },238  { months: 48, label: "4 ans" },239  { months: 60, label: "5 ans" },240  { months: 84, label: "7 ans" },241  { months: 120, label: "10 ans" },242];243export const termLabel = (m: number) => TERMS.find((t) => t.months === m)?.label ?? `${m} mois`;244245/** « il y a 3 h » à partir d'un âge en minutes. */246export const fmtAge = (min: number | null | undefined): string =>247  min == null ? "—" : min < 60 ? `il y a ${Math.max(1, Math.round(min))} min` : min < 48 * 60 ? `il y a ${Math.round(min / 60)} h` : `il y a ${Math.round(min / 1440)} j`;248249// --- Propriété (lecture tolérante de /api/listings/{uid}) -------------------------------250export interface VraiPrix {251  id?: string;252  value: number | null;253  low: number | null;254  high: number | null;255  /** lettre A à D, rarement fournie */256  confidence: string | null;257  confidence_pct: number | null;258  url?: string;259  valeur_role?: number;260  valeur_terrain?: number;261  valeur_batiment?: number;262  annee_construction_role?: number;263}264export interface Property {265  uid: string;266  source: string;267  url: string;268  title: string;269  address: string;270  sector: string;271  city: string;272  region: string;273  property_type: string;274  price: number | null;275  bedrooms: number | null;276  bathrooms: number | null;277  powder_rooms: number | null;278  area_sqft: number | null;279  lot_sqft: number | null;280  year_built: number | null;281  images: string[];282  details: Record<string, unknown>;283  vraiprix: VraiPrix | null;284  agency: string | null;285  days_on_market: number | null;286  active: number;287  price_history: { ts: number; price: number | null }[];288}289290const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);291const str = (v: unknown): string => (typeof v === "string" ? v : "");292293function decodeProperty(raw: Record<string, unknown>): Property {294  const vp = raw.vraiprix && typeof raw.vraiprix === "object" ? (raw.vraiprix as Record<string, unknown>) : null;295  return {296    uid: str(raw.uid),297    source: str(raw.source),298    url: str(raw.url),299    title: str(raw.title),300    address: str(raw.address),301    sector: str(raw.sector),302    city: str(raw.city),303    region: str(raw.region),304    property_type: str(raw.property_type),305    price: num(raw.price),306    bedrooms: num(raw.bedrooms),307    bathrooms: num(raw.bathrooms),308    powder_rooms: num(raw.powder_rooms),309    area_sqft: num(raw.area_sqft),310    lot_sqft: num(raw.lot_sqft),311    year_built: num(raw.year_built),312    images: Array.isArray(raw.images) ? raw.images.filter((u): u is string => typeof u === "string" && u.length > 0) : [],313    details: raw.details && typeof raw.details === "object" ? (raw.details as Record<string, unknown>) : {},314    vraiprix:315      vp && num(vp.value) != null316        ? {317            id: str(vp.id) || undefined,318            value: num(vp.value),319            low: num(vp.low),320            high: num(vp.high),321            confidence: str(vp.confidence) || null,322            confidence_pct: num(vp.confidence_pct),323            url: str(vp.url) || undefined,324            valeur_role: num(vp.valeur_role) ?? undefined,325            valeur_terrain: num(vp.valeur_terrain) ?? undefined,326            valeur_batiment: num(vp.valeur_batiment) ?? undefined,327            annee_construction_role: num(vp.annee_construction_role) ?? undefined,328          }329        : null,330    agency: str(raw.agency) || null,331    days_on_market: num(raw.days_on_market),332    active: raw.active === 0 ? 0 : 1,333    price_history: Array.isArray(raw.price_history) ? (raw.price_history as { ts: number; price: number | null }[]) : [],334  };335}336337export const fetchProperty = async (uid: string) => decodeProperty(await get<Record<string, unknown>>(`/api/listings/${encodeURIComponent(uid)}`));338339/** Clé de cache distincte de celle de la fiche (le décodage n'est pas le même). */340export const propertyKey = (uid: string) => ["propriete-marche", uid] as const;341342/** Un prix de vente plausible : les prix à 0 $ ou 1 $ sont des « prix sur demande » déguisés. */343export const priceOk = (p: number | null | undefined): p is number => p != null && p >= 1000;344345export const propertyPlace = (p: { sector?: string; city?: string }): string => {346  const city = (p.city || "").replace(/[()*]/g, "").trim();347  const sector = (p.sector || "").trim();348  return [sector && sector !== city ? sector : null, city].filter(Boolean).join(", ");349};350351/** Prix au pied carré habitable, quand la superficie est crédible. */352export const pricePerSqft = (p: Pick<Property, "price" | "area_sqft" | "lot_sqft">): number | null =>353  priceOk(p.price) && p.area_sqft != null && p.area_sqft >= 250 && p.area_sqft <= 20000 && p.area_sqft !== p.lot_sqft ? p.price / p.area_sqft : null;354355/** Lit un montant publié en texte (« 3,128 $ », « 1 655 $ (2026) »). */356function parseMoney(v: unknown): number | null {357  if (typeof v === "number") return Number.isFinite(v) && v > 0 ? v : null;358  if (typeof v !== "string") return null;359  const m = v.replace(/\(.*?\)/g, "").match(/\d[\d\s.,  ]*/);360  if (!m) return null;361  let s = m[0].replace(/[\s  ]/g, "");362  // « 3,128 » : virgule de milliers ; « 3128,50 » : virgule décimale363  s = /,\d{3}(\D|$)/.test(s) ? s.replace(/,/g, "") : s.replace(",", ".");364  const n = Number.parseFloat(s);365  return Number.isFinite(n) && n > 0 ? n : null;366}367368/** Taxes annuelles publiées par la source (municipales et scolaires), si elles existent. */369export function annualTaxes(p: Pick<Property, "details">): { municipal: number | null; school: number | null; total: number } | null {370  let municipal: number | null = null;371  let school: number | null = null;372  for (const [k, v] of Object.entries(p.details)) {373    const key = k.toLowerCase();374    if (!key.includes("taxe")) continue;375    const n = parseMoney(v);376    if (n == null || n > 200_000) continue;377    if (key.includes("scolaire")) school ??= n;378    else if (key.includes("municipal")) municipal ??= n;379  }380  if (municipal == null && school == null) return null;381  return { municipal, school, total: (municipal ?? 0) + (school ?? 0) };382}383384// --- Vrai prix : verdict -------------------------------------------------------------------385// Règle unique du backend v2 (voir `@/lib/verdict`).386export type { VerdictKey } from "./verdict";387import { deviationOf, estimateCoherent, verdictOfDeviation, VERDICT_BAND, DEVIATION_MAX, type VerdictKey } from "./verdict";388export const VP_SEUIL = VERDICT_BAND;389export const VP_HORS_COMPARAISON = DEVIATION_MAX;390391export function vraiPrixVerdict(price: number | null | undefined, estimate: number | null | undefined, low?: number | null, high?: number | null): { verdict: VerdictKey; deviation: number } | null {392  const deviation = deviationOf(price, estimate);393  if (deviation == null || !estimateCoherent(estimate!, low, high)) return null;394  return { verdict: verdictOfDeviation(deviation), deviation };395}396397// --- Bonnes occasions (/api/listings.geojson, champs allégés) -----------------------------398export interface DealPoint {399  uid: string;400  title: string | null;401  address: string;402  price: number;403  property_type: string;404  bedrooms: number | null;405  bathrooms: number | null;406  source: string;407  city: string;408  sector: string;409  image: string;410  vp: number;411  deviation: number;412}413414interface GeoFeature {415  properties: {416    uid: string;417    title: string | null;418    address: string | null;419    price: number | null;420    property_type: string | null;421    bedrooms: number | null;422    bathrooms: number | null;423    source: string;424    city: string | null;425    sector: string | null;426    image: string | null;427    vp: number | null;428  };429}430431/**432 * Propriétés d'une ville dont le prix demandé est de 8 % à 30 % sous leur433 * estimation. L'API v1 n'a pas de filtre « sous l'estimation » : on lit les434 * points allégés de la carte et on filtre ici. Les photos de plateformes dont435 * les liens expirent sont écartées.436 */437export async function fetchDeals(city: string, propertyType: string, priceMin: number, priceMax: number): Promise<DealPoint[]> {438  const qs = new URLSearchParams({ city, property_type: propertyType, price_min: String(priceMin), price_max: String(priceMax), limit: "500" });439  const data = await get<{ features: GeoFeature[] }>(`/api/listings.geojson?${qs}`);440  const out: DealPoint[] = [];441  for (const f of data.features ?? []) {442    const p = f.properties;443    if (!p?.uid || !priceOk(p.price) || !p.vp || !p.image || !p.address) continue;444    if (/fbcdn|kijiji|lespac/i.test(p.image) || /^(fb_|kijiji|lespac)/.test(p.source)) continue;445    const deviation = (p.price - p.vp) / p.vp;446    if (deviation > -0.08 || deviation < -0.3) continue;447    out.push({448      uid: p.uid,449      title: p.title,450      address: p.address,451      price: p.price,452      property_type: p.property_type ?? "",453      bedrooms: p.bedrooms,454      bathrooms: p.bathrooms,455      source: p.source,456      city: p.city ?? "",457      sector: p.sector ?? "",458      image: p.image,459      vp: p.vp,460      deviation,461    });462  }463  return out;464}465
Files main
Menu

Theme