# Datei: dashboard_engine.py # VERSION: Phönix 5.11 (Fix: Full Logic + Stable Module Import) import json import os import time import re from datetime import datetime, timedelta import sys import random import requests from bs4 import BeautifulSoup import warnings import subprocess import concurrent.futures import base64 import sqlite3 # --- STABILER IMPORT (Zirkelbezug-Schutz) --- # Wir importieren das Modul als Objekt ('drm'). # Das verhindert "Cannot import name"-Fehler während der Initialisierung. try: import deal_radar_masterplan as drm HAS_MASTERPLAN = True except ImportError as e: # Nur warnen, nicht abstürzen (damit Webserver trotzdem startet) print(f"Warning: Masterplan-Logik nicht geladen: {e}") HAS_MASTERPLAN = False warnings.filterwarnings('ignore', message='Unverified HTTPS request') # --- PFAD KONFIGURATION --- if os.path.exists("/data"): BASE_DIR = "/data" else: BASE_DIR = os.path.dirname(os.path.abspath(__file__)) DB_FILE = os.path.join(BASE_DIR, "radar.db") # ##### START: LOGGING ##### class Logger: def __init__(self, filename="scan.log"): self.log_path = os.path.join(BASE_DIR, filename) self.terminal_out = sys.stdout self.log = open(self.log_path, "a", encoding='utf-8', buffering=1) def write(self, message): self.terminal_out.write(message) try: self.log.write(message) self.log.flush() os.fsync(self.log.fileno()) except: pass def flush(self): self.terminal_out.flush() try: self.log.flush(); os.fsync(self.log.fileno()) except: pass sys.stdout = Logger() sys.stderr = sys.stdout # ##### ENDE LOGGING ##### # --- KONSTANTEN --- FULL_SCAN_RESULT_KEY = "last_full_scan" QUICK_SCAN_RESULT_KEY = "last_quick_scan" CHECKED_DEALS_KEY = "checked_deals" UNAVAILABLE_TRACKER_KEY = "unavailable_asin_tracker" ROTATION_STATE_KEY = "scan_pointer" TS_LAST_MAIN_KEY = "ts_last_main" TS_LAST_QUICK_KEY = "ts_last_quick" MYDEALZ_FILE = "mydealz_deals.json" MISMATCH_FILE = "mismatches.json" # --- DATENBANK HELPER (STANDALONE) --- def get_db_connection(): """Stellt eine eigene Verbindung her, unabhängig vom Masterplan Import""" try: conn = sqlite3.connect(DB_FILE, timeout=30) conn.row_factory = sqlite3.Row return conn except Exception as e: print(f"!! DB Connection Error in Dashboard Engine: {e}") return None def db_init(): print("-> Initialisiere Datenbank-Schema...") conn = get_db_connection() if not conn: return try: cursor = conn.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS key_value_store (key TEXT PRIMARY KEY, json_data TEXT)") cursor.execute("""CREATE TABLE IF NOT EXISTS products (asin TEXT PRIMARY KEY, verified_name TEXT, source_article_url TEXT, source_article_slug TEXT, publication_date TEXT, source_score REAL)""") cursor.execute("""CREATE TABLE IF NOT EXISTS price_history (id INTEGER PRIMARY KEY AUTOINCREMENT, asin TEXT NOT NULL, date TEXT NOT NULL, price REAL NOT NULL, UNIQUE(asin, date))""") conn.commit() except Exception as e: print(f"DB Init Error: {e}") finally: conn.close() def db_load_json(key, default_value={}): conn = get_db_connection() if not conn: return default_value try: cursor = conn.cursor() cursor.execute("SELECT json_data FROM key_value_store WHERE key = ?", (key,)) result = cursor.fetchone() if result and result['json_data']: return json.loads(result['json_data']) return default_value except: return default_value finally: conn.close() def db_save_json(key, data): conn = get_db_connection() if not conn: return try: cursor = conn.cursor() json_data = json.dumps(data, indent=2, ensure_ascii=False) cursor.execute("INSERT OR REPLACE INTO key_value_store (key, json_data) VALUES (?, ?)", (key, json_data)) conn.commit() except Exception as e: print(f"DB Save Error: {e}") finally: conn.close() # --- ZEITSTEMPEL --- def save_scan_timestamp(scan_type): now_str = datetime.now().strftime('%d.%m.%Y um %H:%M Uhr') key = TS_LAST_MAIN_KEY if scan_type == "main" else TS_LAST_QUICK_KEY db_save_json(key, now_str) def get_amazon_timestamps(): return { "main": db_load_json(TS_LAST_MAIN_KEY, "Noch nie"), "quick": db_load_json(TS_LAST_QUICK_KEY, "Noch nie") } def get_mydealz_timestamp(): fp = os.path.join(BASE_DIR, MYDEALZ_FILE) if os.path.exists(fp): ts = os.path.getmtime(fp) return datetime.fromtimestamp(ts).strftime('%d.%m.%Y um %H:%M Uhr') return "Noch nie" # --- DATA HANDLING --- def load_price_history(): history = {}; conn = get_db_connection() if not conn: return {} try: cursor = conn.cursor() cursor.execute("SELECT asin, date, price FROM price_history ORDER BY date ASC"); rows = cursor.fetchall() for row in rows: if row['asin'] not in history: history[row['asin']] = [] history[row['asin']].append({"date": row['date'], "price": row['price']}) return history finally: conn.close() def update_price_history(deals): today = datetime.now().strftime('%Y-%m-%d'); new_entries = [] for deal in deals: if deal.get('final_price'): new_entries.append((deal['asin'], today, deal['final_price'])) if new_entries: conn = get_db_connection() if conn: try: cursor = conn.cursor() cursor.executemany("""INSERT INTO price_history (asin, date, price) VALUES (?, ?, ?) ON CONFLICT(asin, date) DO UPDATE SET price = excluded.price""", new_entries) conn.commit() finally: conn.close() return load_price_history() def load_master_product_list(): """Lädt NUR Amazon ASINs (Starten mit B0)""" conn = get_db_connection() if not conn: return {} try: cursor = conn.cursor() # FILTER: Nur Amazon IDs laden cursor.execute("SELECT * FROM products WHERE asin GLOB 'B0*'"); rows = cursor.fetchall() return {row['asin']: dict(row) for row in rows} finally: conn.close() def cleanup_expired_tracked_asins(): asin_tracker = db_load_json(UNAVAILABLE_TRACKER_KEY, {}) if not asin_tracker: return cutoff = datetime.now() - timedelta(days=30) expired = [a for a, d in asin_tracker.items() if datetime.strptime(d, '%Y-%m-%d') < cutoff] if expired: conn = get_db_connection() if conn: cursor = conn.cursor() cursor.executemany("DELETE FROM products WHERE asin = ?", [(a,) for a in expired]); conn.commit(); conn.close() cleaned = {a: d for a, d in asin_tracker.items() if a not in expired} db_save_json(UNAVAILABLE_TRACKER_KEY, cleaned) def save_full_scan_results(deals): db_save_json(FULL_SCAN_RESULT_KEY, deals) def save_quick_scan_results(deals): db_save_json(QUICK_SCAN_RESULT_KEY, deals) def load_checked_deals(): return db_load_json(CHECKED_DEALS_KEY, {}) def save_checked_deals(checked_deals): db_save_json(CHECKED_DEALS_KEY, checked_deals) def load_full_scan_results(): return db_load_json(FULL_SCAN_RESULT_KEY, None) def load_quick_scan_results(): return db_load_json(QUICK_SCAN_RESULT_KEY, None) def save_rotation_state(index): db_save_json(ROTATION_STATE_KEY, index) def load_rotation_state(): return db_load_json(ROTATION_STATE_KEY, 0) # --- HELPER: IDEALO SNIPER --- def _get_smart_idealo_query(amazon_title, slug): STOP_WORDS = ['test', 'review', 'bericht', 'erfahrung', 'angebot', 'deal', 'rabatt', 'coupon', 'gutschein', 'kaufen', 'preis', 'china', 'gadgets', 'video', 'vorstellung', 'hands-on', 'unboxing', 'saugroboter', 'wischsauger', 'maehroboter', 'rasenmaeher', 'roboter', 'staubsauger', 'akku', 'handstaubsauger', 'kabellos', 'smart', 'watch', 'fitness', 'tracker', '3d', 'lidar', 'laser', 'navigation', 'station', 'absaugstation', 'mit', 'ohne', 'gen', 'generation', 'neuheit', 'release', 'launch'] if slug and len(slug) > 3: clean_slug = slug.replace('-', ' ') words = [w for w in clean_slug.split() if w.lower() not in STOP_WORDS] if len(words) >= 1: return " ".join(words[:4]).title() if not amazon_title: return "" t = amazon_title; t = re.sub(r'\[.*?\]', '', t); t = re.sub(r'\(.*?\)', '', t) for sep in [' - ', ' | ', ', ', ' – ', ' : ']: if sep in t: t = t.split(sep)[0]; break words = [w for w in t.split() if w.lower() not in STOP_WORDS] return " ".join(words[:4]) # --- PREIS EXTRACTION --- PRICE_RE_EURO = re.compile(r'(?:€\s*|)\s*((?:\d{1,3}(?:[.\s]\d{3})*|\d+)(?:[.,]\d{1,2}|(?:\s*[-–])?)?)\s*(?:€|eur|euro)?', re.I) def _normalize_price_to_float(raw): if not raw: return None s = str(raw).replace('\xa0', ' ').replace('EUR', '').replace('eur', '').replace('Euro', '').replace('€', '').strip() s = re.sub(r'\s+', ' ', s); s = re.sub(r'\s*[-–]\s*$', '', s); s = s.replace(' ', '') if ',' in s and '.' in s: s = s.replace('.', '').replace(',', '.') elif ',' in s and '.' not in s: s = s.replace(',', '.') else: s = s.replace('.', '') try: return float(s) except: return None def get_cg_article_price(slug_or_html, product_name=None, current_amazon_price=None): # Fallback-Wrapper für Masterplan-Funktion if HAS_MASTERPLAN: # Hier nutzen wir das Modul-Objekt 'drm' statt direkt importierte Funktion return _get_cg_article_price_logic(slug_or_html, current_amazon_price) return None def _get_cg_article_price_logic(slug_or_html, current_amazon_price): # Hier kopieren wir die Logik der Preisfindung, damit sie autark ist # oder wir rufen drm.get_article_data_from_api auf BAD_PRICE_WORDS = re.compile(r'(uvp|statt|vorher|durchgestrichen|strikethrough|unverbindliche)', re.I) PROMO_HINTS_RE = re.compile(r'\b(jetzt|nur|für|heute|deal|angebot|zum angebot|reduziert)\b', re.I) FOREIGN_SHOPS = re.compile(r'(geekbuying|banggood|proshop|aliexpress|cafago|dhgate|edwaybuy|tomtop|zbanx|lightinthebox)', re.I) def _is_plausible_local(val, ref): if val is None or val < 3 or val > 10000: return False if ref is None: return True return (0.35 * ref) <= val <= (3.0 * ref) def _has_strike_or_badcontext(node): if node.find('del'): return True txt = (node.get_text(" ", strip=True) or '') if BAD_PRICE_WORDS.search(txt) and not PROMO_HINTS_RE.search(txt): return True return False def _is_foreign_context(node): txt = (node.get_text(" ", strip=True) or '') return bool(FOREIGN_SHOPS.search(txt)) def _score(candidate_price, distance_level, ctx_text, ref, source=""): proximity_weight = {0: 1.0, 1: 0.85, 2: 0.7, 3: 0.55}.get(distance_level, 0.6) if isinstance(ref, (int, float)) and ref > 0: rel = abs(candidate_price - ref) / ref; near = max(0.2, 1.0 - rel) else: near = 0.6 return proximity_weight * near def _load_html(s): if '<' in str(s) and ' 0] if prices_before_today: current_price = deal.get('final_price', 0) all_time_low = min(p['price'] for p in prices_before_today) if current_price < all_time_low: deal['sort_priority'] = 1 elif current_price == all_time_low: deal['sort_priority'] = 2 analyzed_deals.append(deal) analyzed_deals.sort(key=lambda x: x.get('sort_priority', 99)) return analyzed_deals def analyze_and_sort_deals_deep(deals, history, fast_resort=False): """Tiefe Analyse NACH dem Scan""" analyzed_deals = [] today_str = datetime.now().strftime('%Y-%m-%d') checked_deals_data = load_checked_deals() deals_to_uncheck = [] cg_prices = [None] * len(deals) if not fast_resort and HAS_MASTERPLAN: print("-> [Analyse] Hole Artikel-Preise (Parallel)...") tasks = [{"slug": d.get('source_article_slug'), "name": d.get('verified_name'), "price": d.get('final_price', 0)} for d in deals] with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor: cg_prices = list(executor.map(lambda t: get_cg_article_price(t["slug"], t["name"], t["price"]), tasks)) for i, deal in enumerate(deals): if deal.get('final_price') is None: continue deal.setdefault('is_checked_off', False); deal.setdefault('sort_priority', 9) current_price = deal.get('final_price', 0) if deal['asin'] in checked_deals_data: check_info = checked_deals_data[deal['asin']] checked_at = datetime.fromisoformat(check_info['checked_at']) price_at_check = check_info['price_at_check'] if current_price < (price_at_check * 0.95): deals_to_uncheck.append(deal['asin']) elif datetime.now() > checked_at + timedelta(days=28): deals_to_uncheck.append(deal['asin']) else: deal['sort_priority'] = 999; deal['is_checked_off'] = True deal['analysis_text'] = f"Abgehakt {checked_at.strftime('%d.%m.')}" else: deal['is_checked_off'] = False if deal['is_checked_off']: analyzed_deals.append(deal); continue deal.update({'trend_icon': '⚪️', 'trend_title': 'Neu', 'trend_color_class': 'icon-new', 'savings_percent': 'Neu', 'savings_color_class': '', 'analysis_text': 'Keine Historie', 'reference_price': 0, 'reference_price_source': 'none'}) # CG Price integration cg_price = cg_prices[i] if (not fast_resort and cg_prices) else None if cg_price and cg_price > 0: deal.update({'reference_price_source': 'article', 'reference_price': cg_price}) if current_price < cg_price: deal.update({'trend_icon': '▼', 'trend_color_class': 'arrow-down'}) elif current_price > cg_price: deal.update({'trend_icon': '▲', 'trend_color_class': 'arrow-up'}) if current_price < (cg_price * 0.95): deal.update({'analysis_text': f'🔥 Top vs. Artikel ({cg_price:.0f}€)', 'sort_priority': 0}) else: deal['analysis_text'] = f"Artikel: {cg_price:.2f}€" if cg_price > 0: deal['savings_percent'] = f"{((current_price / cg_price) - 1) * 100:.1f}%" if deal['asin'] in history: hist = history[deal['asin']] prices_before = [p for p in hist if p['date'] != today_str] if prices_before: last_price = prices_before[-1]['price'] all_time_low = min(p['price'] for p in prices_before) if deal['reference_price'] == 0: deal['reference_price'] = last_price; deal['reference_price_source'] = 'history' if current_price < last_price: deal.update({'trend_icon': '▼', 'trend_color_class': 'arrow-down'}) elif current_price > last_price: deal.update({'trend_icon': '▲', 'trend_color_class': 'arrow-up'}) else: deal.update({'trend_icon': '-', 'trend_color_class': 'icon-stable'}) if last_price > 0: deal['savings_percent'] = f"{((current_price / last_price) - 1) * 100:.1f}%" if deal['sort_priority'] > 0: if current_price < all_time_low: deal.update({'analysis_text': '🔥 All-Time-Low!', 'sort_priority': 1}) elif current_price == all_time_low: deal.update({'analysis_text': '🔥 Bestpreis gehalten', 'sort_priority': 2}) try: deal['savings_numeric'] = float(deal.get('savings_percent', '0').replace('%', '')) except: deal['savings_numeric'] = 0.0 analyzed_deals.append(deal) if deals_to_uncheck: for asin in deals_to_uncheck: if asin in checked_deals_data: del checked_deals_data[asin] save_checked_deals(checked_deals_data) analyzed_deals.sort(key=lambda x: (x.get('is_checked_off', False), x.get('sort_priority', 99), x.get('savings_numeric', 0))) return analyzed_deals def select_products_for_hotlist_scan(all_deals_last_scan, history): print("-> [Phönix 3.1] Smart-Targeting (Strict Efficiency)...") master_list = load_master_product_list() checked_deals = load_checked_deals() # WICHTIG: Abgehakte laden # Limits für den Quick-Scan (damit er 'Quick' bleibt) TARGET_COUNT = 90 CAP_FRESH = 30 CAP_VOLATILE = 30 # Der Rest (mind. 30 Slots) ist für Rotation reserviert batch = [] seen_asins = set() # Blacklist Keywords (Müll rausfiltern) IGNORE_KEYWORDS = ["baby", "plüsch", "kuscheltier", "netzkabel", "stromkabel", "kaltgerätestecker", "verlängerungskabel", "tamper", "kaffeezubehör", "kaffeefilter", "vicloon", "deleycon", "schutzfolie", "panzerglas", "hülle", "case", "schrauben", "dübel", "werkzeugkoffer"] def is_valid_candidate(item): asin = item['asin'] # 1. Dubletten-Check if asin in seen_asins: return False # 2. Abgehakt-Check (Das ist Prio C!) # Wenn abgehakt -> NICHT im Quick-Scan. Der Main-Scan kümmert sich um Reaktivierung. if asin in checked_deals: return False # 3. Keyword-Check name = (item.get('verified_name') or "").lower() if any(bad in name for bad in IGNORE_KEYWORDS): return False return True def add_to_batch(item): if len(batch) >= TARGET_COUNT: return False batch.append(item) seen_asins.add(item['asin']) return True # Volatilitäts-Rechner (Robust gegen DB-Fehler) def get_volatility_score(asin): if not history or asin not in history: return 0 try: entries = history[asin] if not entries or len(entries) < 3: return 3 # Zweifel für den Angeklagten (neu = interessant) # Prüfe Varianz der letzten 10 Preise prices = [e['price'] for e in entries[-10:] if e['price'] > 0] if not prices: return 0 # Simpler Score: Anzahl der Preisänderungen changes = 0 for k in range(1, len(prices)): if abs(prices[k] - prices[k-1]) > 0.5: changes += 1 return changes except: return 0 all_products = list(master_list.values()) # --- BUCKET 1: FRESHNESS (Max 30) --- # Alles was jünger als 10 Tage ist cutoff_fresh = (datetime.now() - timedelta(days=10)).strftime('%Y-%m-%d') fresh_candidates = [p for p in all_products if str(p.get('publication_date') or '1970') >= cutoff_fresh] # Sortiere Fresh nach Datum (neueste zuerst) fresh_candidates.sort(key=lambda x: str(x.get('publication_date')), reverse=True) count_fresh = 0 for item in fresh_candidates: if count_fresh >= CAP_FRESH: break if is_valid_candidate(item): if add_to_batch(item): count_fresh += 1 print(f" -> Bucket 1 (Fresh): {count_fresh} Items") # --- BUCKET 2: VOLATILITY (Max 30) --- # Finde Produkte, die oft den Preis ändern volatile_candidates = [] for p in all_products: if p['asin'] not in seen_asins and is_valid_candidate(p): score = get_volatility_score(p['asin']) if score >= 2: # Mindestens 2 Änderungen in letzter Zeit volatile_candidates.append((score, p)) # Sortiere nach Score (höchste Volatilität zuerst) volatile_candidates.sort(key=lambda x: x[0], reverse=True) count_vol = 0 for score, item in volatile_candidates: if count_vol >= CAP_VOLATILE: break if add_to_batch(item): count_vol += 1 print(f" -> Bucket 2 (Volatile): {count_vol} Items") # --- BUCKET 3: ROTATION (Auffüllen bis voll) --- # Klassische Rotation durch den Restbestand all_sorted_date = sorted(all_products, key=lambda x: str(x.get('publication_date') or '1970'), reverse=True) start_idx = load_rotation_state() if start_idx >= len(all_sorted_date): start_idx = 0 curr_idx = start_idx loops = 0 # Wir loopen maximal 1x durch die ganze Liste while len(batch) < TARGET_COUNT and loops < len(all_sorted_date): item = all_sorted_date[curr_idx] if is_valid_candidate(item): add_to_batch(item) curr_idx += 1 if curr_idx >= len(all_sorted_date): curr_idx = 0 loops += 1 save_rotation_state(curr_idx) print(f"-> [Smart Select] {len(batch)} Produkte final. (Rotation ab Index {start_idx})") return batch def filter_deals_by_age(deals, max_age_days=730): cutoff = datetime.now() - timedelta(days=max_age_days); filtered = [] for d in deals: pub = d.get('publication_date') if not pub: filtered.append(d); continue try: if datetime.fromisoformat(pub.replace('Z', '+00:00')).replace(tzinfo=None) >= cutoff: filtered.append(d) except: filtered.append(d) return filtered # --- DASHBOARD RENDERING (RESTORED FULL) --- def render_html_layout(page_content, scan_type, theme_color, active_module, status_html="", extra_head_content=""): title = "CG Preis-Radar" tabs = f""" Amazon AliExpress Mydealz """ return f"""{title}{extra_head_content}

