SPB Git

Repository Public

squarespace.py 8.3 KB 187 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Fabri·Ka9# File             : fabrika/connectors/squarespace.py10# Module           : fabrika11# Repository       : https://git.spboucher.ai/fabri-ka12# Created          : 2026-08-1213# 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/squarespace.py : connecteur générique Squarespace Commerce —91#   pages collection en JSON natif (?format=json).92# -----------------------------------------------------------------------------93from __future__ import annotations9495from ..schema import Product, parse_price96from .base import BaseConnector979899class SquarespaceConnector(BaseConnector):100    platform = "squarespace"101102    def fetch(self) -> list[Product]:103        endpoint = (self.store.get("catalog_endpoint") or "/shop?format=json").split("?")[0]104        out: list[Product] = []105        page_url = f"{self.base}{endpoint}?format=json"106        for _ in range(self.max_pages):107            data = self.get(page_url).json()108            items = data.get("items", [])109            for it in items:110                sd = it.get("structuredContent") or {}111                variants = it.get("variants") or sd.get("variants") or []112113                def _money(v, key):114                    return parse_price((v.get(key) or {}).get("value")115                                       or v.get(key.replace("Money", "")))116                prices, compares = [], []117                vout, opt_values = [], {}118                any_stock = None119                for v in variants:120                    if not isinstance(v, dict):121                        continue122                    reg = _money(v, "priceMoney")123                    sale = _money(v, "salePriceMoney") if v.get("onSale") else None124                    eff = sale if sale and reg and sale < reg else reg125                    if eff:126                        prices.append(eff)127                    if sale and reg and sale < reg:128                        compares.append(reg)129                    attrs = v.get("attributes") or {}130                    for k, val in attrs.items():131                        opt_values.setdefault(str(k), [])132                        if str(val) not in opt_values[str(k)]:133                            opt_values[str(k)].append(str(val))134                    stock = v.get("stock") or {}135                    in_stock = bool(stock.get("unlimited")) or (stock.get("quantity") or 0) > 0136                    any_stock = in_stock if any_stock is None else (any_stock or in_stock)137                    if len(vout) < 20:138                        vd: dict = {"title": " / ".join(str(x) for x in attrs.values()) or (v.get("sku") or ""),139                                    "price": eff}140                        if v.get("sku"):141                            vd["sku"] = v["sku"]142                        if sale and reg and sale < reg:143                            vd["compare_at_price"] = reg144                        if stock:145                            vd["available"] = in_stock146                        vout.append(vd)147                if not prices:148                    prices = [parse_price((sd.get("priceMoney") or {}).get("value"))]149                    prices = [p for p in prices if p]150                det: dict = {}151                if vout:152                    det["variants"] = vout153                if opt_values:154                    det["options"] = [{"name": k, "values": vals[:30]}155                                      for k, vals in opt_values.items()]156                skus = [v.get("sku") for v in variants if isinstance(v, dict) and v.get("sku")]157                if skus:158                    det["sku"] = skus[0]159                if compares:160                    det["on_sale"] = True161                imgs = [it.get("assetUrl", "")]162                imgs += [im.get("assetUrl", "") for im in (it.get("items") or [])]163                desc = it.get("excerpt", "") or it.get("body", "") or ""164                sold_out = bool(sd.get("isSoldOut") or False)165                available = (not sold_out) if any_stock is None else (any_stock and not sold_out)166                out.append(Product(167                    store_id=self.store_id,168                    external_id=str(it.get("id", it.get("urlId", ""))),169                    url=f"{self.base}{it.get('fullUrl', '')}",170                    title=it.get("title", ""),171                    description=desc,172                    price=min(prices) if prices else None,173                    price_max=max(prices) if prices else None,174                    compare_at_price=max(compares) if compares else None,175                    images=[i for i in imgs if i],176                    tags=list(it.get("tags") or []) + list(it.get("categories") or []),177                    available=available,178                    details=det,179                ))180            pagination = data.get("pagination") or {}181            if not pagination.get("nextPage"):182                break183            page_url = f"{self.base}{endpoint}?format=json&offset={pagination.get('nextPageOffset','')}"184            if not pagination.get("nextPageOffset"):185                break186        return out187
Files main
Menu

Theme