Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Food·Ka9# File : foodka/connectors/_shopify.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/_shopify.py : socle commun des épiceries sur Shopify91# Toute boutique Shopify expose son catalogue public en JSON :92# /products.json?limit=250&page=N (ou /collections/{handle}/products.json93# pour cibler des rayons précis). Aucun anti-bot, requests direct suffit.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"<[^>]+>")105106107def _strip_html(text: str | None, max_len: int = 1500) -> str:108 """Retire les balises HTML d'un body_html Shopify et tronque (~1500 car.)."""109 if not text:110 return ""111 clean = html.unescape(_TAG_RE.sub(" ", text))112 clean = re.sub(r"\s+", " ", clean).strip()113 if len(clean) > max_len:114 clean = clean[:max_len].rsplit(" ", 1)[0] + "…"115 return clean116117118class ShopifyConnector(BaseConnector):119 """Base des épiceries Shopify — sous-classes : définir source_id et domain.120121 Par défaut on pagine /products.json (catalogue complet). Si le champ122 `product_type` de la boutique est vide ou inutilisable, une sous-classe123 peut définir `collections` : liste de (handle, catégorie canonique) —124 on pagine alors /collections/{handle}/products.json à la place.125 Une catégorie canonique vide ("") signifie : déduire du product_type.126 """127128 domain: str = "" # ex. "www.supermarchepa.com"129 # /products.json est gratuit et direct (aucun crédit Scrapfly) : plafond130 # large — 24 × 250 = 6 000 produits par catalogue/collection.131 max_pages: int = 24 # 250 produits/page132 collections: list[tuple[str, str]] = [] # [(handle, catégorie canonique)]133134 # -- récupération -----------------------------------------------------------135 def _page(self, url: str) -> list[dict]:136 """Une page de produits JSON ; liste vide si la page n'existe pas."""137 resp = self.get(url, headers={"Accept": "application/json"})138 data = resp.json()139 return data.get("products") or []140141 # -- mapping Shopify -> Product ----------------------------------------------142 def _pick_variant(self, product: dict) -> dict:143 """Première variante disponible, sinon la première tout court."""144 variants = product.get("variants") or []145 for v in variants:146 if v.get("available"):147 return v148 return variants[0] if variants else {}149150 def _to_product(self, product: dict, category: str = "") -> Product | None:151 pid = product.get("id")152 handle = product.get("handle") or ""153 if not pid or not handle:154 return None155 variant = self._pick_variant(product)156157 # prix : la variante porte le prix courant ; compare_at_price est le158 # prix régulier quand le produit est en solde.159 try:160 price = float(variant.get("price")) if variant.get("price") else None161 except (TypeError, ValueError):162 price = None163 regular = None164 try:165 cap = variant.get("compare_at_price")166 if cap and price is not None and float(cap) > price:167 regular = float(cap)168 except (TypeError, ValueError):169 regular = None170171 # format : titre de variante s'il est réel, sinon le poids en grammes172 size_label = ""173 vtitle = variant.get("title") or ""174 if vtitle and vtitle != "Default Title":175 size_label = vtitle176 elif variant.get("grams"):177 size_label = f"{variant['grams']} g"178179 tags = [str(t) for t in product.get("tags") or [] if t]180 category_raw = product.get("product_type") or " ".join(tags)181182 # prix unitaire : size_label d'abord ; sinon le poids en grammes de la183 # variante (fiable même quand le titre de variante n'est pas un format)184 unit_p, unit_label = None, ""185 if price is not None:186 up = unit_price(price, size_label)187 if not up and variant.get("grams"):188 up = unit_price(price, f"{variant['grams']} g")189 if up:190 unit_p, unit_label = up[0], format_unit_price(up)191192 # champs structurés : variantes multiples (multi-formats à prix193 # distincts), dates produit Shopify194 details: dict = {}195 variants = product.get("variants") or []196 if len(variants) > 1:197 details["variant_count"] = len(variants)198 details["variants"] = [{k: v for k, v in {199 "title": var.get("title"),200 "price": var.get("price"),201 "grams": var.get("grams"),202 "sku": var.get("sku"),203 "available": var.get("available"),204 }.items() if v not in (None, "")} for var in variants[:15]]205 for key in ("created_at", "updated_at"):206 if product.get(key):207 details[key] = product[key]208209 return Product(210 source=self.source_id,211 external_id=str(pid),212 url=f"https://{self.domain}/products/{handle}",213 name=html.unescape(product.get("title") or ""),214 brand=product.get("vendor") or "",215 category=category or normalize_category(category_raw),216 category_raw=category_raw,217 size_label=size_label,218 price=price,219 regular_price=regular,220 on_sale=bool(regular is not None),221 unit_price=unit_p,222 unit_price_label=unit_label,223 in_stock=(bool(variant["available"])224 if variant.get("available") is not None else None),225 description=_strip_html(product.get("body_html")),226 keywords=tags,227 details=details,228 images=[img["src"] for img in product.get("images") or []229 if isinstance(img, dict) and img.get("src")],230 )231232 # -- contrat ------------------------------------------------------------------233 def fetch(self) -> list[Product]:234 products: list[Product] = []235 seen: set[str] = set()236 # sources à paginer : catalogue complet, ou collections ciblées237 sources: list[tuple[str, str]] = (238 [(f"https://{self.domain}/collections/{handle}/products.json", cat)239 for handle, cat in self.collections]240 or [(f"https://{self.domain}/products.json", "")])241 for base_url, category in sources:242 for page in range(1, self.max_pages + 1):243 try:244 batch = self._page(f"{base_url}?limit=250&page={page}")245 except Exception: # une collection qui casse ne bloque pas le reste246 break247 if not batch:248 break249 for raw in batch:250 try:251 prod = self._to_product(raw, category)252 except Exception:253 continue254 if prod and prod.name and prod.uid not in seen:255 seen.add(prod.uid)256 products.append(prod)257 return products258