{title}

{status_html}

{scan_type}

{page_content}
""" def render_dashboard_html(deals, scan_type, is_full_report=False): ts = get_amazon_timestamps() status_html = f"Main: {ts['main']} | Quick: {ts['quick']}" link = 'Zurück' if is_full_report else 'Archiv' backup_html = """
💾 Backup: Abgehakt | Blacklist | ⚠️ Fehler-Log | Datenbank
""" actions = f"""
{link}
Logs
{backup_html} """ js = """""" # Safe Rendering try: rows = generate_table_rows(deals) except Exception as e: rows = f"Rendering Error: {e}" table = f"""{rows}
#TrendProduktPreisCouponEndpreisCG-PreisErsparnisAnalyseArtikel
""" return render_html_layout(actions + table, scan_type, "#00A8E1", "amazon", status_html, js) def render_mydealz_html(deals, checked_urls): ts = get_mydealz_timestamp() status_html = f"Letztes Update: {ts}" backup_html = """
💾 Backup: Abgehakt | Liste | 🍪 Cookies
""" actions = f"""
Update Mydealz
Logs
{backup_html}""" deals.sort(key=lambda d: d.get('link','') in checked_urls) js = """""" rows = "" for i, d in enumerate(deals, 1): is_chk = d.get('link') in checked_urls b64 = base64.urlsafe_b64encode(d.get('link','').encode()).decode() link = f"{'[Reaktivieren]' if is_chk else '[Abhaken]'}" temp = d.get('temperature','0°'); temp_val = 0 try: temp_val = int(temp.replace('°','').replace('.','')) except: pass rows += f"""{i}
{link}{temp}{d.get('title')}{d.get('price')}{d.get('shop')}Link""" table = f"""{rows}
#TempTitelPreisShopLink
""" return render_html_layout(actions + table, "Mydealz", "#87c540", "mydealz", status_html, js) def generate_table_rows(deals): # Lade Liste der gemeldeten Fehler für Visual Feedback reported_map = {} base_dir = "/data" if os.path.exists("/data") else os.path.dirname(os.path.abspath(__file__)) mismatch_path = os.path.join(base_dir, MISMATCH_FILE) if os.path.exists(mismatch_path): try: raw_data = json.load(open(mismatch_path)) for item in raw_data: asin = item.get('asin') e_type = item.get('error_type', 'product_mismatch') if asin not in reported_map: reported_map[asin] = [] reported_map[asin].append(e_type) except: pass rows = [] for index, deal in enumerate(deals, 1): # FIX: Safe .get() Access asin = deal.get('asin', 'N/A') full_name = deal.get('verified_name', 'N/A') # Filter (Safe) if "404" in full_name or "Nicht gefunden" in full_name or "Redirect" in full_name: continue if len(full_name) > 55: full_name = full_name[:55] + '...' pub_date = "unbekannt" if deal.get('publication_date'): try: pub_date = datetime.fromisoformat(deal['publication_date'].replace('Z', '+00:00')).strftime('%b %Y') except: pass bsr_val = deal.get('bsr') bsr_info = f"
BSR: #{bsr_val:,}".replace(',', '.') if bsr_val and bsr_val != 999999 else "" info = f"
ASIN: {asin} | {pub_date}{bsr_info}
" p_raw = deal.get('price', 0); c_raw = deal.get('coupon_details', 'N/A') try: p_float = float(p_raw) except: p_float = 0.0 is_unavail = (p_float <= 0.01) or (c_raw == "Nicht verfügbar") if is_unavail: continue price_h = f"{p_float:.2f}€" s_price = p_float c_val = 0.0 if c_raw != "Kein Coupon" and c_raw: if m := re.search(r'([\d.,]+)€', str(c_raw)): try: c_val = float(m.group(1).replace('.','').replace(',','.')) except: pass c_h = str(c_raw).replace("Checkbox-Coupon (€):", "Coupon:") else: c_h = "-" s_coup = c_val final = deal.get('final_price',0) end_h = f"{final:.2f}€"; s_final = final sav = deal.get('savings_percent','0'); sav_h = sav; s_sav = 0; sav_cls = "savings-neutral" if sav != 'Neu' and sav: try: s_sav = float(str(sav).replace('%','')) if s_sav < -0.1: sav_cls = "savings-green" elif s_sav > 0.1: sav_cls = "savings-red" except: pass ref = deal.get('reference_price', 0); ref_h = f"{ref:.2f}€" if deal.get('reference_price_source') == 'history': ref_h = f"{ref:.2f}€" cls = "checked-off-row" if deal.get('is_checked_off') else ("best-price-row" if deal.get('sort_priority', 9) <= 3 else "") act = f"[Reaktivieren]" if deal.get('is_checked_off') else f"[Abhaken]" ana = deal.get('analysis_text','') or "-" clean_title = _get_smart_idealo_query(deal.get('verified_name', ''), deal.get('source_article_slug', '')) idealo_link = f"https://www.idealo.de/preisvergleich/MainSearchProductCategory.html?q={clean_title}" if clean_title else f"https://www.idealo.de/preisvergleich/MainSearchProductCategory.html?q={asin}" keepa_link = f"https://keepa.com/#!product/3-{asin}" ana_h = f"""
{ana}
📈 : K I
""" slug = deal.get('source_article_slug', ''); art_n = slug.replace('-', ' ').title()[:15] + "..." if slug else "Artikel" reports = reported_map.get(asin, []) if 'product_mismatch' in reports: btn_prod = "✅ Produkt gemeldet" else: btn_prod = f"⚠️ Produkt falsch?" if 'price_error' in reports: btn_price = "✅ Preis gemeldet" else: btn_price = f"💸 Preis falsch?" report_area = f"
{btn_prod}{btn_price}
" rows.append(f"""{index}
{act}{deal.get('trend_icon','-')}{full_name}{info}{price_h}{c_h}{end_h}{ref_h}{sav_h}{ana_h}{art_n}{report_area}""") return "".join(rows) if __name__ == '__main__': db_init(); cleanup_expired_tracked_asins(); start_time = time.time() if "--rebuild-master-list" in sys.argv: print("--- REBUILD ---"); conn = get_db_connection(); conn.execute("DELETE FROM products"); conn.commit(); conn.close() # FIX: Sicherer Aufruf über Modul-Objekt drm if HAS_MASTERPLAN: drm.update_master_product_list(); sys.exit() else: print("!! Masterplan Modul fehlt. Abbruch."); sys.exit() if "--quick" in sys.argv: print(f"\n--- QUICK SCAN START ({datetime.now().strftime('%H:%M:%S')}) ---") if not HAS_MASTERPLAN: print("!! Masterplan Modul fehlt. Scan nicht möglich."); sys.exit() last = load_full_scan_results() if not last: print("!! Kein Full-Scan."); sys.exit() rel = filter_deals_by_age(last, 730); hist = load_price_history() pre = analyze_and_sort_deals(rel, hist); hot = select_products_for_hotlist_scan(pre, hist) # Aufruf über Modul-Alias drm live, _ = drm.check_prices_of_master_list(hot) if live: hist = update_price_history(live) fin = analyze_and_sort_deals_deep(live or [], hist) save_quick_scan_results(fin); save_scan_timestamp("quick") elif "--main" in sys.argv or len(sys.argv) == 1: print(f"\n--- MAIN SCAN START ({datetime.now().strftime('%H:%M:%S')}) ---") if not HAS_MASTERPLAN: print("!! Masterplan Modul fehlt. Scan nicht möglich."); sys.exit() drm.update_master_product_list(); master = load_master_product_list() scan = filter_deals_by_age(list(master.values()), 730) live, success = drm.check_prices_of_master_list(scan); hist = load_price_history() if live: hist = update_price_history(live) fin = analyze_and_sort_deals_deep(live, hist) if success: save_full_scan_results(fin); drm.save_current_scan_time(); save_scan_timestamp("main") else: save_full_scan_results(fin) print(f"\n=== Ende nach {timedelta(seconds=int(time.time()-start_time))} ===")