SPB Git

Repository Public

saq.py 12.5 KB 323 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Food·Ka9# File             : foodka/connectors/saq.py10# Module           : foodka11# Repository       : https://git.spboucher.ai/food-ka12# Created          : 2026-08-1813# 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 — connecteur SAQ (saq.com — Société des alcools du Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# Prix officiels UNIFORMES dans toute la province (monopole d'État) : une seule91# « succursale » suffit. Magento 2 + Adobe Live Search : la grille produit est92# montée côté client, mais l'API GraphQL du catalogue93# (catalog-service.adobe.io/graphql) répond en DIRECT — clé publique du94# storefront (X-Api-Key: search_gql + Magento-Environment-Id lu sur la page).95# productSearch paginé 200/page, TOUT dans la réponse liste (prix final et96# régulier, format ml, pays, cépages, pastille de goût, dispo en ligne,97# image) : zéro Scrapfly, zéro page détail. ~22 requêtes/sync.98# Cap ~3 300 produits : premières pages de chaque catégorie dans l'ordre de99# pertinence du site (produits mis en avant = les plus populaires) ; le vin100# (20 000+ réfs) et les spiritueux (3 300) sont plafonnés, les petites101# catégories (bière, cidre…) sont couvertes en entier.102# Catégorie canonique unique « Alcool » (exclue du matching inter-bannières —103# voir matching.EXCLUDED_SOURCES).104# -----------------------------------------------------------------------------105from __future__ import annotations106107import os108109from ..schema import Product, clean_text110from .base import BaseConnector111112GRAPHQL_URL = "https://catalog-service.adobe.io/graphql"113114# En-têtes publics du storefront saq.com (visibles dans la page HTML —115# script LiveSearchAutocomplete). Le customer group est celui des invités.116STOREFRONT_HEADERS = {117    "Content-Type": "application/json",118    "Origin": "https://www.saq.com",119    "Referer": "https://www.saq.com/",120    "X-Api-Key": "search_gql",121    "Magento-Environment-Id": "2ce24571-9db9-4786-84a9-5f129257ccbb",122    "Magento-Website-Code": "base",123    "Magento-Store-Code": "main_website_store",124    "Magento-Store-View-Code": "fr",125    "Magento-Customer-Group": "b6589fc6ab0dc82cf12099d1c2d40ab994e8410c",126}127128# (categoryPath, nb de pages de 200) — priorité aux familles populaires.129# Totaux live 2026-08 : vin 20 421, spiritueux 3 284, mousseux 1 215,130# cooler 416, bière 215, cidre 246, porto 227, vin de dessert 150, saké 131,131# apéritif 89, hydromel 35, poire 11, non alcoolisé 35.132CATEGORY_PAGES: list[tuple[str, int]] = [133    ("produits/vin", 5),134    ("produits/spiritueux", 3),135    ("produits/champagne-et-mousseux", 2),136    ("produits/biere", 2),137    ("produits/cidre", 2),138    ("produits/cooler-et-cocktail-premixe", 1),139    ("produits/porto-et-vin-fortifie", 1),140    ("produits/sake", 1),141    ("produits/vin-de-dessert", 1),142    ("produits/aperitif", 1),143    ("produits/hydromel", 1),144    ("produits/poire", 1),145    ("produits/article-non-alcoolise", 1),146]147148PAGE_SIZE = 200149MAX_PRODUCTS = int(os.environ.get("FOODKA_SAQ_MAX_PRODUCTS", "3400"))150151_QUERY = """152query FoodKa($phrase: String!, $pageSize: Int!, $currentPage: Int!,153             $filter: [SearchClauseInput!]) {154  productSearch(phrase: $phrase, page_size: $pageSize,155                current_page: $currentPage, filter: $filter) {156    total_count157    items {158      productView {159        sku160        name161        urlKey162        images { url }163        attributes { name value }164        ... on SimpleProductView {165          price {166            final { amount { value } }167            regular { amount { value } }168          }169        }170        ... on ComplexProductView {171          priceRange {172            minimum {173              final { amount { value } }174              regular { amount { value } }175            }176          }177        }178      }179    }180  }181}182"""183184# attributs SAQ conservés dans details (quand présents et non vides)185_KEEP_ATTRS = (186    "identite_produit", "pays_origine", "region", "appellation", "couleur",187    "cepage", "millesime_produit", "pastille_gout", "particularite",188    "designation_reglementee", "taux_alcool", "degre_alcool",189    "nom_producteur", "availability_front",190)191192193class SaqConnector(BaseConnector):194    source_id = "saq"195    request_delay = 1.0            # API partagée Adobe : politesse accrue196197    def _search_page(self, category_path: str, page: int) -> dict:198        payload = {199            "query": _QUERY,200            "variables": {201                "phrase": "", "pageSize": PAGE_SIZE, "currentPage": page,202                "filter": [{"attribute": "categoryPath", "eq": category_path}],203            },204        }205        resp = self.post(GRAPHQL_URL, json=payload, headers=STOREFRONT_HEADERS)206        data = resp.json()207        if data.get("errors"):208            raise RuntimeError(f"saq graphql: {data['errors'][:1]}")209        return (data.get("data") or {}).get("productSearch") or {}210211    def fetch(self) -> list[Product]:212        products: list[Product] = []213        seen: set[str] = set()214        for category_path, pages in CATEGORY_PAGES:215            for page in range(1, pages + 1):216                if len(products) >= MAX_PRODUCTS:217                    return products218                result = self._search_page(category_path, page)219                items = result.get("items") or []220                if not items:221                    break222                for item in items:223                    prod = self._to_product(item.get("productView") or {},224                                            category_path)225                    if prod is not None and prod.uid not in seen:226                        seen.add(prod.uid)227                        products.append(prod)228                total = result.get("total_count") or 0229                if page * PAGE_SIZE >= total:230                    break               # catégorie épuisée231        return products232233    # -- extraction d'une fiche productView -----------------------------------234    def _to_product(self, view: dict, category_path: str) -> Product | None:235        sku = clean_text(str(view.get("sku") or ""))236        name = clean_text(view.get("name") or "")237        if not sku or not name:238            return None239240        price, regular = self._prices(view)241        if price is None:242            return None                 # jamais de prix inventé243244        attrs: dict[str, object] = {}245        for att in view.get("attributes") or []:246            key, val = att.get("name"), att.get("value")247            if key and val not in (None, "", []):248                attrs[key] = val249250        size_label = self._size_label(attrs.get("format_contenant_ml"))251        availability = attrs.get("availability_front") or []252        if isinstance(availability, str):253            availability = [availability]254255        keywords = [clean_text(str(k)) for k in (256            attrs.get("couleur"), attrs.get("pastille_gout"),257            attrs.get("particularite")) if k]258        cepages = attrs.get("cepage")259        if isinstance(cepages, list):260            keywords += [clean_text(str(c)) for c in cepages if c]261        elif cepages:262            keywords.append(clean_text(str(cepages)))263264        details = {"code_saq": sku}265        for key in _KEEP_ATTRS:266            if key in attrs:267                details[key] = attrs[key]268        details["categorie_saq"] = category_path.split("/", 1)[-1]269270        url_key = clean_text(view.get("urlKey") or "") or sku271        images = [img.get("url") for img in (view.get("images") or [])272                  if img.get("url")]273274        return Product(275            source=self.source_id,276            external_id=sku,             # code SAQ277            url=f"https://www.saq.com/fr/{url_key}",278            name=name,279            brand=clean_text(str(attrs.get("nom_producteur") or "")),280            category="Alcool",281            category_raw=clean_text(str(attrs.get("identite_produit") or "")),282            size_label=size_label,283            price=price,284            regular_price=regular,285            price_label=f"{price:.2f} $".replace(".", ","),286            on_sale=regular is not None and regular > price,287            in_stock=("En ligne" in availability) or None,288            keywords=[k for k in keywords if k],289            details=details,290            images=[u.replace("http://", "https://") for u in images],291        )292293    @staticmethod294    def _prices(view: dict) -> tuple[float | None, float | None]:295        """(prix courant, prix régulier si supérieur) — Simple ou Complex."""296        node = view.get("price") or (view.get("priceRange") or {}).get("minimum") or {}297298        def amount(key: str) -> float | None:299            try:300                value = float(((node.get(key) or {}).get("amount") or {})["value"])301            except (KeyError, TypeError, ValueError):302                return None303            return value if 0 < value <= 2000 else None304305        final, regular = amount("final"), amount("regular")306        if regular is not None and final is not None and regular <= final:307            regular = None308        return final, regular309310    @staticmethod311    def _size_label(raw) -> str:312        """format_contenant_ml « 750 » -> « 750 ml », « 1500 » -> « 1,5 L »."""313        try:314            ml = float(str(raw).strip())315        except (TypeError, ValueError):316            return ""317        if ml <= 0:318            return ""319        if ml >= 1000:320            litres = ml / 1000321            return (f"{litres:g} L").replace(".", ",")322        return f"{ml:g} ml"323
Files main
Menu

Theme