Repository Public
1# -----------------------------------------------------------------------------2# Fabri-Ka v2 — pages rendues par le serveur (référencement) et sitemaps3# Auteur : Simon-Pierre Boucher — contact@spboucher.ai4# seo.py : chaque adresse publique rend un HTML complet (titre, description,5# canonique, Open Graph, JSON-LD, contenu d'indexation dans #root) et porte6# l'AMORÇAGE des données de la page : window.__FABRIKA__ = {…}, identique à7# la réponse de l'API. Les adresses de la v1 restent valides :8# /produits/{slug}-{uid} /boutiques/{id} /categorie/{slug}9# /categorie/{slug}/region/{region} /region/{slug}10# Quand frontend/dist/index.html existe, il sert de gabarit ; sinon un gabarit11# neutre minimal est utilisé.12# -----------------------------------------------------------------------------13from __future__ import annotations1415import html as _html16import json17import os18import re19import time20from pathlib import Path21from urllib.parse import quote, urlencode2223from fastapi import FastAPI, Request24from fastapi.responses import FileResponse, HTMLResponse, PlainTextResponse, RedirectResponse, Response25from fastapi.staticfiles import StaticFiles2627from . import categories as cats28from . import public, recherche, texte29from .public import catalogue3031ROOT = Path(__file__).resolve().parent.parent32FRONT_DIST = Path(os.environ.get("FABRIKA_FRONT_DIST") or ROOT / "frontend" / "dist")33BASE = os.environ.get("FABRIKA_BASE_URL", "https://www.fabri-ka.com").rstrip("/")34NOINDEX = os.environ.get("FABRIKA_NOINDEX", "").strip() not in ("", "0", "false")35SITE = "Fabri-Ka"36CONTACT = "contact@spboucher.ai"37SITEMAP_CHUNK = 40_00038PER_PAGE = 243940_GABARIT = """<!doctype html><html lang="fr-CA"><head><meta charset="UTF-8">41<meta name="viewport" content="width=device-width, initial-scale=1.0">42<meta name="description" content=""><title>Fabri-Ka</title></head>43<body><div id="root"></div></body></html>"""44_tpl = {"mtime": None, "text": _GABARIT}454647def gabarit() -> str:48 p = FRONT_DIST / "index.html"49 try:50 m = p.stat().st_mtime51 except OSError:52 return _GABARIT53 if m != _tpl["mtime"]:54 _tpl.update(mtime=m, text=p.read_text(encoding="utf-8"))55 return _tpl["text"]565758def esc(s) -> str:59 return _html.escape("" if s is None else str(s), quote=True)606162def prix(v) -> str:63 if v is None:64 return ""65 s = f"{v:,.2f}".replace(",", " ").replace(".", ",")66 return (s[:-3] if s.endswith(",00") else s) + " $"676869def entier(n) -> str:70 return f"{int(n):,}".replace(",", " ")717273def iso(ts) -> str | None:74 try:75 return time.strftime("%Y-%m-%d", time.gmtime(float(ts)))76 except (TypeError, ValueError):77 return None787980def rendre(*, title: str, description: str, canonical: str | None = None, body: str = "",81 jsonld: list[dict] | None = None, image: str | None = None, robots: str | None = None,82 status: int = 200, ctx: dict | None = None, og_type: str = "website") -> HTMLResponse:83 tpl = gabarit()84 description = texte.resume(description, 300)85 tpl = re.sub(r"<title>[^<]*</title>", lambda m: f"<title>{esc(title)}</title>", tpl, count=1)86 tpl = re.sub(r'<meta[^>]*name="description"[^>]*>',87 lambda m: f'<meta name="description" content="{esc(description)}">', tpl, count=1)88 tpl = re.sub(r'\s*<meta (?:property="og:|name="twitter:|name="robots")[^>]*/?>', "", tpl)89 tpl = re.sub(r'\s*<link rel="canonical"[^>]*/?>', "", tpl)90 extra: list[str] = []91 if NOINDEX:92 robots = "noindex, nofollow"93 if robots:94 extra.append(f'<meta name="robots" content="{esc(robots)}">')95 if canonical:96 url = BASE + canonical97 extra.append(f'<link rel="canonical" href="{esc(url)}">')98 extra.append(f'<link rel="alternate" hreflang="fr-CA" href="{esc(url)}">')99 og = {"og:site_name": SITE, "og:locale": "fr_CA", "og:type": og_type, "og:title": title,100 "og:description": description, "og:url": (BASE + canonical) if canonical else None,101 "og:image": image}102 for k, v in og.items():103 if v:104 extra.append(f'<meta property="{esc(k)}" content="{esc(v)}">')105 extra.append(f'<meta name="twitter:card" content="{"summary_large_image" if image else "summary"}">')106 for obj in jsonld or []:107 extra.append('<script type="application/ld+json">'108 + json.dumps(obj, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")109 + "</script>")110 # amorçage : JSON sur une ligne, « </ » échappé111 amorce = json.dumps(ctx or {}, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")112 extra.append(f"<script>window.__FABRIKA__={amorce}</script>")113 tpl = tpl.replace("</head>", "\n".join(extra) + "\n</head>", 1)114 tpl = tpl.replace('<div id="root"></div>', f'<div id="root">{body}</div>', 1)115 return HTMLResponse(tpl, status_code=status,116 headers={"Cache-Control": "public, max-age=120" if status == 200 else "no-store"})117118119# -- briques HTML d'indexation -----------------------------------------------------120def fil(items: list[tuple[str, str]]) -> tuple[str, dict]:121 h = '<nav aria-label="Fil d\'Ariane"><ol>' + "".join(122 f'<li><a href="{esc(u)}">{esc(n)}</a></li>' for n, u in items) + "</ol></nav>"123 ld = {"@context": "https://schema.org", "@type": "BreadcrumbList",124 "itemListElement": [{"@type": "ListItem", "position": i + 1, "name": n, "item": BASE + u}125 for i, (n, u) in enumerate(items)]}126 return h, ld127128129def li_produit(c: dict) -> str:130 lieu = " · ".join(x for x in (c.get("store_name"), c.get("city") or c.get("region")) if x)131 return (f'<li><a href="{esc(c["path"])}"><img src="{esc(c["img"])}" alt="{esc(c["title"])}" '132 f'loading="lazy" width="320" height="320"><h3>{esc(c["title"])}</h3></a>'133 f'<p>{esc(prix(c["price"]))} · {esc(lieu)}</p></li>')134135136def grille(cs: list[dict]) -> str:137 return '<ul class="produits">' + "".join(li_produit(c) for c in cs) + "</ul>" if cs else ""138139140def li_boutique(b: dict) -> str:141 lieu = ", ".join(x for x in (b.get("city"), b.get("region")) if x)142 return (f'<li><a href="{esc(b["path"])}"><h3>{esc(b["name"])}</h3></a>'143 f'<p>{esc(lieu)}{" · " if lieu else ""}{entier(b["n"])} produits · {esc(b["category_label"])}</p></li>')144145146def pagination(chemin: str, params: dict, page: int, pages: int) -> str:147 if pages <= 1:148 return ""149 def lien(p):150 q = {k: v for k, v in params.items() if v not in (None, "")}151 if p > 1:152 q["page"] = p153 return chemin + ("?" + urlencode(q) if q else "")154 h = '<nav aria-label="Pages">'155 if page > 1:156 h += f'<a rel="prev" href="{esc(lien(page - 1))}">Page précédente</a> '157 h += f"<span>Page {page} de {entier(pages)}</span>"158 if page < pages:159 h += f' <a rel="next" href="{esc(lien(page + 1))}">Page suivante</a>'160 return h + "</nav>"161162163def page_404(msg: str = "Cette page n'existe pas.") -> HTMLResponse:164 body = (f'<main><h1>Page introuvable</h1><p>{esc(msg)}</p>'165 '<p><a href="/">Accueil</a> · <a href="/produits">Produits</a> · '166 '<a href="/boutiques">Boutiques</a></p></main>')167 return rendre(title=f"Page introuvable — {SITE}", description=msg, body=body,168 robots="noindex, follow", status=404, ctx={"page": "404"})169170171def page_retiree(msg: str) -> HTMLResponse:172 body = f'<main><h1>Page retirée</h1><p>{esc(msg)}</p><p><a href="/">Accueil</a></p></main>'173 return rendre(title=f"Page retirée — {SITE}", description=msg, body=body,174 robots="noindex, follow", status=410, ctx={"page": "gone"})175176177# -- pages ----------------------------------------------------------------------------178def page_accueil() -> HTMLResponse:179 from . import web180 cat = catalogue()181 d = web.decouverte(cat)182 t = d["totals"]183 desc = (f"{entier(t['products'])} produits de {entier(t['stores'])} boutiques en ligne du Québec, "184 f"dans {t['regions']} régions. Fabri-Ka ne vend rien : chaque produit mène à la boutique "185 "qui le fabrique ou le vend.")186 body = (f'<main><h1>Le répertoire des produits et des boutiques du Québec</h1><p>{esc(desc)}</p>'187 '<form action="/produits" method="get" role="search"><label>Chercher un produit, une '188 'boutique, une ville <input type="search" name="q"></label><button>Chercher</button></form>'189 '<section><h2>Catégories</h2><ul>'190 + "".join(f'<li><a href="{esc(c["path"])}">{esc(c["label"])}</a> ({entier(c["n"])})</li>'191 for c in d["categories"])192 + '</ul></section><section><h2>Régions</h2><ul>'193 + "".join(f'<li><a href="{esc(r["path"])}">{esc(r["name"])}</a> ({entier(r["stores"])} boutiques)</li>'194 for r in d["regions"] if r["stores"])195 + '</ul></section><section><h2>Nouveautés de la semaine</h2>'196 + grille(d["new_this_week"]["products"][:12])197 + '</section><section><h2>Boutiques récemment ajoutées</h2><ul>'198 + "".join(li_boutique(b) for b in d["new_stores"]) + "</ul></section></main>")199 ld = [{"@context": "https://schema.org", "@type": "WebSite", "name": SITE, "url": BASE + "/",200 "inLanguage": "fr-CA",201 "potentialAction": {"@type": "SearchAction", "target": BASE + "/produits?q={search_term_string}",202 "query-input": "required name=search_term_string"}},203 {"@context": "https://schema.org", "@type": "Organization", "name": SITE, "url": BASE + "/",204 "email": CONTACT}]205 return rendre(title=f"{SITE} — produits et boutiques du Québec", description=desc, canonical="/",206 body=body, jsonld=ld, ctx={"page": "home", "discover": d})207208209_PARAMS_LISTE = recherche.PARAMS + ("sort", "diversity")210211212def page_liste(params, *, fixe: dict, chemin: str, titre: str, intro: str, fil_items: list,213 page_ctx: dict, extra_html: str = "") -> HTMLResponse:214 """Liste de produits (recherche, catégorie, région…) rendue par le serveur."""215 from . import web216 cat = catalogue()217 qp = {k: params.get(k) for k in _PARAMS_LISTE if params.get(k) not in (None, "")}218 libres = {k: v for k, v in qp.items() if k not in fixe}219 p = {**{k: qp.get(k) for k in recherche.PARAMS}, **fixe}220 try:221 page = max(1, int(params.get("page") or 1))222 except ValueError:223 page = 1224 try:225 res = web.reponse_recherche(cat, p, qp.get("sort") or "", page, PER_PAGE, None, False, True)226 except recherche.Erreur as exc:227 return page_404(str(exc))228 if page > res["pages"]:229 return page_404("Cette page de résultats n'existe pas.")230 fh, fld = fil(fil_items)231 n = res["total"]232 desc = intro.format(n=entier(n), b=entier(res["stores_total"]))233 body = (f"<main>{fh}<h1>{esc(titre)}</h1><p>{esc(desc)}</p>{extra_html}"234 + grille(res["products"]) + pagination(chemin, libres, page, res["pages"]) + "</main>")235 ld = [fld, {"@context": "https://schema.org", "@type": "ItemList", "numberOfItems": n,236 "itemListElement": [{"@type": "ListItem", "position": (page - 1) * PER_PAGE + i + 1,237 "url": BASE + c["path"], "name": c["title"]}238 for i, c in enumerate(res["products"])]}]239 canon = chemin + (f"?page={page}" if page > 1 else "")240 return rendre(title=f"{titre}{f' — page {page}' if page > 1 else ''} — {SITE}", description=desc,241 canonical=canon, body=body, jsonld=ld,242 image=res["products"][0]["img"] if res["products"] else None,243 robots="noindex, follow" if (libres or n == 0) else None,244 ctx={**page_ctx, "results": res})245246247def page_produit(slug: str | None, uid: str) -> Response:248 from . import web249 cat = catalogue()250 v = web._memo(cat, "fiche", uid, lambda: web.fiche(uid) or False)251 if not v:252 code, corps = web.etat_produit(uid)253 if corps.get("canonical_path"):254 return RedirectResponse(corps["canonical_path"], status_code=301)255 if code == 410:256 sid = corps.get("store_id")257 body = ('<main><h1>Ce produit n\'est plus offert</h1><p>La boutique l\'a retiré de son '258 'catalogue.</p><p>'259 + (f'<a href="/boutiques/{esc(quote(sid))}">Voir les autres produits de la boutique</a> · '260 if sid else "")261 + '<a href="/produits">Tous les produits</a></p></main>')262 return rendre(title=f"Produit retiré — {SITE}",263 description="Ce produit n'est plus offert par la boutique.", body=body,264 robots="noindex, follow", status=410,265 ctx={"page": "product", "uid": uid, "gone": True, "store_id": sid})266 return page_404("Ce produit n'est pas publié.")267 canon = v["path"]268 attendu = recherche.slug_v1(v["title"])[:70].rstrip("-") or None269 if (slug or None) != attendu:270 return RedirectResponse(canon, status_code=301)271 s = v["store"]272 lieu = ", ".join(x for x in (s["city"], s["region"]) if x)273 k = v["category"]274 fh, fld = fil([("Accueil", "/"), (cats.LIBELLES[k], "/categorie/" + cats.SLUGS[k]),275 (s["name"], s["path"]), (v["title"], canon)])276 dispo = {True: "En stock", False: "Épuisé", None: "Disponibilité non précisée"}[v["available"]]277 desc = texte.resume(f"{v['title']}" + (f", {prix(v['price'])}" if v["price"] else "") + f" chez {s['name']}"278 + (f" ({lieu})" if lieu else "") + ". " + (v["summary"] or ""), 300)279 body = (f"<main>{fh}<article><h1>{esc(v['title'])}</h1>"280 + "".join(f'<img src="{esc(u)}" alt="{esc(v["title"])}" width="800" height="800"'281 f'{"" if i == 0 else " loading=\"lazy\""}>' for i, u in enumerate(v["images"][:6]))282 + f'<p><strong>{esc(prix(v["price"]) if v["price"] else "Prix chez la boutique")}</strong>'283 + (f' à {esc(prix(v["price_max"]))}' if v["price_max"] else "")284 + (f' <s>{esc(prix(v["compare_at_price"]))}</s>' if v["compare_at_price"] else "")285 + f' · {esc(dispo)}</p>'286 + f'<p>Vendu par <a href="{esc(s["path"])}">{esc(s["name"])}</a>'287 + (f", {esc(lieu)}" if lieu else "") + f' · {esc(s["origin_label"])}</p>'288 + f'<p><a href="{esc(v["url"])}" rel="nofollow noopener">Voir chez {esc(s["name"])}</a></p>'289 + "".join(f"<p>{esc(x)}</p>" for x in v["description_paragraphs"][:12])290 + ("<h2>Options</h2><ul>" + "".join(291 f'<li>{esc(o["name"])} : {esc(", ".join(o["values"][:20]))}</li>' for o in v["options"])292 + "</ul>" if v["options"] else "")293 + ("<h2>Détails</h2><dl>" + "".join(294 f'<dt>{esc(f["label"])}</dt><dd>{esc(f["value"])}</dd>' for f in v["facts"]) + "</dl>"295 if v["facts"] else "")296 + f'</article><section><h2>La boutique : {esc(s["name"])}</h2>'297 + (f'<p>{esc(s["description"])}</p>' if s["description"] else "")298 + grille(v["same_store"]) + "</section>"299 + ('<section><h2>Produits semblables chez d\'autres boutiques</h2>' + grille(v["similar"])300 + "</section>" if v["similar"] else "") + "</main>")301 if not v["public"]:302 # produit réel mais écarté des listes : page atteignable, non indexée, sans offre structurée303 return rendre(title=f"{v['title']} — {s['name']} — {SITE}", description=desc, canonical=canon,304 body=body, jsonld=[fld], image=v["images"][0] if v["images"] else None,305 robots="noindex, follow",306 ctx={"page": "product", "uid": uid, "public": False,307 "generated_at": v["generated_at"], "product": v})308 offre = {"@type": "Offer", "url": BASE + canon, "priceCurrency": "CAD", "price": f"{v['price']:.2f}",309 "availability": "https://schema.org/" + ({True: "InStock", False: "OutOfStock"}.get(v["available"], "InStock")),310 "seller": {"@type": "Organization", "name": s["name"], "url": s["url"]}}311 if v["price_max"]:312 offre = {"@type": "AggregateOffer", "priceCurrency": "CAD", "lowPrice": f"{v['price']:.2f}",313 "highPrice": f"{v['price_max']:.2f}", "offerCount": max(2, len(v["variants"]) or 2),314 "availability": offre["availability"], "url": BASE + canon,315 "seller": offre["seller"]}316 ld = {"@context": "https://schema.org", "@type": "Product", "name": v["title"],317 "image": v["images"][:6], "description": v["summary"] or v["title"], "url": BASE + canon,318 "category": cats.LIBELLES[k], "offers": offre}319 if v["vendor"]:320 ld["brand"] = {"@type": "Brand", "name": v["vendor"]}321 if v["variants"] and v["variants"][0].get("sku"):322 ld["sku"] = v["variants"][0]["sku"]323 return rendre(title=f"{v['title']} — {s['name']} — {SITE}", description=desc, canonical=canon,324 body=body, jsonld=[fld, ld], image=v["images"][0], og_type="product",325 ctx={"page": "product", "uid": uid, "public": True,326 "generated_at": v["generated_at"], "product": v})327328329def page_boutiques(params) -> HTMLResponse:330 from . import web331 cat = catalogue()332 try:333 page = max(1, int(params.get("page") or 1))334 except ValueError:335 page = 1336 filtres = {k: params.get(k) or "" for k in ("q", "region", "city", "category", "origin")}337 try:338 res = web.liste_boutiques(cat, filtres["q"], filtres["region"], filtres["city"],339 filtres["category"], filtres["origin"], "", None, None, False,340 params.get("sort") or "size", page, 48)341 except recherche.Erreur as exc:342 return page_404(str(exc))343 libres = {k: v for k, v in filtres.items() if v}344 desc = (f"{entier(res['total'])} boutiques en ligne du Québec suivies par Fabri-Ka, "345 f"{entier(res['products_total'])} produits : artisans, producteurs, fabricants et détaillants.")346 fh, fld = fil([("Accueil", "/"), ("Boutiques", "/boutiques")])347 body = (f"<main>{fh}<h1>Les boutiques du Québec</h1><p>{esc(desc)}</p><ul>"348 + "".join(li_boutique(b) for b in res["stores"]) + "</ul>"349 + pagination("/boutiques", libres, page, res["pages"]) + "</main>")350 return rendre(title=f"Boutiques du Québec{f' — page {page}' if page > 1 else ''} — {SITE}",351 description=desc, canonical="/boutiques" + (f"?page={page}" if page > 1 else ""),352 body=body, jsonld=[fld], robots="noindex, follow" if libres else None,353 ctx={"page": "stores", "results": res})354355356def page_boutique(store_id: str, params) -> Response:357 from . import web358 cat = catalogue()359 v = web._memo(cat, "boutique", store_id.lower(), lambda: web.fiche_boutique(store_id) or False)360 if not v:361 return page_404("Cette boutique n'est pas au répertoire.")362 canon = "/boutiques/" + quote(v["id"])363 if store_id != v["id"]:364 return RedirectResponse(canon, status_code=301)365 if not v.get("catalogue"):366 lieu = ", ".join(x for x in (v.get("city"), v.get("region")) if x)367 body = (f'<main><h1>{esc(v["name"])}</h1><p>{esc(lieu)}</p><p>Boutique répertoriée, sans '368 f'catalogue suivi par Fabri-Ka.</p><p><a href="{esc(v["url"])}" rel="nofollow noopener">'369 'Visiter le site</a></p></main>')370 return rendre(title=f"{v['name']} — {SITE}", description=f"{v['name']} : boutique du Québec répertoriée par Fabri-Ka.",371 canonical=canon, body=body, robots="noindex, follow",372 ctx={"page": "store", "id": v["id"], "store": v})373 try:374 page = max(1, int(params.get("page") or 1))375 except ValueError:376 page = 1377 libres = {k: params.get(k) for k in ("q", "category", "sort", "in_stock", "new") if params.get(k)}378 try:379 res = web.reponse_recherche(cat, {**{k: params.get(k) for k in recherche.PARAMS}, "store": v["id"]},380 params.get("sort") or "", page, PER_PAGE, 0, False, True)381 except recherche.Erreur as exc:382 return page_404(str(exc))383 lieu = ", ".join(x for x in (v["city"], v["region"]) if x)384 desc = texte.resume(f"{v['name']}" + (f", {lieu}" if lieu else "") + f" : {entier(v['n'])} produits "385 f"({v['category_label']}). " + (v["description"] or ""), 300)386 fh, fld = fil([("Accueil", "/"), ("Boutiques", "/boutiques"), (v["name"], canon)])387 c = v["contact"]388 body = (f"<main>{fh}<h1>{esc(v['name'])}</h1><p>{esc(lieu)} · {esc(v['origin_label'])}</p>"389 + (f"<p>{esc(v['description'])}</p>" if v["description"] else "")390 + f'<p><a href="{esc(v["url"])}" rel="nofollow noopener">Visiter la boutique</a>'391 + (f' · <a href="tel:{esc(c["phone"]["tel"])}">{esc(c["phone"]["affichage"])}</a>' if c["phone"] else "")392 + "</p>"393 + ("<ul>" + "".join(f"<li>{esc(x['label'])}</li>" for x in v["certifications"]) + "</ul>"394 if v["certifications"] else "")395 + f"<h2>{entier(res['total'])} produits</h2>" + grille(res["products"])396 + pagination(canon, libres, page, res["pages"])397 + ("<h2>Boutiques voisines</h2><ul>" + "".join(li_boutique(b) for b in v["nearby"]) + "</ul>"398 if v["nearby"] else "") + "</main>")399 ld = {"@context": "https://schema.org", "@type": ["Store", "LocalBusiness"], "name": v["name"],400 "url": v["url"], "@id": BASE + canon}401 if v["description"]:402 ld["description"] = v["description"]403 if v["logo"]:404 ld["logo"] = v["logo"]405 if v["img"]:406 ld["image"] = v["img"]407 if c["phone"]:408 ld["telephone"] = c["phone"]["tel"]409 if c["email"]:410 ld["email"] = c["email"]411 if v["city"] or v["region"]:412 ld["address"] = {"@type": "PostalAddress", "addressRegion": "QC", "addressCountry": "CA",413 **({"addressLocality": v["city"]} if v["city"] else {})}414 if v["lat"] is not None:415 ld["geo"] = {"@type": "GeoCoordinates", "latitude": v["lat"], "longitude": v["lng"]}416 if c["socials"]:417 ld["sameAs"] = [x["url"] for x in c["socials"]]418 return rendre(title=f"{v['name']}{f' ({lieu})' if lieu else ''} — {SITE}", description=desc,419 canonical=canon + (f"?page={page}" if page > 1 else ""), body=body, jsonld=[fld, ld],420 image=v["cover"] or v["img"], robots="noindex, follow" if libres else None,421 ctx={"page": "store", "id": v["id"], "store": v, "results": res})422423424def page_regions() -> HTMLResponse:425 from . import web426 d = web.index_regions(catalogue())427 fh, fld = fil([("Accueil", "/"), ("Régions", "/regions")])428 desc = "Les boutiques et les produits du Québec, région par région : les 17 régions administratives."429 body = (f"<main>{fh}<h1>Les régions du Québec</h1><p>{esc(desc)}</p><ul>"430 + "".join(f'<li><a href="{esc(r["path"])}">{esc(r["name"])}</a> : {entier(r["stores"])} boutiques, '431 f'{entier(r["products"])} produits</li>' for r in d["regions"]) + "</ul></main>")432 return rendre(title=f"Régions du Québec — {SITE}", description=desc, canonical="/regions",433 body=body, jsonld=[fld], ctx={"page": "regions", "regions": d})434435436def page_region(slug: str, params) -> HTMLResponse:437 from . import web438 cat = catalogue()439 v = web.page_region(cat, slug)440 if v is None:441 return page_404("Région inconnue.")442 extra = ("<h2>Villes</h2><ul>" + "".join(443 f'<li><a href="{esc(c["path"])}">{esc(c["name"])}</a> ({c["stores"]})</li>' for c in v["cities"][:40])444 + "</ul><h2>Boutiques</h2><ul>" + "".join(li_boutique(b) for b in v["top_stores"]) + "</ul>"445 + "<h2>Produits récents</h2>")446 return page_liste(params, fixe={"region": v["slug"]}, chemin=v["path"],447 titre=f"Produits et boutiques : {v['name']}",448 intro=f"{{n}} produits de {{b}} boutiques en ligne établies dans la région {v['name']}.",449 fil_items=[("Accueil", "/"), ("Régions", "/regions"), (v["name"], v["path"])],450 page_ctx={"page": "region", "slug": v["slug"], "region": v}, extra_html=extra)451452453def page_ville(slug: str, params) -> HTMLResponse:454 from . import web455 cat = catalogue()456 v = web.page_ville(cat, slug)457 if v is None:458 return page_404("Ville inconnue.")459 extra = ("<h2>Boutiques</h2><ul>" + "".join(li_boutique(b) for b in v["all_stores"]) + "</ul>"460 + "<h2>Produits récents</h2>")461 items = [("Accueil", "/"), ("Régions", "/regions")]462 if v["region"]:463 items.append((v["region"], "/region/" + v["region_slug"]))464 items.append((v["name"], v["path"]))465 return page_liste(params, fixe={"city": v["slug"]}, chemin=v["path"],466 titre=f"Boutiques et produits : {v['name']}",467 intro=f"{{n}} produits de {{b}} boutiques en ligne établies à {v['name']}"468 + (f" ({v['region']})." if v["region"] else "."),469 fil_items=items, page_ctx={"page": "city", "slug": v["slug"], "city": v},470 extra_html=extra)471472473def page_categorie(parts: list[str], params) -> Response:474 cat = catalogue()475 k = cats.CLE_DU_SLUG.get(parts[0])476 if not k:477 return page_404("Catégorie inconnue.")478 lab = cats.LIBELLES[k]479 base = "/categorie/" + cats.SLUGS[k]480 items = [("Accueil", "/"), ("Produits", "/produits"), (lab, base)]481 from . import web482 noeud = next((c for c in web.arbre_categories(cat) if c["key"] == k), None)483 if len(parts) == 1:484 extra = ""485 if noeud and noeud["subcategories"]:486 extra = "<h2>Sous-catégories</h2><ul>" + "".join(487 f'<li><a href="{esc(s["path"])}">{esc(s["label"])}</a> ({entier(s["n"])})</li>'488 for s in noeud["subcategories"]) + "</ul>"489 return page_liste(params, fixe={"category": k}, chemin=base, titre=lab,490 intro=f"{{n}} produits de {{b}} boutiques du Québec dans la catégorie {lab}.",491 fil_items=items, page_ctx={"page": "category", "category": k, "node": noeud},492 extra_html=extra)493 if len(parts) == 3 and parts[1] == "region":494 r = cat.region_slug.get(parts[2])495 if not r:496 return page_404("Région inconnue.")497 return page_liste(params, fixe={"category": k, "region": parts[2]},498 chemin=f"{base}/region/{parts[2]}", titre=f"{lab} : {r}",499 intro=f"{{n}} produits de {{b}} boutiques de la région {r} dans la catégorie {lab}.",500 fil_items=items + [(r, f"{base}/region/{parts[2]}")],501 page_ctx={"page": "category", "category": k, "region": r, "node": noeud})502 if len(parts) == 2:503 j = cat.sous_index.get((k, parts[1]))504 if j is None:505 return page_404("Sous-catégorie inconnue.")506 s = cat.sous[j]507 return page_liste(params, fixe={"category": k, "subcategory": s["slug"]},508 chemin=f"{base}/{s['slug']}", titre=f"{s['label']} ({lab})",509 intro=f"{{n}} produits de {{b}} boutiques du Québec : {s['label']}.",510 fil_items=items + [(s["label"], f"{base}/{s['slug']}")],511 page_ctx={"page": "category", "category": k, "subcategory": s["slug"],512 "node": noeud})513 return page_404()514515516def page_hasard(kind: str, seed: str) -> Response:517 from . import web518 cat = catalogue()519 try:520 d = web.au_hasard(cat, "product" if kind == "produit" else "store",521 int(seed) if seed else None)522 except (ValueError, recherche.Erreur):523 return page_404()524 if not seed:525 return RedirectResponse(d["path"], status_code=302)526 if d["kind"] == "product":527 c = d["product"]528 body = (f'<main><h1>Au hasard : {esc(c["title"])}</h1>' + grille([c])529 + f'<p><a href="/hasard/produit">Un autre</a></p></main>')530 titre = f"Au hasard : {c['title']}"531 else:532 b = d["store"]533 body = (f'<main><h1>Au hasard : {esc(b["name"])}</h1><ul>{li_boutique(b)}</ul>'534 + grille(d["products"]) + '<p><a href="/hasard/boutique">Une autre</a></p></main>')535 titre = f"Au hasard : {b['name']}"536 return rendre(title=f"{titre} — {SITE}", description="Une découverte tirée au sort dans le répertoire.",537 body=body, robots="noindex, follow", ctx={"page": "random", **d})538539540def page_stats() -> HTMLResponse:541 from . import web542 cat = catalogue()543 s = web.statistiques(cat)544 t = s["totals"]545 desc = (f"Le répertoire en chiffres : {entier(t['products'])} produits, {entier(t['stores'])} boutiques, "546 f"{t['regions']} régions, prix médian {prix(t['price_median'])}.")547 fh, fld = fil([("Accueil", "/"), ("Le répertoire en chiffres", "/stats")])548 body = (f"<main>{fh}<h1>Le répertoire en chiffres</h1><p>{esc(desc)}</p>"549 "<h2>Par région</h2><table><tr><th>Région</th><th>Boutiques</th><th>Produits</th></tr>"550 + "".join(f"<tr><td>{esc(r['name'])}</td><td>{entier(r['stores'])}</td><td>{entier(r['products'])}</td></tr>"551 for r in s["by_region"])552 + "</table><h2>Par catégorie</h2><table><tr><th>Catégorie</th><th>Produits</th><th>Boutiques</th></tr>"553 + "".join(f"<tr><td>{esc(r['label'])}</td><td>{entier(r['products'])}</td><td>{entier(r['stores'])}</td></tr>"554 for r in s["by_category"]) + "</table></main>")555 return rendre(title=f"Le répertoire en chiffres — {SITE}", description=desc, canonical="/stats",556 body=body, jsonld=[fld], ctx={"page": "stats", "stats": s})557558559_STATIQUES = {560 "a-propos": ("À propos", "Fabri-Ka recense les boutiques en ligne du Québec et leurs produits. On n'y "561 "achète rien : chaque produit renvoie à la boutique d'origine.", None),562 "contact": ("Contact", f"Une question, une correction, un retrait : {CONTACT}.", None),563 "inscrire": ("Inscrire une boutique", "Proposez votre boutique en ligne québécoise : la demande est "564 "lue par une personne avant toute publication.", None),565 "methode": ("Méthode et sources", "D'où viennent les données, ce qui est publié, ce qui est écarté, "566 "et ce que « québécois » veut dire ici.", None),567 "carte": ("Carte des boutiques", "Les boutiques en ligne du Québec sur la carte, par région et par ville.", None),568 "decouvrir": ("Découvrir", "Nouveautés de la semaine, boutiques récemment ajoutées, catégories et "569 "trouvailles au hasard.", None),570 "favoris": ("Favoris", "Les produits et les boutiques mis de côté sur cet appareil.", "noindex, follow"),571 "comparer": ("Comparer", "Des produits côte à côte.", "noindex, follow"),572 "recherches": ("Recherches enregistrées", "Les recherches gardées sur cet appareil.", "noindex, follow"),573 "reglages": ("Réglages", "Thème, animations, données gardées sur cet appareil.", "noindex, follow"),574 "confidentialite": ("Confidentialité", "Fabri-Ka n'a ni compte ni témoin de suivi. Favoris et "575 "réglages restent sur l'appareil.", None),576}577578579def page_statique(nom: str) -> HTMLResponse:580 titre, desc, robots = _STATIQUES[nom]581 ctx: dict = {"page": nom}582 extra = ""583 if nom == "methode":584 cat = catalogue()585 extra = "<h2>Ce qui est publié</h2><ol>" + "".join(f"<li>{esc(r)}</li>" for r in public.REGLES) + "</ol>"586 ctx["rules"] = public.REGLES587 ctx["measures"] = {"products": cat.N, "stores": len(cat.boutiques)}588 if nom == "inscrire":589 from . import inscriptions590 ctx["form"] = inscriptions.formulaire()591 if nom in ("carte", "decouvrir"):592 extra = '<p><a href="/regions">Les régions</a> · <a href="/boutiques">Les boutiques</a></p>'593 body = (f"<main><h1>{esc(titre)}</h1><p>{esc(desc)}</p>{extra}"594 f'<p>Contact : <a href="mailto:{CONTACT}">{CONTACT}</a></p></main>')595 return rendre(title=f"{titre} — {SITE}", description=desc, canonical="/" + nom, body=body,596 robots=robots, ctx=ctx)597598599# -- robots, sitemaps -----------------------------------------------------------------600def robots_txt() -> PlainTextResponse:601 if NOINDEX:602 return PlainTextResponse("User-agent: *\nDisallow: /\n")603 return PlainTextResponse("User-agent: *\nAllow: /\nDisallow: /api/\nDisallow: /hasard/\n"604 "Disallow: /favoris\nDisallow: /reglages\n\n"605 f"Sitemap: {BASE}/sitemap.xml\n")606607608def _urlset(urls) -> str:609 return ('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'610 + "".join("<url><loc>" + esc(BASE + p) + "</loc>" + (f"<lastmod>{d}</lastmod>" if d else "") + "</url>"611 for p, d in urls) + "</urlset>")612613614def _morceaux(cat) -> int:615 return max(1, -(-cat.N // SITEMAP_CHUNK))616617618def sitemap_index() -> Response:619 from . import web620 cat = catalogue()621622 def calc():623 jour = iso(cat.genere)624 noms = ["pages", "categories", "lieux", "boutiques"] + [f"produits-{i}" for i in range(1, _morceaux(cat) + 1)]625 return ('<?xml version="1.0" encoding="UTF-8"?><sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'626 + "".join(f"<sitemap><loc>{esc(BASE)}/sitemap-{n}.xml</loc><lastmod>{jour}</lastmod></sitemap>"627 for n in noms) + "</sitemapindex>")628 return Response(web._memo(cat, "sm", "index", calc), media_type="application/xml")629630631def sitemap(name: str) -> Response:632 from . import web633 import numpy as np634 cat = catalogue()635 jour = iso(cat.genere)636637 def pages():638 return _urlset([("/", jour), ("/produits", jour), ("/boutiques", jour), ("/regions", jour),639 ("/stats", jour), ("/decouvrir", jour), ("/carte", None), ("/methode", None),640 ("/a-propos", None), ("/contact", None), ("/inscrire", None)])641642 def categories_():643 urls = []644 for c in web.arbre_categories(cat):645 urls.append((c["path"], jour))646 urls += [(s["path"], jour) for s in c["subcategories"]]647 ci = cats.INDEX_CLE[c["key"]]648 nb = np.bincount(cat.p_b[cat.p_cat == ci], minlength=len(cat.boutiques))649 for i, r in enumerate(cat.regions):650 if nb[cat.b_region == i].sum() > 0:651 urls.append((f"{c['path']}/region/{texte.slug(r)}", jour))652 return _urlset(urls)653654 def lieux():655 urls = [(r["path"], jour) for r in web.index_regions(cat)["regions"] if r["stores"]]656 urls += [(v["path"], jour) for v in web.index_villes(cat)]657 return _urlset(urls)658659 def boutiques():660 return _urlset([("/boutiques/" + quote(b["id"]), iso(b["last_ok"] or b["last_sync"]))661 for b in cat.boutiques])662663 if name == "pages":664 xml = web._memo(cat, "sm", "pages", pages)665 elif name == "categories":666 xml = web._memo(cat, "sm", "categories", categories_)667 elif name == "lieux":668 xml = web._memo(cat, "sm", "lieux", lieux)669 elif name == "boutiques":670 xml = web._memo(cat, "sm", "boutiques", boutiques)671 else:672 m = re.fullmatch(r"produits-(\d+)", name)673 if not m or not (1 <= int(m.group(1)) <= _morceaux(cat)):674 return PlainTextResponse("Introuvable", status_code=404)675 i = int(m.group(1))676677 def produits():678 ordre = sorted(range(cat.N), key=lambda j: cat.uid[j])[(i - 1) * SITEMAP_CHUNK: i * SITEMAP_CHUNK]679 return _urlset([(recherche.chemin_produit(cat.uid[j], cat.titre[j]), iso(cat.p_vu[j]))680 for j in ordre])681 xml = web._memo(cat, "sm", name, produits)682 return Response(xml, media_type="application/xml")683684685# -- routeur ----------------------------------------------------------------------------686_PROD = re.compile(r"^produits/(?:(?P<slug>.+)-)?(?P<uid>[0-9a-f]{20})$")687_RETIREES = {"profil": "Fabri-Ka n'a plus de compte ni de profil.",688 "doc": "L'ancien guide a été retiré.", "connexion": "Fabri-Ka n'a plus de compte.",689 "mon-univers": "Les favoris restent sur l'appareil."}690691692def route(path: str, params) -> Response:693 path = path.strip("/")694 if path == "":695 return page_accueil()696 if path in ("produits", "recherche"):697 if path == "recherche":698 q = urlencode({k: v for k, v in params.items()})699 return RedirectResponse("/produits" + ("?" + q if q else ""), status_code=301)700 q = (params.get("q") or "").strip()701 return page_liste(params, fixe={}, chemin="/produits",702 titre=f"« {q} »" if q else "Tous les produits",703 intro="{n} produits de {b} boutiques en ligne du Québec.",704 fil_items=[("Accueil", "/"), ("Produits", "/produits")],705 page_ctx={"page": "search"})706 m = _PROD.match(path)707 if m:708 return page_produit(m.group("slug"), m.group("uid"))709 parts = path.split("/")710 tete = parts[0]711 if tete == "produits":712 return page_404("Produit inconnu.")713 if path == "boutiques":714 return page_boutiques(params)715 if tete == "boutiques" and len(parts) == 2:716 return page_boutique(parts[1], params)717 if tete == "categorie" and 2 <= len(parts) <= 4:718 return page_categorie(parts[1:], params)719 if path == "regions":720 return page_regions()721 if tete == "region" and len(parts) == 2:722 return page_region(parts[1], params)723 if tete == "ville" and len(parts) == 2:724 return page_ville(parts[1], params)725 if tete == "hasard" and len(parts) in (2, 3) and parts[1] in ("produit", "boutique"):726 return page_hasard(parts[1], parts[2] if len(parts) == 3 else "")727 if path == "stats":728 return page_stats()729 if path in _STATIQUES:730 return page_statique(path)731 if tete in _RETIREES:732 return page_retiree(_RETIREES[tete])733 return page_404()734735736def monter(app: FastAPI) -> None:737 @app.get("/robots.txt", include_in_schema=False)738 def _robots():739 return robots_txt()740741 @app.get("/sitemap.xml", include_in_schema=False)742 def _sm_index():743 return sitemap_index()744745 @app.get("/sitemap-{name}.xml", include_in_schema=False)746 def _sm(name: str):747 return sitemap(name)748749 class _Haches(StaticFiles):750 def file_response(self, *a, **kw):751 r = super().file_response(*a, **kw)752 r.headers["Cache-Control"] = "public, max-age=31536000, immutable"753 return r754755 if (FRONT_DIST / "assets").is_dir():756 app.mount("/assets", _Haches(directory=FRONT_DIST / "assets"), name="assets")757758 @app.get("/{path:path}", include_in_schema=False)759 def _page(path: str, request: Request):760 if path and ".." not in path:761 cible = FRONT_DIST / path762 if cible.is_file() and cible.name != "index.html":763 r = FileResponse(cible)764 r.headers["Cache-Control"] = "public, max-age=86400"765 return r766 return route(path, request.query_params)767