Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Fabri·Ka9# File : fabrika/connectors/square.py10# Module : fabrika11# Repository : https://git.spboucher.ai/fabri-ka12# Created : 2026-08-1813# 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/square.py : connecteur générique Square Online (Weebly).91# Les sites Square Online exposent une API JSON publique côté storefront :92# /app/store/api/v13/editor/users/<user_id>/sites/<site_id>/products93# Les identifiants user_id / site_id sont imprimés dans le HTML de chaque94# page (config JS `user_id: '…'` / `site_id: '…'`). Pagination via95# meta.pagination.total_pages, 100 produits/page.96# -----------------------------------------------------------------------------97from __future__ import annotations9899import re100101from ..schema import Product, parse_price102from .base import BaseConnector103104# le HTML expose les IDs sous deux formes (config JS et JSON embarqué)105_USER_RES = [re.compile(r"user_id: '(\d+)'"), re.compile(r'"user_id":"?(\d+)')]106_SITE_RES = [re.compile(r"site_id: '(\d+)'"), re.compile(r'"site_id":"?(\d+)')]107108API_PATH = "/app/store/api/v13"109110111def extract_ids(html: str) -> tuple[str | None, str | None]:112 """(user_id, site_id) depuis le HTML d'une page Square Online."""113 user = site = None114 for rx in _USER_RES:115 m = rx.search(html)116 if m:117 user = m.group(1)118 break119 for rx in _SITE_RES:120 m = rx.search(html)121 if m:122 site = m.group(1)123 break124 return user, site125126127class SquareConnector(BaseConnector):128 platform = "square"129 request_delay = 0.5130131 def _ids(self) -> tuple[str, str]:132 r = self.get(self.base + "/")133 user, site = extract_ids(r.text)134 if not (user and site):135 raise RuntimeError("IDs Square Online (user_id/site_id) introuvables dans le HTML")136 return user, site137138 def fetch(self) -> list[Product]:139 user, site = self._ids()140 out: list[Product] = []141 page = 1142 while page <= self.max_pages:143 # include=images,options : galerie complète + variantes dans la même144 # requête paginée (levée du « mono-image » sans requête supplémentaire)145 url = (f"{self.base}{API_PATH}/editor/users/{user}/sites/{site}"146 f"/products?page={page}&per_page=100&include=images,options")147 data = self.get(url).json()148 items = data.get("data") or []149 for it in items:150 if (it.get("visibility") or "visible") != "visible":151 continue152 price = it.get("price") or {}153 low = parse_price(price.get("low"))154 high = parse_price(price.get("high"))155 reg_high = parse_price(price.get("regular_high"))156 on_sale = bool(it.get("on_sale"))157 badges = it.get("badges") or {}158 inv = it.get("inventory") or {}159 available = not (badges.get("out_of_stock")160 or inv.get("all_variations_sold_out"))161 thumb = ((it.get("thumbnail") or {}).get("data") or {})162 img = thumb.get("absolute_url")163 images: list[str] = []164 for rec in ((it.get("images") or {}).get("data") or []):165 u = rec.get("absolute_url") or ""166 if u and not u.startswith("http"):167 u = "https://" + u.lstrip("/")168 if u and u not in images:169 images.append(u)170 if not images and img:171 images = [img if img.startswith("http") else "https://" + img.lstrip("/")]172 det: dict = {}173 opts = []174 for o in ((it.get("options") or {}).get("data") or []):175 name = o.get("name") or ""176 if name:177 opts.append({"name": name,178 "values": [str(c) for c in (o.get("choice_order") or [])]})179 if opts:180 det["options"] = opts181 try:182 if float(it.get("avg_rating") or 0) > 0:183 det["average_rating"] = float(it["avg_rating"])184 except (TypeError, ValueError):185 pass186 if on_sale:187 det["on_sale"] = True188 if it.get("is_alcoholic"):189 det["is_alcoholic"] = True190 if it.get("sku"):191 det["sku"] = str(it["sku"])192 if it.get("rating_count"):193 try:194 det["review_count"] = int(it["rating_count"])195 except (TypeError, ValueError):196 pass197 for k in ("created_date", "updated_date"):198 if it.get(k):199 det[k] = it[k]200 site_link = (it.get("site_link") or "").lstrip("/")201 out.append(Product(202 store_id=self.store_id,203 external_id=str(it.get("id") or it.get("square_id") or ""),204 url=f"{self.base}/{site_link}" if site_link else self.base,205 title=it.get("name", "") or "",206 description=(it.get("short_description")207 or it.get("seo_page_description") or ""),208 price=low,209 price_max=high if high and low and high > low else low,210 compare_at_price=(reg_high if on_sale and reg_high211 and reg_high > (high or 0) else None),212 images=images,213 product_type=it.get("product_type", "") or "",214 available=available,215 details=det,216 ))217 pag = (data.get("meta") or {}).get("pagination") or {}218 if page >= int(pag.get("total_pages") or page):219 break220 page += 1221 return out222