Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Food·Ka9# File : foodka/connectors/akhavan.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 — connecteur Akhavan (akhavanfood.com — supermarché moyen-oriental,89# Montréal / NDG)90# Auteur : Simon-Pierre Boucher — contact@spboucher.ai91# WooCommerce : l'API Store publique (/wp-json/wc/store/v1/products) répond92# sans authentification — noms, prix (en cents, minor units), solde, stock,93# catégories et images. ~700 produits au total ; on pagine par 100 avec un94# plafond max_pages pour garder la synchro modeste. Aucun rendu JS requis.95# -----------------------------------------------------------------------------96from __future__ import annotations9798import html as _html99import re100101from bs4 import BeautifulSoup102103from ..normalize import format_unit_price, unit_price104from ..schema import Product, normalize_category105106BASE = "https://akhavanfood.com"107API = f"{BASE}/wp-json/wc/store/v1/products"108109from ._woocommerce import store_api_details110from .base import BaseConnector111112# format dans le nom : « Mix Shoor – Kambiz – 670 g (شور مخلوط) » -> « 670 g »113_SIZE_IN_NAME_RE = re.compile(114 r"(\d+(?:[.,]\d+)?)\s*(kg|g|gr|ml|l|lb|lbs|oz)\b", re.IGNORECASE)115116117def _minor(value: str | None, unit: int) -> float | None:118 """Prix WooCommerce Store API : chaîne en unités mineures (« 599 » = 5,99 $)."""119 if not value:120 return None121 try:122 price = int(value) / (10 ** unit)123 except ValueError:124 return None125 return price if price > 0 else None126127128class AkhavanConnector(BaseConnector):129 source_id = "akhavan"130131 per_page: int = 100132 # Store API gratuite et directe : plafond large (le catalogue ~700-900133 # produits était tronqué à exactement 400 avec l'ancien plafond de 4).134 max_pages: int = 12 # 12 x 100 = jusqu'à 1200 produits135136 def _parse_item(self, item: dict) -> Product | None:137 name = _html.unescape(item.get("name") or "").strip()138 if not name or not item.get("id"):139 return None140141 prices = item.get("prices") or {}142 unit = int(prices.get("currency_minor_unit") or 2)143 price = _minor(prices.get("price"), unit)144 regular = _minor(prices.get("regular_price"), unit)145 if price is None:146 return None # pas de prix affiché = produit inutilisable147148 cats = [_html.unescape(c.get("name") or "")149 for c in (item.get("categories") or [])]150 category_raw = " / ".join(c for c in cats if c)151152 brands = item.get("brands") or []153 brand = _html.unescape(brands[0].get("name") or "") if brands else ""154155 m = _SIZE_IN_NAME_RE.search(name)156 size_label = ""157 if m:158 u = m.group(2).lower()159 size_label = f"{m.group(1)} {'g' if u == 'gr' else u}"160161 desc_html = item.get("short_description") or ""162 description = BeautifulSoup(desc_html, "html.parser").get_text(163 " ", strip=True) if desc_html else ""164165 images = [img.get("src") for img in (item.get("images") or [])166 if img.get("src")]167168 # prix unitaire : si le nom ne porte pas de format, le poids catalogue169 # (`formatted_weight` inclut l'unité, ex. « 885 g ») fiabilise le $/100 g170 fw = item.get("formatted_weight") or ""171 if fw in ("N/A", "n/a"):172 fw = ""173 unit_p, unit_label = None, ""174 if not size_label and fw:175 up = unit_price(price, fw)176 if up:177 unit_p, unit_label = up[0], format_unit_price(up)178179 return Product(180 source=self.source_id,181 external_id=str(item["id"]),182 url=item.get("permalink") or f"{BASE}/?p={item['id']}",183 name=name,184 brand=brand,185 category=normalize_category(category_raw),186 category_raw=category_raw,187 size_label=size_label,188 price=price,189 regular_price=regular if regular and price and regular > price else None,190 on_sale=bool(item.get("on_sale")),191 unit_price=unit_p,192 unit_price_label=unit_label,193 in_stock=item.get("is_in_stock"),194 description=description,195 details=store_api_details(item),196 images=images[:3],197 )198199 def fetch(self) -> list[Product]:200 products: list[Product] = []201 seen: set[str] = set()202 for page in range(1, self.max_pages + 1):203 try:204 data = self.get(205 API, params={"per_page": self.per_page, "page": page}).json()206 except Exception: # une page qui casse ne bloque pas le reste207 break208 if not isinstance(data, list) or not data:209 break210 for item in data:211 prod = self._parse_item(item)212 if prod is not None and prod.uid not in seen:213 seen.add(prod.uid)214 products.append(prod)215 if len(data) < self.per_page:216 break217 return products218