SPB Git

Repository Public

ParcClient.tsx 17.3 KB 412 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Vrai-Prix8 * File             : src/app/parc/ParcClient.tsx9 * Module           : app10 * Repository       : https://git.spboucher.ai/vrai-prix11 * Created          : 2026-08-1312 * Last Modified    : 2026-08-2313 *14 * Author           : Simon-Pierre Boucher15 * Position         : Professor of Finance16 * Institution      : Université du Québec en Outaouais (UQO)17 * Organization     : SP Boucher18 * Website          : https://spboucher.ai19 * Git              : https://git.spboucher.ai20 *21 * Preferred Contact: contact@spboucher.ai22 * Development      : dev@spboucher.ai23 * Support          : support@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142"use client";43import { useEffect, useState } from "react";44import Link from "next/link";45import SearchBox, { type Suggestion } from "@/components/SearchBox";46import { CountUp, locNum, Sparkline, ValueSplit } from "@/components/MetricViz";47import { useLang } from "@/components/LangContext";48import FavButton from "@/components/FavButton";49import type { PortfolioResult } from "@/lib/estimator";50import type { TKey } from "@/lib/i18n";5152const KEY = "vp-parc";5354interface Saved {55  id: string;56  adresse: string;57  municipalite: string;58}5960const fmt = (v: number | null | undefined, lang: string) =>61  v == null62    ? "—"63    : new Intl.NumberFormat(lang === "fr" ? "fr-CA" : "en-CA", {64        style: "currency",65        currency: "CAD",66        maximumFractionDigits: 0,67      }).format(v);6869const CONF: Record<string, string> = {70  A: "pill-conf-A",71  B: "pill-conf-B",72  C: "pill-conf-C",73  D: "pill-conf-D",74};7576export default function ParcClient() {77  const { lang, t } = useLang();78  const fr = lang === "fr";79  const [list, setList] = useState<Saved[]>([]);80  const [data, setData] = useState<PortfolioResult | null>(null);81  const [loading, setLoading] = useState(false);82  const [hydrated, setHydrated] = useState(false);8384  useEffect(() => {85    const id = setTimeout(() => {86      try {87        const raw = window.localStorage.getItem(KEY);88        if (raw) setList(JSON.parse(raw) as Saved[]);89      } catch {}90      setHydrated(true);91    }, 0);92    return () => clearTimeout(id);93  }, []);9495  const persist = (l: Saved[]) => {96    setList(l);97    window.localStorage.setItem(KEY, JSON.stringify(l));98    setData(null);99  };100101  const add = (s: Suggestion) => {102    if (list.some((x) => x.id === s.id) || list.length >= 40) return;103    persist([104      ...list,105      {106        id: s.id,107        adresse: `${s.adresse ?? ""}${s.apt ? ` app. ${s.apt}` : ""}`,108        municipalite: s.municipalite ?? "",109      },110    ]);111  };112113  const evaluate = async () => {114    setLoading(true);115    try {116      const res = await fetch("/api/portfolio", {117        method: "POST",118        headers: { "Content-Type": "application/json" },119        body: JSON.stringify({ ids: list.map((x) => x.id) }),120      });121      if (res.ok) setData((await res.json()) as PortfolioResult);122    } finally {123      setLoading(false);124    }125  };126127  const a = data?.aggregates;128129  return (130    <div className="pb-6 pt-10 sm:pt-14">131      {/* héros */}132      <section>133        <span className="kicker">{fr ? "Investisseurs · propriétaires multiples" : "Investors · multi-owners"}</span>134        <h1 className="vp-display mt-3 max-w-4xl text-[clamp(30px,5.6vw,62px)] font-bold uppercase leading-[0.98] tracking-[-0.035em]">135          {fr ? (136            <>137              La valeur de votre <span className="hl">parc immobilier</span>,138              <br />139              <span className="outline-txt">au complet.</span>140            </>141          ) : (142            <>143              Your <span className="hl">property portfolio</span>,144              <br />145              <span className="outline-txt">fully valued.</span>146            </>147          )}148        </h1>149        <p className="mt-4 max-w-xl text-[16px] text-ink-2">150          {fr151            ? "Ajoutez chacune de vos adresses. Vrai-Prix évalue chaque propriété, agrège votre parc — valeur totale, fourchette, croissance 2021→2026 — et produit un rapport PDF consolidé."152            : "Add each of your addresses. Vrai-Prix values every property, aggregates your portfolio — total value, range, 2021→2026 growth — and produces a consolidated PDF report."}153        </p>154      </section>155156      {/* constructeur de parc */}157      <section className="mt-9">158        <div className="vp-card p-4 sm:p-5">159          <p className="klabel mb-2 pl-0.5">160            {fr ? `Ajouter une propriété (${list.length}/40)` : `Add a property (${list.length}/40)`}161          </p>162          <SearchBox163            onPick={add}164            placeholder={fr ? "Tapez une adresse puis choisissez-la…" : "Type an address, then pick it…"}165          />166          {hydrated && list.length > 0 && (167            <div className="mt-4 flex flex-wrap gap-2">168              {list.map((p, i) => (169                <span170                  key={p.id}171                  className="stat-chip !py-1.5"172                  style={{ animationDelay: `${i * 40}ms` }}173                >174                  <b>{i + 1}</b> {p.adresse} · {p.municipalite}175                  <button176                    aria-label={fr ? "Retirer" : "Remove"}177                    onClick={() => persist(list.filter((x) => x.id !== p.id))}178                    className="vp-mono ml-1 cursor-pointer rounded-full border-[1.5px] border-ink px-1.5 text-[10px] font-bold hover:bg-ink hover:text-lime"179                  >180                    ✕181                  </button>182                </span>183              ))}184            </div>185          )}186          <div className="mt-4 flex flex-wrap gap-2.5">187            <button188              className="btn btn-primary"189              disabled={list.length === 0 || loading}190              onClick={evaluate}191            >192              {loading193                ? fr ? "Évaluation en cours…" : "Valuing…"194                : fr ? `Évaluer mon parc (${list.length})` : `Value my portfolio (${list.length})`}195            </button>196            {list.length > 0 && (197              <button className="btn btn-ghost" onClick={() => persist([])}>198                {fr ? "Vider la liste" : "Clear list"}199              </button>200            )}201          </div>202        </div>203      </section>204205      {/* résultats */}206      {data && a && (207        <div className="mt-12 space-y-10">208          {/* total */}209          <section className="vp-card p-6 sm:p-8">210            <span className="kicker">{fr ? "Valeur totale estimée du parc" : "Total estimated portfolio value"}</span>211            <p className="vp-display mt-3 text-[clamp(40px,7vw,68px)] font-bold leading-none tracking-[-0.04em]">212              <CountUp213                value={a.totalEstimate}214                format={(v) =>215                  new Intl.NumberFormat(fr ? "fr-CA" : "en-CA", {216                    style: "currency",217                    currency: "CAD",218                    maximumFractionDigits: 0,219                  }).format(Math.round(v / 100) * 100)220                }221              />222            </p>223            <div className="mt-5 flex flex-wrap items-center gap-x-6 gap-y-3">224              <div>225                <p className="klabel">{fr ? "Fourchette cumulée" : "Cumulative range"}</p>226                <p className="vp-display text-[18px] font-bold">227                  {fmt(a.totalLow, lang)} <span className="text-ink-3">→</span> {fmt(a.totalHigh, lang)}228                </p>229              </div>230              <div>231                <p className="klabel">{fr ? "Confiance pondérée" : "Weighted confidence"}</p>232                <span className={`pill ${CONF[a.confidenceLevel]}`}>233                  {a.confidenceLevel} · {a.confidencePct} %234                </span>235              </div>236              <div>237                <p className="klabel">{fr ? "Évaluation municipale" : "Municipal assessment"}</p>238                <p className="vp-display text-[18px] font-bold text-ink-2">{fmt(a.totalRole, lang)}</p>239              </div>240            </div>241            <a242              href={`/api/report/portfolio?ids=${data.items.map((i) => i.unit!.id).join(",")}`}243              className="btn btn-primary mt-6"244              download245            >246              {fr247                ? `Télécharger le rapport de parc (${1 + data.items.length} pages PDF)`248                : `Download the portfolio report (${1 + data.items.length} PDF pages)`}{" "}249              ↓250            </a>251          </section>252253          {/* tuiles registre */}254          <section>255            <span className="kicker">{fr ? "Votre parc, en chiffres du registre" : "Your portfolio, in registry numbers"}</span>256            <div className="mt-4 grid grid-cols-2 gap-3.5 sm:grid-cols-4">257              {(258                [259                  [fr ? "Propriétés" : "Properties", String(a.count), true],260                  [fr ? "Écart vs rôle" : "vs assessment", a.ecartRolePct != null ? `${a.ecartRolePct >= 0 ? "+" : ""}${a.ecartRolePct.toFixed(0)} %` : "—", false],261                  [fr ? "Croissance 2021→2026" : "Growth 2021→2026", a.growthPct != null ? `${a.growthPct >= 0 ? "+" : ""}${a.growthPct.toFixed(0)} %` : "—", true],262                  [fr ? "Logements" : "Dwellings", String(a.totalDwellings), false],263                  [fr ? "Aire habitable" : "Living area", `${a.totalFloorArea.toLocaleString(fr ? "fr-CA" : "en-CA")} m²`, false],264                  [fr ? "Terrain total" : "Total land", `${a.totalLandArea.toLocaleString(fr ? "fr-CA" : "en-CA")} m²`, false],265                  [fr ? "Année moyenne" : "Avg. year built", a.avgYearBuilt ? String(a.avgYearBuilt) : "—", false],266                  [fr ? "Municipalités" : "Municipalities", String(a.municipalities.length), false],267                ] as [string, string, boolean][]268              ).map(([k, v, hero]) => (269                <div270                  key={k}271                  className={`vp-card vp-card-hover p-4 ${hero ? "!bg-ink" : ""}`}272                >273                  <p className={`vp-display text-[clamp(20px,2.6vw,28px)] font-bold leading-tight tracking-[-0.03em] ${hero ? "text-lime" : "text-ink"}`}>274                    {v}275                  </p>276                  <p className={`vp-mono mt-1.5 text-[10px] font-bold uppercase tracking-[0.1em] ${hero ? "text-[rgba(255,81,72,0.7)]" : "text-ink-3"}`}>277                    {k}278                  </p>279                </div>280              ))}281            </div>282          </section>283284          {/* historique du parc + répartitions */}285          <section className="grid gap-4 lg:grid-cols-[1.4fr_1fr]">286            <div className="vp-card p-5 sm:p-6">287              <p className="klabel mb-3">{fr ? "Valeur du parc par année" : "Portfolio value by year"}</p>288              <div className="flex flex-col gap-2">289                {a.history.map((h) => {290                  const max = Math.max(...a.history.map((x) => x.total), 1);291                  return (292                    <div key={h.year} className="hbar-row grid grid-cols-[46px_1fr_auto] items-center gap-3">293                      <span className="vp-mono text-[12px] font-bold">{h.year}</span>294                      <span className="hbar-track !h-[22px]">295                        <span296                          className="hbar-fill !rounded-r-[6px]"297                          style={{ width: `${(h.total / max) * 100}%`, background: h.year === 2026 ? "var(--ink)" : undefined }}298                        />299                      </span>300                      <span className="vp-mono text-[12px] font-bold">301                        {fmt(h.total, lang)}302                        {h.nCovered < a.count && (303                          <span className="text-ink-3"> ({h.nCovered}/{a.count})</span>304                        )}305                      </span>306                    </div>307                  );308                })}309              </div>310            </div>311            <div className="vp-card p-5 sm:p-6">312              <p className="klabel mb-3">{fr ? "Répartition" : "Breakdown"}</p>313              <div className="space-y-2">314                {a.municipalities.slice(0, 4).map((m) => (315                  <div key={m.name} className="flex items-baseline justify-between gap-3 border-b border-dashed border-[rgba(20,24,20,0.14)] pb-1.5">316                    <span className="vp-display text-[14px] font-bold">{m.name}</span>317                    <span className="vp-mono text-[11px] text-ink-2">318                      {m.count} · {fmt(m.total, lang)}319                    </span>320                  </div>321                ))}322                {a.types.map((tp) => (323                  <div key={tp.type} className="flex items-baseline justify-between gap-3 border-b border-dashed border-[rgba(20,24,20,0.14)] pb-1.5 last:border-0">324                    <span className="text-[13px] font-semibold text-ink-2">{t(tp.type as TKey)}</span>325                    <span className="vp-mono text-[11px] text-ink-2">326                      {tp.count} · {fmt(tp.total, lang)}327                    </span>328                  </div>329                ))}330              </div>331            </div>332          </section>333334          {/* cartes propriétés */}335          <section>336            <span className="kicker">{fr ? "Chaque propriété du parc" : "Every property in the portfolio"}</span>337            <div className="mt-4 grid gap-4 sm:grid-cols-2">338              {data.items.map((it, i) => {339                const u = it.unit!;340                const r = it.result;341                return (342                  <Link343                    key={u.id}344                    href={`/estimation/${u.id}`}345                    className="vp-card vp-card-hover rise block p-5"346                    style={{ animationDelay: `${i * 70}ms` }}347                  >348                    <div className="flex items-start justify-between gap-3">349                      <div>350                        <p className="vp-mono text-[10px] font-bold text-green">351                          {String(i + 1).padStart(2, "0")}352                        </p>353                        <p className="vp-display mt-0.5 text-[16px] font-bold uppercase leading-tight">354                          {u.adresse}355                        </p>356                        <p className="vp-mono mt-0.5 text-[10.5px] uppercase tracking-[0.05em] text-ink-3">357                          {u.municipalite} · {u.anneeConstruction ?? "—"} ·{" "}358                          {u.aireEtagesM2 ? locNum(u.aireEtagesM2, lang, { unit: "m²" }) : "—"}359                        </p>360                      </div>361                      <span className="flex shrink-0 items-center gap-2">362                        {/* ♥ favori local (src/lib/store) */}363                        <FavButton364                          item={{365                            item_id: u.id,366                            title: u.adresse ?? u.id,367                            subtitle: u.municipalite ?? "",368                            price_label: fmt(r.estimate, lang),369                            url: `https://www.vrai-prix.com/estimation/${encodeURIComponent(u.id)}`,370                          }}371                        />372                        <span className={`pill ${CONF[r.confidenceLevel]}`}>373                          {r.confidenceLevel}374                        </span>375                      </span>376                    </div>377                    <div className="mt-3 flex items-end justify-between gap-3 border-t-[1.5px] border-dashed border-[rgba(20,24,20,0.14)] pt-3">378                      <div>379                        <p className="vp-display text-[22px] font-bold tracking-[-0.02em]">380                          {fmt(r.estimate, lang)}381                        </p>382                        <p className="vp-mono text-[10.5px] text-ink-3">383                          {fr ? "rôle" : "roll"} {fmt(u.valeurRole, lang)}384                        </p>385                      </div>386                      <Sparkline history={u.history} />387                    </div>388                    <div className="mt-3">389                      <ValueSplit390                        land={u.specs.valeurTerrain}391                        building={u.specs.valeurBatiment}392                        previous={null}393                        total={u.valeurRole}394                        lang={lang}395                        labels={{396                          land: fr ? "Terrain" : "Land",397                          building: fr ? "Bâtiment" : "Building",398                          previous: "",399                        }}400                      />401                    </div>402                  </Link>403                );404              })}405            </div>406          </section>407        </div>408      )}409    </div>410  );411}412
Files main
Menu

Theme