SPB Git

Repository Public

backfill_closures.py 6.0 KB 155 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : Fabri·Ka10# File             : scripts/backfill_closures.py11# Description      : Backfill du statut « présumée fermée » depuis l'historique12#                    sync_log.13# Module           : scripts14# Repository       : https://git.spboucher.ai/fabri-ka15# Created          : 2026-08-1916# Last Modified    : 2026-08-1917#18# =============================================================================19# AUTHOR & PROFESSIONAL AFFILIATION20# =============================================================================21#22# Author           : Simon-Pierre Boucher23# Position         : Professor of Finance24# Institution      : Université du Québec en Outaouais (UQO)25# Department       : Département des sciences administratives26# Organization     : SP Boucher27#28# Website          : https://spboucher.ai29# Git              : https://git.spboucher.ai30#31# =============================================================================32# OFFICIAL CONTACT DIRECTORY33# =============================================================================34#35# General          : info@spboucher.ai36# Professional     : contact@spboucher.ai37# Direct           : simon@spboucher.ai38# Research         : research@spboucher.ai39# Development      : dev@spboucher.ai40# Support          : support@spboucher.ai41# Security/Admin   : admin@spboucher.ai42# Notifications    : notifications@spboucher.ai43#44# Preferred Contact: contact@spboucher.ai45#46# =============================================================================47# COPYRIGHT & INTELLECTUAL PROPERTY48# =============================================================================49#50# Copyright (c) 202651# Simon-Pierre Boucher52#53# All rights reserved where applicable.54#55# This file is governed by the applicable project license,56# copyright notices, institutional agreements and relevant law.57#58# Unless expressly authorized by the applicable license or59# rights holder, copying, redistribution, sublicensing,60# publication and commercial exploitation are not permitted.61#62# Existing third-party rights and notices remain unaffected.63#64# =============================================================================65# CONFIDENTIALITY & SECURITY66# =============================================================================67#68# Classification   : Public69# Distribution     : Public repository; use is governed by the project license70# Security Contact : admin@spboucher.ai71#72# Access to this source does not independently grant permission73# to redistribute or disclose confidential materials.74#75# Do not embed credentials, private keys, access tokens,76# certificates or confidential personal information.77#78# =============================================================================79# LICENSE & MAINTENANCE80# =============================================================================81#82# License          : None specified (no license file in this repository)83# Maintainer       : Simon-Pierre Boucher84# Technical Contact: dev@spboucher.ai85#86# =============================================================================87# END OF SP BOUCHER SOURCE HEADER88# =============================================================================8990"""Backfill du statut « présumée fermée » depuis l'historique sync_log.9192Le mécanisme durable vit dans fabrika/ingest.py (compteur fail_streak,93seuil CLOSE_AFTER_FAILS, réintégration automatique au premier sync réussi).94Ce script rejoue l'historique existant : pour chaque boutique activée, on95compte les échecs consécutifs depuis le dernier sync réussi ; au-delà du96seuil, statut appliqué + produits dépubliés (réversible).9798Usage : .venv/bin/python scripts/backfill_closures.py [--dry-run]99"""100import argparse101import sys102from pathlib import Path103104ROOT = Path(__file__).resolve().parent.parent105sys.path.insert(0, str(ROOT))106107from fabrika import db                       # noqa: E402108from fabrika.ingest import CLOSE_AFTER_FAILS  # noqa: E402109110111def main():112    ap = argparse.ArgumentParser()113    ap.add_argument("--dry-run", action="store_true")114    args = ap.parse_args()115116    con = db.connect()117    stores = con.execute(118        "SELECT id, name, product_count FROM stores "119        "WHERE enabled=1 AND catalog_endpoint<>''").fetchall()120    closed, updated = [], 0121    for sid, name, pc in stores:122        rows = con.execute(123            "SELECT status FROM sync_log WHERE store_id=? "124            "ORDER BY ts DESC LIMIT 100", (sid,)).fetchall()125        streak = 0126        for (status,) in rows:127            if status == "error":128                streak += 1129            elif status == "ok":130                break131            # presumed_closed / autres statuts : neutres132        con.execute("UPDATE stores SET fail_streak=? WHERE id=?", (streak, sid))133        updated += 1134        if streak >= CLOSE_AFTER_FAILS:135            closed.append((sid, name, streak, pc))136            if not args.dry_run:137                con.execute("UPDATE stores SET presumed_closed=1, product_count=0 "138                            "WHERE id=?", (sid,))139                con.execute("UPDATE products SET active=0 WHERE store_id=?", (sid,))140                db.log_sync(con, sid, 0, 0, 0, 0, "presumed_closed",141                            f"backfill historique : {streak} échecs consécutifs")142    if not args.dry_run:143        con.commit()144    con.close()145    print(f"fail_streak recalculé pour {updated} boutiques")146    print(f"présumées fermées ({'dry-run' if args.dry_run else 'appliqué'}) : "147          f"{len(closed)}")148    for sid, name, streak, pc in closed:149        print(f"  - {sid} «{name}» : {streak} échecs consécutifs, "150              f"{pc} produits dépubliés")151152153if __name__ == "__main__":154    main()155
Files main
Menu

Theme