Repository Public
1// UQO Éval — export universel (PDF, XLSX, CSV, JSON) de tout élément généré par la plateforme, toujours avec la mention UQO Éval.2/**3 * GET /api/export?kind=estimate|portfolio|cost|stats|prov|marche|municipalite&format=pdf|xlsx|csv|json&lang=fr|en4 * + id= (estimate, cost) · ids=a,b,c (portfolio) · slug= (municipalite)5 * → le serveur recalcule/relit l'élément puis le sérialise.6 * POST /api/export?format=… — corps JSON { kind, title, subtitle?, lang?, result }7 * → export d'un résultat déjà calculé côté client (laboratoire hédonique, atelier de comparables, coût non enregistré…).8 */9import { NextRequest, NextResponse } from "next/server";10import { exportResult, slug } from "@/lib/export-generic";11import { clientKey, rateLimit } from "@/lib/cost/cache";1213export const runtime = "nodejs";14export const maxDuration = 60;1516type Fmt = "pdf" | "xlsx" | "csv" | "json";17const fmtOf = (s: string | null): Fmt => (s === "pdf" || s === "xlsx" || s === "csv" || s === "json" ? s : "xlsx");18const langOf = (s: unknown): "fr" | "en" => (s === "en" ? "en" : "fr");19const bad = (msg: string, status = 400) => NextResponse.json({ error: msg }, { status });2021/** Noms des exclusions par type : objets volumineux non tabulaires (nuages de points, code source, images). */22const SKIP: Record<string, string[]> = { hedonique: ["plots", "code", "lab"], estimate: ["history"], portfolio: [], cost: [], stats: [], prov: [], marche: [], municipalite: [], avendre: [] };2324async function respond(result: unknown, format: Fmt, meta: { title: string; subtitle?: string | null; source: string; lang: "fr" | "en" }, skip: string[]) {25 let r: Awaited<ReturnType<typeof exportResult>>;26 try { r = await exportResult(result, format, meta, { skip }); }27 catch (e) { console.error("[export]", meta.title, format, e); return NextResponse.json({ error: `export ${format} impossible : ${(e as Error).message}` }, { status: 500 }); }28 const name = `uqo-eval_${slug(meta.title)}_${new Date().toISOString().slice(0, 10)}.${r.ext}`;29 return new NextResponse(new Uint8Array(r.body), { headers: { "Content-Type": r.mime, "Content-Disposition": `attachment; filename="${name}"`, "Cache-Control": "private, no-store", "X-UQO-Eval": "export" } });30}3132export async function GET(req: NextRequest) {33 if (!rateLimit(`export:${clientKey(req)}`, 120, 60_000)) return bad("Trop de requêtes — réessayez dans une minute.", 429);34 const q = req.nextUrl.searchParams; const kind = q.get("kind") ?? ""; const format = fmtOf(q.get("format")); const lang = langOf(q.get("lang")); const fr = lang === "fr";35 const src = `https://www.uqo-eval.app${req.nextUrl.pathname}?${q.toString()}`;36 switch (kind) {37 case "estimate": {38 const id = q.get("id"); if (!id) return bad("id requis");39 const { estimateByUnitId } = await import("@/lib/estimator"); const r = estimateByUnitId(id); if (!r || !r.unit) return bad("unité introuvable", 404);40 const u = r.unit; const { history, specs, ...unit } = u;41 const result = { unit: { ...unit, specs }, result: { ...r.result, comps: undefined }, comparables: r.result.comps, historique_role: history, context: r.context ?? null };42 return respond(result, format, { title: `${fr ? "Estimation" : "Estimate"} — ${u.adresse ?? u.id}`, subtitle: `${u.municipalite ?? ""} · ${u.typeProp}`, source: src, lang }, SKIP.estimate);43 }44 case "portfolio": {45 const ids = (q.get("ids") ?? "").split(",").map((s) => s.trim()).filter(Boolean).slice(0, 40); if (!ids.length) return bad("ids requis");46 const { estimatePortfolio } = await import("@/lib/estimator"); const r = estimatePortfolio(ids); if (!r.items.length) return bad("aucune propriété trouvée", 404);47 const items = r.items.map((i) => { const u = i.unit!; return { id: u.id, adresse: u.adresse, municipalite: u.municipalite, typeProp: u.typeProp, anneeConstruction: u.anneeConstruction, aireEtagesM2: u.aireEtagesM2, superficieTerrainM2: u.superficieTerrainM2, nbLogements: u.nbLogements, valeurRole: u.valeurRole, estimate: i.result.estimate, low: i.result.low, high: i.result.high, confidenceLevel: i.result.confidenceLevel, confidencePct: i.result.confidencePct, modelEstimate: i.result.modelEstimate, compsEstimate: i.result.compsEstimate, nCompsUsed: i.result.nCompsUsed }; });48 const comparables = r.items.flatMap((i) => i.result.comps.map((c) => ({ unitId: i.unit!.id, ...c })));49 return respond({ aggregates: r.aggregates, items, comparables }, format, { title: fr ? `Parc immobilier — ${items.length} propriétés` : `Portfolio — ${items.length} properties`, source: src, lang }, SKIP.portfolio);50 }51 case "cost": {52 const id = q.get("id") ?? ""; if (!/^[0-9a-f-]{36}$/.test(id)) return bad("id invalide");53 const { getEstimate } = await import("@/lib/cost/estimate"); const est = getEstimate(id); if (!est) return bad("estimation introuvable", 404);54 return respond(est, format, { title: fr ? "Méthode du coût — estimation" : "Cost approach — estimate", subtitle: `${est.id} · ${est.priceDate}`, source: src, lang }, SKIP.cost);55 }56 case "stats": {57 const { getDashboard } = await import("@/lib/stats-dashboard");58 return respond(getDashboard(), format, { title: fr ? "Statistiques provinciales — tableau de bord" : "Provincial statistics — dashboard", subtitle: fr ? "instantané du rôle 2026 · corpus de ventes 2021-2026" : "2026 roll snapshot · 2021-2026 sales corpus", source: src, lang }, SKIP.stats);59 }60 case "prov": {61 const stats = (await import("@/data/stats.json")).default;62 return respond(stats, format, { title: fr ? "La valeur de l'immobilier québécois" : "The value of Québec real estate", source: src, lang }, SKIP.prov);63 }64 case "marche": {65 const marche = (await import("@/data/marche-stats.json")).default;66 return respond(marche, format, { title: fr ? "La mesure à l'épreuve du marché" : "The measure vs. the market", subtitle: fr ? "estimations UQO Éval vs prix demandés" : "UQO Éval estimates vs asking prices", source: src, lang }, SKIP.marche);67 }68 case "municipalite": {69 const s = q.get("slug") ?? ""; const m = await import("@/lib/municipalites"); const mun = m.munBySlug(s); if (!mun) return bad("municipalité introuvable", 404);70 const st = m.munStats(mun.nom); if (!st) return bad("aucune donnée", 404);71 return respond({ municipalite: mun, statistiques: st }, format, { title: `${fr ? "L'immobilier à" : "Real estate in"} ${mun.nom}`, source: src, lang }, SKIP.municipalite);72 }73 default: return bad("kind : estimate | portfolio | cost | stats | prov | marche | municipalite");74 }75}7677export async function POST(req: NextRequest) {78 if (!rateLimit(`export:${clientKey(req)}`, 120, 60_000)) return bad("Trop de requêtes — réessayez dans une minute.", 429);79 const len = Number(req.headers.get("content-length") ?? 0); if (len > 12 * 1024 * 1024) return bad("corps trop volumineux (12 Mo max)", 413);80 let b: { kind?: string; title?: string; subtitle?: string | null; lang?: string; result?: unknown; skip?: unknown };81 try { b = await req.json(); } catch { return bad("JSON invalide"); }82 if (b.result === undefined) return bad("result requis");83 const format = fmtOf(req.nextUrl.searchParams.get("format") ?? null); const lang = langOf(b.lang ?? req.nextUrl.searchParams.get("lang"));84 const kind = typeof b.kind === "string" ? b.kind.slice(0, 40) : "resultat";85 const title = (typeof b.title === "string" && b.title.trim() ? b.title : kind).slice(0, 160);86 const skip = [...(SKIP[kind] ?? []), ...(Array.isArray(b.skip) ? b.skip.filter((x): x is string => typeof x === "string") : [])];87 return respond(b.result, format, { title, subtitle: typeof b.subtitle === "string" ? b.subtitle.slice(0, 240) : null, source: `https://www.uqo-eval.app/${kind}`, lang }, skip);88}89