Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Food·Ka9# File : foodka/connectors/_woocommerce.py10# Module : foodka11# Repository : https://git.spboucher.ai/food-ka12# Created : 2026-08-1213# Last Modified : 2026-08-1814#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author : Simon-Pierre Boucher20# Position : Professor of Finance21# Institution : Université du Québec en Outaouais (UQO)22# Department : Département des sciences administratives23# Organization : SP Boucher24#25# Website : https://spboucher.ai26# Git : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General : info@spboucher.ai33# Professional : contact@spboucher.ai34# Direct : simon@spboucher.ai35# Research : research@spboucher.ai36# Development : dev@spboucher.ai37# Support : support@spboucher.ai38# Security/Admin : admin@spboucher.ai39# Notifications : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification : Public66# Distribution : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License : None specified (no license file in this repository)80# Maintainer : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Food-Ka — Agrégateur de produits d'épicerie (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/_woocommerce.py : socle commun des épiceries sur WooCommerce91# L'API publique "Store API" expose le catalogue en JSON sans clé :92# /wp-json/wc/store/v1/products?per_page=100&page=N. Les prix y sont en93# unités mineures (cents) — "1299" + currency_minor_unit=2 -> 12,99 $.94# -----------------------------------------------------------------------------95from __future__ import annotations9697import html98import re99100from ..normalize import format_unit_price, unit_price101from ..schema import Product, normalize_category102from .base import BaseConnector103104_TAG_RE = re.compile(r"<[^>]+>")105106# format dans le nom du produit : "Yogourt nature (650 g)", "Huile 2 x 750 ml"107_SIZE_IN_NAME_RE = re.compile(108 r"(\d+\s*[x×]\s*)?\d+(?:[.,]\d+)?\s*(?:kg|g|mg|lb|lbs|oz|ml|cl|l|un|unités?)\b",109 re.IGNORECASE)110111112def _strip_html(text: str | None, max_len: int = 500) -> str:113 """Retire balises et entités HTML d'un champ WooCommerce, tronque (~500)."""114 if not text:115 return ""116 clean = html.unescape(_TAG_RE.sub(" ", text))117 clean = re.sub(r"\s+", " ", clean).strip()118 if len(clean) > max_len:119 clean = clean[:max_len].rsplit(" ", 1)[0] + "…"120 return clean121122123def store_api_details(raw: dict) -> dict:124 """Champs structurés riches de la Store API -> details (JSON).125126 Note (avis clients, poids/dimensions catalogue, attributs bio/origine,127 stock restant, nombre de variantes) — seulement les champs renseignés.128 Partagé avec le connecteur akhavan (Store API maison).129 """130 details: dict = {}131 try:132 rating = float(raw.get("average_rating") or 0)133 except (TypeError, ValueError):134 rating = 0.0135 if rating > 0:136 details["average_rating"] = rating137 if raw.get("review_count"):138 details["review_count"] = raw["review_count"]139140 fw = raw.get("formatted_weight") or ""141 weight = raw.get("weight") or ""142 if fw and fw not in ("N/A", "n/a"):143 details["weight"] = fw144 elif weight not in ("", "0", 0, None):145 details["weight"] = str(weight)146147 dims = raw.get("dimensions") or {}148 if isinstance(dims, dict):149 dims = {k: v for k, v in dims.items()150 if k in ("length", "width", "height") and v not in ("", "0", None)}151 if dims:152 details["dimensions"] = dims153154 # attributs produit (bio, origine, format…) : {nom: "terme1, terme2"}155 attrs: dict[str, str] = {}156 for att in raw.get("attributes") or []:157 if not isinstance(att, dict):158 continue159 aname = html.unescape(str(att.get("name") or "")).strip()160 terms = [html.unescape(str(t.get("name") or "")).strip()161 for t in att.get("terms") or [] if isinstance(t, dict)]162 terms = [t for t in terms if t]163 if aname and terms:164 attrs[aname] = ", ".join(terms)165 if attrs:166 details["attributes"] = attrs167168 if raw.get("low_stock_remaining") is not None:169 details["low_stock_remaining"] = raw["low_stock_remaining"]170 variations = raw.get("variations") or []171 if variations:172 details["variation_count"] = len(variations)173 return details174175176def _minor(value: str | int | None, minor_unit: int) -> float | None:177 """Convertit un prix Store API (unités mineures) en dollars : "1299" -> 12.99."""178 if value in (None, ""):179 return None180 try:181 return round(int(value) / (10 ** minor_unit), 2)182 except (TypeError, ValueError):183 return None184185186class WooStoreConnector(BaseConnector):187 """Base des épiceries WooCommerce — sous-classes : source_id et domain."""188189 domain: str = "" # ex. "bocoboco.ca"190 # Store API gratuite et directe : plafond large (aliments_merci était191 # tronqué à exactement 800 produits avec l'ancien plafond de 8 ;192 # son catalogue complet fait ~2 765 produits = 28 pages).193 max_pages: int = 32 # 100 produits/page194 per_page: int = 100195196 def _page(self, page: int) -> list[dict]:197 url = (f"https://{self.domain}/wp-json/wc/store/v1/products"198 f"?per_page={self.per_page}&page={page}")199 resp = self.get(url, headers={"Accept": "application/json"})200 data = resp.json()201 return data if isinstance(data, list) else []202203 def _to_product(self, raw: dict) -> Product | None:204 pid = raw.get("id")205 name = html.unescape(_TAG_RE.sub("", raw.get("name") or "")).strip()206 if not pid or not name:207 return None208209 prices = raw.get("prices") or {}210 minor_unit = int(prices.get("currency_minor_unit") or 2)211 price = _minor(prices.get("price"), minor_unit)212 on_sale = bool(raw.get("on_sale"))213 regular = _minor(prices.get("regular_price"), minor_unit) if on_sale else None214 if regular is not None and price is not None and regular <= price:215 regular = None # solde annoncé mais prix identiques : pas un rabais216217 # taxonomie : première catégorie = catégorie brute, les autres en mots-clés218 cats = [c.get("name") or "" for c in raw.get("categories") or []219 if isinstance(c, dict)]220 cats = [html.unescape(c).strip() for c in cats if c]221 category_raw = cats[0] if cats else ""222 keywords = cats[1:]223224 # format : extrait du nom s'il y figure (ex. "Tofu ferme 454 g")225 m = _SIZE_IN_NAME_RE.search(name)226 size_label = m.group(0).strip() if m else ""227228 # marque : taxonomie `brands` de la Store API (quand la boutique l'a)229 brands = raw.get("brands") or []230 brand = (html.unescape(brands[0].get("name") or "").strip()231 if brands and isinstance(brands[0], dict) else "")232233 # prix unitaire : si le nom ne porte pas de format, le poids catalogue234 # (`formatted_weight` inclut l'unité, ex. "885 g") fiabilise le $/100 g235 fw = raw.get("formatted_weight") or ""236 if fw in ("N/A", "n/a"):237 fw = ""238 unit_p, unit_label = None, ""239 if price is not None and not size_label and fw:240 up = unit_price(price, fw)241 if up:242 unit_p, unit_label = up[0], format_unit_price(up)243244 return Product(245 source=self.source_id,246 external_id=str(pid),247 url=raw.get("permalink") or f"https://{self.domain}/?p={pid}",248 name=name,249 brand=brand,250 category=normalize_category(category_raw),251 category_raw=category_raw,252 size_label=size_label,253 price=price,254 regular_price=regular,255 on_sale=on_sale and regular is not None,256 unit_price=unit_p,257 unit_price_label=unit_label,258 in_stock=(bool(raw["is_in_stock"])259 if raw.get("is_in_stock") is not None else None),260 description=_strip_html(raw.get("short_description")261 or raw.get("description")),262 keywords=keywords,263 details=store_api_details(raw),264 images=[img["src"] for img in raw.get("images") or []265 if isinstance(img, dict) and img.get("src")],266 )267268 # -- contrat ------------------------------------------------------------------269 def fetch(self) -> list[Product]:270 products: list[Product] = []271 seen: set[str] = set()272 for page in range(1, self.max_pages + 1):273 try:274 batch = self._page(page)275 except Exception: # fin de pagination ou site en dérangement276 break277 if not batch:278 break279 for raw in batch:280 try:281 prod = self._to_product(raw)282 except Exception:283 continue284 if prod and prod.uid not in seen:285 seen.add(prod.uid)286 products.append(prod)287 return products288