Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Fabri·Ka9# File : fabrika/connectors/immunotec.py10# Module : fabrika11# Repository : https://git.spboucher.ai/fabri-ka12# Created : 2026-08-2413# Last Modified : 2026-08-2814#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# Fabri-Ka — Agrégateur de produits québécois89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/immunotec.py : storefront sur mesure Immunotec (Vaudreuil-Dorion) —91# Next.js + backend Exigo (scus-back2.immunotec.com). Le site et son API sont92# derrière un challenge Cloudflare : tout passe par Scrapfly ASP. Catalogue93# public = « mur produits » de la catégorie « Tous les produits »94# (POST categories/product-wall, header api-key "/"). Les prix n'existent que95# dans cette API (rendu client), jamais dans le HTML SSR ni en JSON-LD.96# -----------------------------------------------------------------------------97from __future__ import annotations9899import json100import re101import unicodedata102103from ..schema import Product, parse_price104from .base import BaseConnector105from .scrapfly import scrapfly_get, scrapfly_post106107API_BASE = "https://scus-back2.immunotec.com/"108WALL_PATH = "categories/product-wall"109API_HEADERS = {"api-key": "/"} # valeur littérale codée dans le bundle du site110# webCategoryId de « Tous les produits » (pageProps.productCategory de111# /fr-CA/products) — redécouvert dynamiquement si le mur revient vide112ALL_CATEGORY_ID = 2139113LOC_RE = re.compile(r"<loc>\s*(.*?)\s*</loc>", re.I | re.S)114115116def _slugify(s: str) -> str:117 s = unicodedata.normalize("NFKD", s or "").encode("ascii", "ignore").decode()118 return re.sub(r"-+", "-", re.sub(r"[^a-z0-9]+", "-", s.lower())).strip("-")119120121def _compact(s: str) -> str:122 return re.sub(r"[^a-z0-9]", "", (s or "").lower())123124125class ImmunotecConnector(BaseConnector):126 platform = "immunotec"127128 def _wall(self, category_id: int, culture: str) -> list[dict]:129 body = {"countryCode": "CA", "cultureCode": culture,130 "categoryId": category_id, "isConsultant": False,131 "downlineCustomerId": 0, "isShareCart": False,132 "isEnrollment": False}133 status, content = scrapfly_post(API_BASE + WALL_PATH, body,134 headers=API_HEADERS)135 if status != 200:136 raise RuntimeError(f"immunotec product-wall {status}")137 data = json.loads(content)138 return ((data.get("records") or {}).get("items") or []) if data.get("status") else []139140 def _all_category_id(self) -> int:141 """Relit le webCategoryId « Tous les produits » depuis la page du mur."""142 status, html = scrapfly_get(f"{self.base}/fr-CA/products")143 if status == 200:144 m = re.search(r'"slug":\s*"all".{0,400}?"customerWebCategoryId":\s*"?(\d+)', html) \145 or re.search(r'"customerWebCategoryId":\s*"?(\d+)"?.{0,400}?"slug":\s*"all"', html)146 if m:147 return int(m.group(1))148 return ALL_CATEGORY_ID149150 def _product_slugs(self) -> dict[str, str]:151 """Slugs fr-CA du sitemap produits (slug -> URL de fiche)."""152 url = f"{self.base}/products-sitemap.xml"153 xml = ""154 try:155 r = self.session.get(url, timeout=self.timeout)156 if r.status_code == 200:157 xml = r.text158 except Exception: # noqa: BLE001 — Cloudflare : on escalade159 pass160 if "<loc>" not in xml:161 try:162 status, xml = scrapfly_get(url)163 if status != 200:164 xml = ""165 except Exception: # noqa: BLE001 — les fiches sont optionnelles166 xml = ""167 return {loc.rsplit("/", 1)[-1]: loc168 for loc in LOC_RE.findall(xml) if "/fr-CA/products/" in loc}169170 @staticmethod171 def _match_slug(item: dict, titles: list[str], slugs: dict[str, str]) -> str | None:172 sku_digits = (item.get("sku") or "").lstrip("0")173 cands = [_slugify(t) for t in titles if t]174 for c in cands:175 if c in slugs:176 return slugs[c]177 if len(sku_digits) >= 4:178 for slug, loc in slugs.items():179 if sku_digits in _compact(slug):180 return loc181 for c in cands:182 cc = _compact(c)183 if len(cc) < 6:184 continue185 for slug, loc in slugs.items():186 sc = _compact(slug)187 if len(sc) >= 6 and (cc.startswith(sc) or sc.startswith(cc)):188 return loc189 return None190191 def fetch(self) -> list[Product]:192 items = self._wall(ALL_CATEGORY_ID, "fr-CA")193 if not items:194 items = self._wall(self._all_category_id(), "fr-CA")195 if not items:196 return []197 # titres anglais : les slugs de fiches sont dérivés des noms EN198 try:199 en_titles = {i.get("sku"): (i.get("titleDescription") or i.get("name"))200 for i in self._wall(ALL_CATEGORY_ID, "en-CA")}201 except Exception: # noqa: BLE001 — enrichissement d'URL seulement202 en_titles = {}203 slugs = self._product_slugs()204 wall_url = f"{self.base}/fr-CA/products"205 out: list[Product] = []206 for it in items:207 sku = str(it.get("sku") or "").strip()208 if not sku:209 continue210 title = it.get("titleDescription") or it.get("name") or ""211 price = parse_price(it.get("priceRetail") or it.get("price"))212 url = self._match_slug(it, [title, en_titles.get(sku, "")], slugs) \213 if slugs else None214 out.append(Product(215 store_id=self.store_id,216 external_id=sku,217 url=url or wall_url,218 title=title,219 description=it.get("description") or "",220 price=price,221 price_max=price,222 images=[it["imageUrl"]] if it.get("imageUrl") else [],223 product_type=it.get("itemType") or "",224 available=True,225 ))226 return out227