""" app.py ─ Fenix Inventory Tracker FastAPI backend with Supabase Cloud DB, Background tasks, Overview & Sparkline Chart KORJAUS (thread exhaustion): - Playwright-haut (_fetch) ajetaan ENNEN tämän muutosta FastAPI:n threadpoolissa ilman rajoitusta. Kun background batch (20 profiilia) pyöri samaan aikaan tavallisten HTTP-pyyntöjen kanssa, threadeja loppui kesken kontista -> "RuntimeError: can't start new thread" -> koko app kaatui (myös "/"). - KORJAUS: yksi globaali threading.Semaphore rajoittaa montako Playwright- selainta voi olla auki SAMANAIKAISESTI (oletus: 1). Background batch ja manuaaliset /api/scrape -kutsut jonottavat saman semaforin takana, joten threadeja ei voi koskaan karata käsistä. BACKGROUND CHECKER LOGIIKKA: - Käynnistyksessä: skannataan BATCH_SIZE vanhinta profiilia (last_checked ASC) - Sen jälkeen joka tunti: skannataan BATCH_SIZE vanhinta joiden last_checked > 14h - Tauot: 3-7s satunnainen väli per skannaus - Poisto: jos profiilissa ei muutosta 7 päivään → poistetaan suoraan - Näin tuhansia profiileja ei yritetä skannata yhdellä kertaa """ from __future__ import annotations import os import re import time import json import random import asyncio import threading from pathlib import Path from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException from fastapi.responses import FileResponse, JSONResponse from fastapi.staticfiles import StaticFiles from pydantic import BaseModel from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeout from supabase import create_client, Client # ══════════════════════════════════════════════════════════════════════════════ # CONFIG & SUPABASE SETUP # ══════════════════════════════════════════════════════════════════════════════ API_KEYWORDS = ["v3?app_id=730", "inventory?", "app_id=730", "/inventory/"] CNY_TO_USD = 0.14 # Kuinka monta profiilia skannataan per ajokerta BATCH_SIZE = 20 # Kuinka monta sekuntia odotetaan skannausten välissä (satunnainen väli) DELAY_MIN = 3 DELAY_MAX = 6 # Kuinka usein background_checker ajetaan (sekunteina) CHECK_INTERVAL = 1800 # 30 minuuttia # Profiilien uudelleenskannauksen kynnys (sekunteina) RESCAN_THRESHOLD = 50400 # 14h DELETE_THRESHOLD = 604800 # 7 päivää # ── THREAD-EXHAUSTION KORJAUS ───────────────────────────────────────────────── # Montako Playwright-selainta saa olla auki SAMAAN AIKAAN koko prosessissa. # Pienissä konteissa (esim. HuggingFace free CPU) tämä pitää pitää PIENENÄ (1-2), # koska jokainen Chromium-instanssi + sen anyio-threadit syövät threadbudjettia. MAX_CONCURRENT_BROWSERS = 1 _browser_semaphore = threading.Semaphore(MAX_CONCURRENT_BROWSERS) USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", ] SUPABASE_URL = os.environ.get("SUPABASE_URL", "").strip().rstrip("/") SUPABASE_KEY = os.environ.get("SUPABASE_KEY", "").strip() def _validate_supabase_url(url: str) -> str: if not url: return url if "supabase.com/dashboard" in url: ref = url.rstrip("/").split("/")[-1] corrected = f"https://{ref}.supabase.co" print(f"⚠️ SUPABASE_URL oli dashboard-linkki! Korjattu: {corrected}") return corrected return url SUPABASE_URL = _validate_supabase_url(SUPABASE_URL) supabase: Client = None if SUPABASE_URL and SUPABASE_KEY: try: supabase = create_client(SUPABASE_URL, SUPABASE_KEY) print(f"✅ Supabase yhdistetty: {SUPABASE_URL}") except Exception as e: print(f"❌ Supabase-yhteys epäonnistui: {e}") else: print("⚠️ SUPABASE_URL tai SUPABASE_KEY puuttuu!") # ══════════════════════════════════════════════════════════════════════════════ # SUPABASE DATABASE LOGIC # ══════════════════════════════════════════════════════════════════════════════ def _calculate_diff(old_items, new_items): old_counts = {} for item in old_items: name = item.get('name', 'Unknown') old_counts[name] = old_counts.get(name, 0) + 1 new_counts = {} for item in new_items: name = item.get('name', 'Unknown') new_counts[name] = new_counts.get(name, 0) + 1 gained, lost = [], [] total_gained, total_lost = 0, 0 all_keys = set(old_counts.keys()).union(set(new_counts.keys())) for k in all_keys: diff = new_counts.get(k, 0) - old_counts.get(k, 0) if diff > 0: gained.append({"name": k, "amount": diff}) total_gained += diff elif diff < 0: lost.append({"name": k, "amount": abs(diff)}) total_lost += abs(diff) gained = sorted(gained, key=lambda x: x['amount'], reverse=True) lost = sorted(lost, key=lambda x: x['amount'], reverse=True) return gained, lost, total_gained, total_lost def _update_profile_data(resolved_url: str, force: bool = False): if not supabase: raise RuntimeError("Supabase-yhteys puuttuu. Tarkista SUPABASE_URL ja SUPABASE_KEY.") resolved_url = resolve_steam_url(resolved_url) now = time.time() res = supabase.table("profiles").select("*").eq("url", resolved_url).execute() row = res.data[0] if res.data else None if row and not force: if now - row['last_checked'] < RESCAN_THRESHOLD: return json.loads(row['items_json']), True steamdt_url = f"https://www.steamdt.com/en/inventory/inventory?search={resolved_url}" raw = _fetch(steamdt_url) if not raw: raise RuntimeError( "Ei saatu dataa SteamDT:ltä. Tili voi olla yksityinen, tyhjä, " "tai inventaario ei sisällä CS2-esineitä." ) new_items = _parse(raw) if not new_items: print(f"DEBUG: Raw data keys: {list(raw.keys()) if isinstance(raw, dict) else type(raw)}") if isinstance(raw, dict): data = raw.get("data", raw) if isinstance(data, dict): print(f"DEBUG: data keys: {list(data.keys())}") raise RuntimeError( "Inventaariosta ei löytynyt CS2-esineitä. " "Profiili voi olla yksityinen tai inventaario tyhjä." ) new_items_json = json.dumps(new_items) if row: old_items = json.loads(row['items_json']) last_changed = row['last_changed'] status = row['status'] if new_items_json != row['items_json']: gained, lost, tg, tl = _calculate_diff(old_items, new_items) supabase.table("daily_changes").insert({ "url": resolved_url, "change_time": now, "total_gained": tg, "total_lost": tl, "gained_json": json.dumps(gained), "lost_json": json.dumps(lost) }).execute() supabase.table("profiles").update({ "status": "active", "last_checked": now, "last_changed": now, "items_json": new_items_json }).eq("url", resolved_url).execute() else: if now - last_changed > DELETE_THRESHOLD: print(f"🗑️ Poistetaan inaktiivinen profiili: {resolved_url} (ei muutosta {(now - last_changed)/86400:.1f} päivään)") supabase.table("profiles").delete().eq("url", resolved_url).execute() return new_items, False else: supabase.table("profiles").update({ "status": "active", "last_checked": now }).eq("url", resolved_url).execute() else: supabase.table("profiles").insert({ "url": resolved_url, "status": "active", "last_checked": now, "last_changed": now, "items_json": new_items_json }).execute() return new_items, False def _get_stale_profiles(limit: int = BATCH_SIZE) -> list[dict]: if not supabase: return [] threshold = time.time() - RESCAN_THRESHOLD try: res = ( supabase.table("profiles") .select("url, status, last_checked, last_changed") .lt("last_checked", threshold) .order("last_checked", desc=False) .limit(limit) .execute() ) return res.data or [] except Exception as e: print(f"⚠️ _get_stale_profiles virhe: {e}") return [] def _run_batch_check(): if not supabase: return profiles = _get_stale_profiles(BATCH_SIZE) if not profiles: print("✅ Background check: kaikki profiilit ajan tasalla (alle 14h vanha), ei skannattavaa.") return print(f"🔄 Background batch: skannataan {len(profiles)} profiilia (BATCH_SIZE={BATCH_SIZE})") for i, row in enumerate(profiles): url = row['url'] last_checked = row['last_checked'] last_changed = row.get('last_changed', last_checked) age_checked = (time.time() - last_checked) / 3600 age_changed = (time.time() - last_changed) / 86400 print(f" [{i+1}/{len(profiles)}] {url}") print(f" last_checked: {age_checked:.1f}h sitten | last_changed: {age_changed:.1f}pv sitten") try: _update_profile_data(url, force=True) print(f" ✅ OK") except Exception as e: print(f" ❌ Epäonnistui: {e}") try: supabase.table("profiles").update({ "last_checked": time.time() }).eq("url", url).execute() except Exception: pass if i < len(profiles) - 1: delay = random.uniform(DELAY_MIN, DELAY_MAX) time.sleep(delay) print(f"✅ Batch valmis. Seuraava ajo {CHECK_INTERVAL // 60} min kuluttua.") async def background_checker(): await asyncio.sleep(10) print("=" * 60) print(f"🚀 BACKGROUND CHECKER KÄYNNISTYY") print(f" BATCH_SIZE={BATCH_SIZE} | CHECK_INTERVAL={CHECK_INTERVAL}s ({CHECK_INTERVAL//60}min)") print(f" RESCAN_THRESHOLD={RESCAN_THRESHOLD//3600}h | DELETE_THRESHOLD={DELETE_THRESHOLD//86400}pv") print(f" MAX_CONCURRENT_BROWSERS={MAX_CONCURRENT_BROWSERS}") print("=" * 60) if supabase: try: now = time.time() threshold = now - RESCAN_THRESHOLD total_res = supabase.table("profiles").select("url", count="exact").execute() stale_res = supabase.table("profiles").select("url", count="exact").lt("last_checked", threshold).execute() total = total_res.count or 0 stale = stale_res.count or 0 eta_h = (stale / BATCH_SIZE) * (CHECK_INTERVAL / 3600) if BATCH_SIZE > 0 else 0 print(f"📊 Profiileja: {total} | Vanhentuneita: {stale} | ETA: ~{eta_h:.1f}h") except Exception as e: print(f"⚠️ Tilakyselyssä virhe: {e}") while True: stale_count = 0 if supabase: try: threshold = time.time() - RESCAN_THRESHOLD res = supabase.table("profiles").select("url", count="exact").lt("last_checked", threshold).execute() stale_count = res.count or 0 except Exception: pass if stale_count == 0: print(f"✅ [{time.strftime('%H:%M:%S')}] Kaikki profiilit ajan tasalla. Seuraava tarkistus {CHECK_INTERVAL//60}min kuluttua.") await asyncio.sleep(CHECK_INTERVAL) else: print(f"\n⏰ [{time.strftime('%H:%M:%S')}] {stale_count} vanhentunutta profiilia — käynnistetään batch...") try: await asyncio.to_thread(_run_batch_check) except Exception as e: print(f"⚠️ Batch epäonnistui: {e}") if stale_count > BATCH_SIZE: await asyncio.sleep(60) else: await asyncio.sleep(CHECK_INTERVAL) @asynccontextmanager async def lifespan(app: FastAPI): if not supabase: print("WARNING: SUPABASE_URL or SUPABASE_KEY not set!") task = asyncio.create_task(background_checker()) yield task.cancel() # ══════════════════════════════════════════════════════════════════════════════ # SCRAPING HELPERS (PLAYWRIGHT) # ══════════════════════════════════════════════════════════════════════════════ def resolve_steam_url(url: str) -> str: url = url.strip() if not url.startswith("http"): url = "https://" + url url = url.split('?')[0].split('#')[0].rstrip('/') if url.lower().endswith('/inventory'): url = url[:-10] if "/id/" in url: parts = url.split("/id/") if len(parts) == 2 and re.match(r"^\d{17}$", parts[1]): url = parts[0] + "/profiles/" + parts[1] print(f"🔧 URL automaattisesti korjattu: {url}") return url def _cny_usd(val) -> float: try: return float(val) * CNY_TO_USD if val else 0.0 except (ValueError, TypeError): return 0.0 def _tag(tags, prefix: str, strip: str = "") -> str: for t in tags: if isinstance(t, str): if t.startswith(prefix + "#"): raw = t.split("#", 1)[-1] return raw.replace(strip, "").replace("_", " ").title() elif isinstance(t, dict): cat = t.get("category", "") or t.get("categoryName", "") or "" val = t.get("value", "") or t.get("internalName", "") or "" if cat.lower() == prefix.lower(): return val.replace(strip, "").replace("_", " ").title() loc = t.get("localizedTagName", "") or t.get("name", "") or "" if cat.lower() == prefix.lower() and loc: return loc return "" def _apply_stealth(page) -> None: page.add_init_script(""" Object.defineProperty(navigator, 'webdriver', { get: () => undefined }); Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] }); Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4] }); window.chrome = { runtime: {} }; """) def _parse(api_data: dict) -> list[dict]: if not api_data: return [] items_list = [] classinfos = {} block = api_data.get("data", api_data) if isinstance(block, dict): inv = block.get("inventory", {}) if isinstance(inv, dict): items_list = inv.get("assets", []) or inv.get("items", []) or [] classinfos = inv.get("classinfos", {}) or inv.get("descriptions", {}) or {} elif isinstance(inv, list): items_list = inv if not items_list: items_list = block.get("assets", []) or block.get("items", []) or block.get("list", []) or [] if not classinfos: classinfos = block.get("classinfos", {}) or block.get("descriptions", {}) or {} elif isinstance(block, list): items_list = block classinfos = api_data.get("classinfos", {}) or {} if items_list and isinstance(items_list[0], dict): if "market_hash_name" in items_list[0] or "marketHashName" in items_list[0] or "name" in items_list[0]: return _parse_direct_items(items_list) out = [] for item in items_list: if not isinstance(item, dict): continue aid = str(item.get("assetId", item.get("asset_id", item.get("id", "")))) if not aid or aid == "None": continue key = str(item.get("classinfoKey", item.get("classinfo_key", item.get("classId", item.get("class_id", ""))))) info = {} if classinfos: info = classinfos.get(key, {}) if not info and isinstance(classinfos, list): for ci in classinfos: if str(ci.get("classId", ci.get("class_id", ""))) == key: info = ci break tags = info.get("tags", []) or item.get("tags", []) name = ( info.get("marketHashName") or info.get("market_hash_name") or info.get("hashName") or info.get("name") or item.get("marketHashName") or item.get("market_hash_name") or item.get("name") or f"Unknown ({key})" ) price_raw = ( item.get("evaluatePrice") or item.get("price") or item.get("steamPrice") or item.get("steam_price") or 0 ) price = _cny_usd(price_raw) rarity = _tag(tags, "Rarity", "Rarity_") or _tag(tags, "rarity", "Rarity_") or "Normal" quality = _tag(tags, "Quality", "Quality_") or "Normal" wtype = _tag(tags, "Type", "Type_") or _tag(tags, "Weapon", "") or info.get("type", "") or "" itype = "StatTrak" if "StatTrak™" in name else "Souvenir" if "Souvenir" in name else "Normal" is_knife = "Knife" in wtype or any(k in name for k in ("★", "Karambit", "Butterfly", "M9 Bayonet", "Bayonet", "Flip Knife", "Gut Knife")) is_glove = "Glove" in wtype or "Gloves" in name out.append({ "assetId": aid, "name": name, "price": price, "rarity": rarity, "quality": quality, "type": itype, "weaponType": wtype, "isKnife": is_knife, "isGlove": is_glove }) return out def _parse_direct_items(items_list: list) -> list[dict]: out = [] for item in items_list: if not isinstance(item, dict): continue name = ( item.get("marketHashName") or item.get("market_hash_name") or item.get("hashName") or item.get("name") or "Unknown" ) price_raw = item.get("evaluatePrice") or item.get("price") or item.get("steamPrice") or 0 price = _cny_usd(price_raw) tags = item.get("tags", []) rarity = _tag(tags, "Rarity", "Rarity_") or item.get("rarity", "Normal") wtype = _tag(tags, "Type", "Type_") or item.get("type", "") or item.get("weaponType", "") itype = "StatTrak" if "StatTrak™" in name else "Souvenir" if "Souvenir" in name else "Normal" is_knife = "Knife" in wtype or any(k in name for k in ("★", "Karambit", "Butterfly", "Bayonet")) is_glove = "Glove" in wtype or "Gloves" in name aid = str(item.get("assetId") or item.get("asset_id") or item.get("id") or "") out.append({ "assetId": aid, "name": name, "price": price, "rarity": rarity, "quality": item.get("quality", "Normal"), "type": itype, "weaponType": wtype, "isKnife": is_knife, "isGlove": is_glove }) return out def _fetch(url: str, retries: int = 3) -> dict | None: """ THREAD-EXHAUSTION KORJAUS: _browser_semaphore varmistaa että korkeintaan MAX_CONCURRENT_BROWSERS Chromium-instanssia on auki samaan aikaan koko prosessissa. Tämä estää background-batchin ja manuaalisten /api/scrape -kutsujen yhdessä syömästä kaikkia käytettävissä olevia OS-threadeja kontista. Muut kutsut jonottavat tässä, mutta eivät enää kaada koko sovellusta. """ with _browser_semaphore: for attempt in range(retries): try: with sync_playwright() as p: browser = p.chromium.launch(headless=True, args=[ "--disable-blink-features=AutomationControlled", "--disable-dev-shm-usage", "--no-sandbox", "--single-process", # vähentää käynnistettävien OS-threadien määrää "--disable-gpu", ]) ctx = browser.new_context( user_agent=random.choice(USER_AGENTS), viewport={"width": 1920, "height": 1080}, locale="en-US" ) page = ctx.new_page() _apply_stealth(page) page.route("**/*.{png,jpg,jpeg,gif,svg,webp,woff,woff2}", lambda r: r.abort()) captured = None captured_url = None def on_response(resp): nonlocal captured, captured_url for kw in API_KEYWORDS: if kw in resp.url and resp.request.method != "OPTIONS": try: if resp.status == 200: json_data = resp.json() if isinstance(json_data, dict) and ( "data" in json_data or "assets" in json_data or "inventory" in json_data or "items" in json_data ): captured = json_data captured_url = resp.url print(f"✅ Captured: {resp.url}") elif isinstance(json_data, list) and len(json_data) > 0: captured = {"data": json_data} captured_url = resp.url print(f"✅ Captured list: {resp.url}") except Exception as e: print(f"Response parse error: {e}") break page.on("response", on_response) page.goto(url, wait_until="domcontentloaded", timeout=60_000) page.mouse.move(random.randint(200, 900), random.randint(200, 700)) page.evaluate("window.scrollTo(0, document.body.scrollHeight)") for _ in range(120): if captured: break page.wait_for_timeout(500) browser.close() if captured: return captured else: print(f"⚠️ Yritys {attempt+1}: ei API-vastausta kohteesta {url}") except PlaywrightTimeout: print(f"⚠️ Timeout yritys {attempt+1}") except Exception as e: print(f"Fetch Error (yritys {attempt+1}): {e}") time.sleep(2) return None # ══════════════════════════════════════════════════════════════════════════════ # FASTAPI APP & ENDPOINTS # ══════════════════════════════════════════════════════════════════════════════ app = FastAPI(title="Fenix Inventory API", lifespan=lifespan) if Path("static").exists(): app.mount("/static", StaticFiles(directory="static"), name="static") @app.get("/") def serve_index(): return FileResponse("index.html") @app.get("/Fenix_red_and_orange.png") def serve_logo(): if Path("Fenix_red_and_orange.png").exists(): return FileResponse("Fenix_red_and_orange.png", media_type="image/png") return JSONResponse({"error": "Image not found"}, status_code=404) @app.get("/api/health") def health_check(): if not supabase: return JSONResponse({ "supabase": False, "url_configured": bool(SUPABASE_URL), "key_configured": bool(SUPABASE_KEY), "hint": "SUPABASE_URL pitää olla muodossa https://.supabase.co" }, status_code=503) try: supabase.table("profiles").select("url").limit(1).execute() return JSONResponse({"supabase": True, "url": SUPABASE_URL}) except Exception as e: return JSONResponse({"supabase": False, "error": str(e)}, status_code=503) @app.get("/api/bg_status") def bg_status(): if not supabase: return JSONResponse({"error": "No Supabase"}, status_code=503) now = time.time() threshold = now - RESCAN_THRESHOLD try: total = supabase.table("profiles").select("url", count="exact").execute() stale = supabase.table("profiles").select("url", count="exact").lt("last_checked", threshold).execute() return JSONResponse({ "total_profiles": total.count, "stale_profiles": stale.count, "up_to_date": (total.count or 0) - (stale.count or 0), "batch_size": BATCH_SIZE, "check_interval_h": CHECK_INTERVAL / 3600, "rescan_threshold_h": RESCAN_THRESHOLD / 3600, "max_concurrent_browsers": MAX_CONCURRENT_BROWSERS, }) except Exception as e: return JSONResponse({"error": str(e)}, status_code=500) @app.post("/api/debug_fetch") def debug_fetch(req: dict): steam_url = req.get("steam_url", "") if not steam_url: raise HTTPException(400, "steam_url required") resolved = resolve_steam_url(steam_url) steamdt_url = f"https://www.steamdt.com/en/inventory/inventory?search={resolved}" raw = _fetch(steamdt_url) if not raw: return JSONResponse({"error": "No data captured", "url": steamdt_url}) def summarize(obj, depth=0): if depth > 3: return "..." if isinstance(obj, dict): return {k: summarize(v, depth+1) for k, v in list(obj.items())[:10]} if isinstance(obj, list): return [summarize(obj[0], depth+1), f"...({len(obj)} items)"] if obj else [] return obj return JSONResponse({"structure": summarize(raw), "top_keys": list(raw.keys()) if isinstance(raw, dict) else "list"}) class ScrapeRequest(BaseModel): steam_url: str force: bool = False @app.post("/api/scrape") def scrape(req: ScrapeRequest): if not supabase: raise HTTPException(500, "Supabase-avaimia ei ole asetettu. Tarkista /api/health.") if "steamcommunity.com" not in req.steam_url: raise HTTPException(400, "Viallinen linkki. Tarvitaan 'steamcommunity.com'") resolved_url = resolve_steam_url(req.steam_url) try: items, cached = _update_profile_data(resolved_url, force=req.force) except RuntimeError as e: raise HTTPException(502, str(e)) except Exception as e: raise HTTPException(502, f"Datan haku epäonnistui: {e}") if not items: raise HTTPException(404, "Inventaariosta ei löytynyt CS2-esineitä.") return JSONResponse({ "items": items, "count": len(items), "resolved_url": resolved_url, "cached": cached }) @app.get("/api/tracked_urls") def get_tracked_urls(): if not supabase: return JSONResponse({"urls": []}) try: res = supabase.table("profiles").select("url").execute() urls = [r['url'] for r in res.data] return JSONResponse({"urls": urls}) except Exception as e: return JSONResponse({"error": str(e)}, status_code=500) @app.get("/api/recent_changes") def get_recent_changes(): if not supabase: return JSONResponse({"changes": []}) res = supabase.table("daily_changes").select("*").order("change_time", desc=True).limit(100).execute() out = [] for r in res.data: out.append({ "url": r['url'], "time": r['change_time'], "total_gained": r['total_gained'], "total_lost": r['total_lost'], "gained": json.loads(r['gained_json'] or "[]"), "lost": json.loads(r['lost_json'] or "[]") }) return JSONResponse({"changes": out}) @app.get("/api/overview") def get_overview(): if not supabase: return JSONResponse({"overview": []}) limit_time = time.time() - 86400 res = supabase.table("daily_changes").select("url, gained_json").gt("change_time", limit_time).execute() agg = {} for r in res.data: gained = json.loads(r['gained_json'] or "[]") for item in gained: name = item['name'] amount = item['amount'] if name not in agg: agg[name] = {"amount": 0, "urls": set()} agg[name]["amount"] += amount agg[name]["urls"].add(r['url']) out = [{"name": name, "amount": data["amount"], "accounts": len(data["urls"])} for name, data in agg.items()] out = sorted(out, key=lambda x: x["amount"], reverse=True) return JSONResponse({"overview": out}) @app.get("/api/daily_chart") def get_daily_chart(): if not supabase: return JSONResponse({"chart": [{"gained": 0, "lost": 0} for _ in range(24)]}) now = time.time() limit_time = now - 86400 res = supabase.table("daily_changes").select("change_time, total_gained, total_lost").gt("change_time", limit_time).execute() buckets = [{"gained": 0, "lost": 0} for _ in range(24)] for r in res.data: t = r['change_time'] hour_diff = int((now - t) / 3600) if 0 <= hour_diff < 24: idx = 23 - hour_diff buckets[idx]["gained"] += r['total_gained'] buckets[idx]["lost"] += r['total_lost'] return JSONResponse({"chart": buckets}) @app.get("/api/account_changes") def get_account_changes(url: str, days: int = 1): if not supabase: return JSONResponse({"gained": [], "lost": [], "total_gained": 0, "total_lost": 0}) now = time.time() limit_time = now - (days * 86400) res = ( supabase.table("daily_changes") .select("gained_json, lost_json") .eq("url", url) .gt("change_time", limit_time) .execute() ) all_gained: dict[str, int] = {} all_lost: dict[str, int] = {} for r in res.data: for item in json.loads(r["gained_json"] or "[]"): all_gained[item["name"]] = all_gained.get(item["name"], 0) + item["amount"] for item in json.loads(r["lost_json"] or "[]"): all_lost[item["name"]] = all_lost.get(item["name"], 0) + item["amount"] gained_list = sorted([{"name": k, "amount": v} for k, v in all_gained.items()], key=lambda x: x["amount"], reverse=True) lost_list = sorted([{"name": k, "amount": v} for k, v in all_lost.items()], key=lambda x: x["amount"], reverse=True) return JSONResponse({ "gained": gained_list, "lost": lost_list, "total_gained": sum(all_gained.values()), "total_lost": sum(all_lost.values()), }) # ── Portfolio endpoints ────────────────────────────────────────────────────── class PortfolioImportRequest(BaseModel): user_id: str items: list[dict] @app.post("/api/portfolio/import") def portfolio_import(req: PortfolioImportRequest): if not supabase: raise HTTPException(500, "Supabase ei yhteydessä") counts: dict[str, dict] = {} for item in req.items: name = item.get("name", "Unknown") price = float(item.get("price", item.get("avg_price", 0)) or 0) if name not in counts: counts[name] = {"quantity": 0, "total_price": 0.0} counts[name]["quantity"] += 1 counts[name]["total_price"] += price now = time.time() result_items = [] for name, data in counts.items(): qty = data["quantity"] avg_price = data["total_price"] / qty if qty else 0 row = { "user_id": req.user_id, "item_name": name, "quantity": qty, "avg_price": round(avg_price, 4), "updated_at": now, } supabase.table("portfolio").upsert(row, on_conflict="user_id,item_name").execute() result_items.append({"item_name": name, "quantity": qty, "avg_price": round(avg_price, 4)}) result_items.sort(key=lambda x: x["quantity"] * x["avg_price"], reverse=True) return JSONResponse({"items": result_items, "count": len(result_items)}) @app.get("/api/portfolio/portfolio/{user_id}") def portfolio_get(user_id: str): if not supabase: raise HTTPException(500, "Supabase ei yhteydessä") try: res = supabase.table("portfolio").select("*").eq("user_id", user_id).execute() items = [ {"item_name": r["item_name"], "quantity": r["quantity"], "avg_price": r["avg_price"]} for r in (res.data or []) ] items.sort(key=lambda x: x["quantity"] * x["avg_price"], reverse=True) return JSONResponse({"items": items}) except Exception as e: raise HTTPException(500, str(e))