DeepImagix commited on
Commit
ae078a5
Β·
verified Β·
1 Parent(s): e66ec4f

Upload 2 files

Browse files
Files changed (2) hide show
  1. polar_subs_studio.py +842 -0
  2. studio_generate.py +301 -76
polar_subs_studio.py ADDED
@@ -0,0 +1,842 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ NeuraPrompt Studio β€” Polar Subscription Checker (multi-plan)
3
+ ============================================================
4
+
5
+ Separate from Kype's polar_subscription.py.
6
+
7
+ Studio has THREE paid tiers (plus free):
8
+ free β€” default, limited builds / no Fix / no Plan
9
+ pro β€” $12/mo β€” download, 5 builds, 25k tokens; Fix/Plan OFF
10
+ max β€” $29/mo β€” everything in Pro + Fix + Plan, 10 builds, 500k tokens
11
+ business β€” custom β€” Pro+Max combined limits, teams, priority
12
+
13
+ This module:
14
+ * Calls Polar /subscriptions/ and maps product β†’ studio plan id
15
+ * Returns entitlements the Studio frontend needs (canFix, canPlan, builds, …)
16
+ * Webhook handler upserts Mongo + clears cache so the UI can refresh after pay
17
+ * Diagnose / invalidate helpers for "I paid but still free"
18
+
19
+ Env vars (Studio-specific; can share the same Polar org as Kype if products differ):
20
+ POLAR_API_KEY β€” Polar PAT (subscriptions:read; checkouts:write if creating sessions)
21
+ POLAR_ORG_ID β€” Polar organization id
22
+ POLAR_WEBHOOK_SECRET β€” webhook signing secret
23
+ POLAR_STUDIO_PRODUCT_PRO β€” optional product id for Pro (preferred over name match)
24
+ POLAR_STUDIO_PRODUCT_MAX β€” optional product id for Max
25
+ POLAR_STUDIO_PRODUCT_BIZ β€” optional product id for Business
26
+ FIREBASE_KEY_PATH β€” service account json (default: serviceAccountKey.json)
27
+
28
+ Mount on your FastAPI app, e.g.:
29
+ from polar_subs_studio import studio_polar_router, handle_studio_polar_webhook
30
+ app.include_router(studio_polar_router)
31
+ # webhook: POST /studio/polar/webhook (or /webhooks/polar-studio)
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import os
37
+ import time
38
+ import hmac
39
+ import json
40
+ import hashlib
41
+ import logging
42
+ from dataclasses import dataclass, field, asdict
43
+ from datetime import datetime, timezone
44
+ from typing import Optional, Dict, Any, List, Tuple
45
+
46
+ import httpx
47
+ from fastapi import APIRouter, HTTPException, Request, Query
48
+ from fastapi.responses import JSONResponse
49
+
50
+ log = logging.getLogger("polar.studio")
51
+
52
+ # ─────────────────────────────────────────────────────────────
53
+ # FIREBASE (lazy β€” resolve UID β†’ email)
54
+ # ─────────────────────────────────────────────────────────────
55
+ _firebase_initialized = False
56
+ _fb_auth = None
57
+
58
+
59
+ def _init_firebase() -> bool:
60
+ global _firebase_initialized, _fb_auth
61
+ if _firebase_initialized:
62
+ return _fb_auth is not None
63
+ _firebase_initialized = True
64
+ try:
65
+ import firebase_admin
66
+ from firebase_admin import auth as _auth
67
+ try:
68
+ firebase_admin.get_app()
69
+ except ValueError:
70
+ key_path = os.getenv("FIREBASE_KEY_PATH", "serviceAccountKey.json")
71
+ if not os.path.exists(key_path):
72
+ log.warning("[Studio/Polar] serviceAccountKey.json missing — UID→email disabled.")
73
+ return False
74
+ from firebase_admin import credentials
75
+ firebase_admin.initialize_app(credentials.Certificate(key_path))
76
+ _fb_auth = _auth
77
+ return True
78
+ except Exception as e:
79
+ log.warning(f"[Studio/Polar] Firebase init failed: {e}")
80
+ return False
81
+
82
+
83
+ def _resolve_firebase_email(user_id: str) -> str:
84
+ if not user_id or user_id in ("anonymous", "anon", "guest"):
85
+ return ""
86
+ if not _init_firebase():
87
+ return ""
88
+ try:
89
+ return (_fb_auth.get_user(user_id).email or "").strip()
90
+ except Exception as e:
91
+ log.warning(f"[Studio/Polar] Firebase get_user({user_id}): {e}")
92
+ return ""
93
+
94
+
95
+ # ─────────────────────────────────────────────────────────────
96
+ # CONFIG
97
+ # ─────────────────────────────────────────────────────────────
98
+ POLAR_API_KEY = os.getenv("POLAR_API_KEY", "")
99
+ POLAR_ORG_ID = os.getenv("POLAR_ORG_ID", "")
100
+ POLAR_WEBHOOK_SECRET = os.getenv("POLAR_WEBHOOK_SECRET", "")
101
+
102
+ # Prefer explicit product IDs from Polar dashboard (Products β†’ id).
103
+ # Fallback: case-insensitive name / slug matching (see _map_product_to_plan).
104
+ POLAR_STUDIO_PRODUCT_PRO = os.getenv("POLAR_STUDIO_PRODUCT_PRO", "").strip()
105
+ POLAR_STUDIO_PRODUCT_MAX = os.getenv("POLAR_STUDIO_PRODUCT_MAX", "").strip()
106
+ POLAR_STUDIO_PRODUCT_BIZ = os.getenv("POLAR_STUDIO_PRODUCT_BIZ", "").strip()
107
+
108
+ POLAR_API_BASE = "https://api.polar.sh/v1"
109
+
110
+ _POS_CACHE_TTL = 300 # 5 min when subscribed
111
+ _NEG_CACHE_TTL = 60 # 1 min when free (so post-checkout rechecks quickly)
112
+ _cache: Dict[str, dict] = {}
113
+
114
+ ACTIVE_STATUSES = {"active", "trialing", "past_due"}
115
+
116
+ # Rank for picking the highest tier if a user somehow has multiple subs
117
+ _PLAN_RANK = {"free": 0, "pro": 1, "max": 2, "business": 3}
118
+
119
+
120
+ # ─────────────────────────────────────────────────────────────
121
+ # STUDIO ENTITLEMENTS (must match frontend Ms[] / feature flags)
122
+ # ─────────────────────────────────────────────────────────────
123
+ # Keep in sync with the static Studio plans array:
124
+ # pro: builds=5, tokens label, canFix=False, canPlan=False, canDownload=True
125
+ # max: builds=10, canFix=True, canPlan=True, canDownload=True
126
+ # business: builds=15, canFix=True, canPlan=True, canDownload=True
127
+
128
+ STUDIO_ENTITLEMENTS: Dict[str, dict] = {
129
+ "free": {
130
+ "id": "free",
131
+ "name": "Free",
132
+ "builds": 1,
133
+ "tokens": "limited",
134
+ "tokens_monthly": 5_000,
135
+ "canFix": False,
136
+ "canPlan": False,
137
+ "canDownload": False,
138
+ "canBuild": True,
139
+ "features": ["Limited builds", "Streaming logs"],
140
+ },
141
+ "pro": {
142
+ "id": "pro",
143
+ "name": "Pro",
144
+ "builds": 5,
145
+ "tokens": "25k tokens / month",
146
+ "tokens_monthly": 25_000,
147
+ "canFix": False,
148
+ "canPlan": False,
149
+ "canDownload": True,
150
+ "canBuild": True,
151
+ "features": [
152
+ "5 builds per month",
153
+ "25k tokens / month",
154
+ "Download project as ZIP",
155
+ "Streaming build logs",
156
+ "Fix bugs β€” disabled",
157
+ ],
158
+ },
159
+ "max": {
160
+ "id": "max",
161
+ "name": "Max",
162
+ "builds": 10,
163
+ "tokens": "500k tokens / month",
164
+ "tokens_monthly": 500_000,
165
+ "canFix": True,
166
+ "canPlan": True,
167
+ "canDownload": True,
168
+ "canBuild": True,
169
+ "features": [
170
+ "10 builds per month",
171
+ "500k tokens / month",
172
+ "Fix bugs enabled",
173
+ "Plan with AI before building",
174
+ "Everything in Pro",
175
+ ],
176
+ },
177
+ "business": {
178
+ "id": "business",
179
+ "name": "Business",
180
+ "builds": 15,
181
+ "tokens": "525k+ tokens / month",
182
+ "tokens_monthly": 525_000,
183
+ "canFix": True,
184
+ "canPlan": True,
185
+ "canDownload": True,
186
+ "canBuild": True,
187
+ "features": [
188
+ "Pro + Max combined limits",
189
+ "Team seats and shared projects",
190
+ "Priority build queue",
191
+ "Dedicated support",
192
+ ],
193
+ },
194
+ }
195
+
196
+
197
+ def entitlements_for(plan_id: str) -> dict:
198
+ return dict(STUDIO_ENTITLEMENTS.get(plan_id) or STUDIO_ENTITLEMENTS["free"])
199
+
200
+
201
+ # ─────────────────────────────────────────────────────────────
202
+ # RESULT
203
+ # ─────────────────────────────────────────────────────────────
204
+ @dataclass
205
+ class StudioPlanResult:
206
+ """What the Studio frontend should apply as the user's plan."""
207
+ plan: str # free | pro | max | business
208
+ subscribed: bool # True if plan != free
209
+ entitlements: dict = field(default_factory=dict)
210
+ matched_by: str = ""
211
+ status: str = "" # Polar sub status
212
+ product_id: str = ""
213
+ product_name: str = ""
214
+ polar_customer_id: str = ""
215
+ subscription_id: str = ""
216
+ error: str = ""
217
+ checked_at: str = field(
218
+ default_factory=lambda: datetime.now(timezone.utc).isoformat()
219
+ )
220
+
221
+ def to_dict(self) -> dict:
222
+ d = asdict(self)
223
+ if not d.get("entitlements"):
224
+ d["entitlements"] = entitlements_for(self.plan)
225
+ return d
226
+
227
+
228
+ # ─────────────────────────────────────────────────────────────
229
+ # HELPERS
230
+ # ─────────────────────────────────────────────────────────────
231
+ def _normalize_email(email: str) -> str:
232
+ if not email:
233
+ return ""
234
+ e = email.strip().lower()
235
+ if "@gmail.com" in e or "@googlemail.com" in e:
236
+ local, _, domain = e.partition("@")
237
+ if "+" in local:
238
+ local = local.split("+", 1)[0]
239
+ e = f"{local}@{domain}"
240
+ return e
241
+
242
+
243
+ def _cache_key(email: str, firebase_uid: str) -> str:
244
+ return f"studio|{_normalize_email(email)}|{firebase_uid or ''}"
245
+
246
+
247
+ def clear_studio_polar_cache(email: str = "", firebase_uid: str = "") -> int:
248
+ if not email and not firebase_uid:
249
+ n = len(_cache)
250
+ _cache.clear()
251
+ return n
252
+ key = _cache_key(email, firebase_uid)
253
+ cleared = 0
254
+ if key in _cache:
255
+ del _cache[key]
256
+ cleared += 1
257
+ norm = _normalize_email(email)
258
+ for k in list(_cache.keys()):
259
+ # studio|email|uid
260
+ parts = k.split("|", 2)
261
+ if len(parts) < 3:
262
+ continue
263
+ _, e_part, uid_part = parts[0], parts[1], parts[2]
264
+ if (norm and e_part == norm) or (firebase_uid and uid_part == firebase_uid):
265
+ del _cache[k]
266
+ cleared += 1
267
+ return cleared
268
+
269
+
270
+ def _polar_headers() -> dict:
271
+ if not POLAR_API_KEY:
272
+ raise HTTPException(500, "POLAR_API_KEY not configured.")
273
+ return {
274
+ "Authorization": f"Bearer {POLAR_API_KEY}",
275
+ "Accept": "application/json",
276
+ "User-Agent": "NeuraPrompt-Studio-Polar/1.0",
277
+ }
278
+
279
+
280
+ def _map_product_to_plan(product_id: str, product_name: str) -> Optional[str]:
281
+ """
282
+ Map a Polar product to studio plan id: pro | max | business.
283
+ 1) Explicit env product IDs
284
+ 2) Name/slug heuristics (pro, max, business / team / enterprise)
285
+ """
286
+ pid = (product_id or "").strip()
287
+ name = (product_name or "").strip().lower()
288
+
289
+ if POLAR_STUDIO_PRODUCT_PRO and pid == POLAR_STUDIO_PRODUCT_PRO:
290
+ return "pro"
291
+ if POLAR_STUDIO_PRODUCT_MAX and pid == POLAR_STUDIO_PRODUCT_MAX:
292
+ return "max"
293
+ if POLAR_STUDIO_PRODUCT_BIZ and pid == POLAR_STUDIO_PRODUCT_BIZ:
294
+ return "business"
295
+
296
+ # Name heuristics β€” keep specific before generic
297
+ if any(x in name for x in ("business", "team", "enterprise", "org")):
298
+ return "business"
299
+ if any(x in name for x in ("max", "ultra", "pro+", "pro plus")):
300
+ return "max"
301
+ if "pro" in name or name in ("studio pro", "neuraprompt pro"):
302
+ return "pro"
303
+
304
+ return None
305
+
306
+
307
+ # ─────────────────────────────────────────────────────────────
308
+ # POLAR API
309
+ # ─────────────────────────────────────────────────────────────
310
+ async def _polar_get_all_subscriptions(client: httpx.AsyncClient) -> List[dict]:
311
+ all_subs: List[dict] = []
312
+ page = 1
313
+ max_pages = 20
314
+ while page <= max_pages:
315
+ r = await client.get(
316
+ f"{POLAR_API_BASE}/subscriptions/",
317
+ params={
318
+ "organization_id": POLAR_ORG_ID,
319
+ "limit": 50,
320
+ "page": page,
321
+ },
322
+ headers=_polar_headers(),
323
+ )
324
+ r.raise_for_status()
325
+ try:
326
+ data = r.json()
327
+ except Exception as e:
328
+ raise RuntimeError(f"Polar non-JSON (status={r.status_code}): {e}")
329
+ page_items = data.get("result") or data.get("items") or []
330
+ all_subs.extend(page_items)
331
+ pagination = data.get("pagination") or {}
332
+ max_page = pagination.get("max_page", 1)
333
+ if page >= max_page or len(page_items) < 50:
334
+ break
335
+ page += 1
336
+ return all_subs
337
+
338
+
339
+ def _extract_product(sub: dict) -> Tuple[str, str]:
340
+ product = sub.get("product")
341
+ if isinstance(product, dict):
342
+ return str(product.get("id") or ""), str(product.get("name") or "")
343
+ # older shapes
344
+ return str(sub.get("product_id") or ""), str(sub.get("product_name") or "")
345
+
346
+
347
+ # ─────────────────────────────────────────────────────────────
348
+ # MONGO (optional)
349
+ # ─────────────────────────────────────────────────────────────
350
+ def _mongo_lookup(col, firebase_uid: str, email: str) -> Optional[StudioPlanResult]:
351
+ if col is None:
352
+ return None
353
+ try:
354
+ doc = None
355
+ if firebase_uid:
356
+ doc = col.find_one({"user_id": firebase_uid, "product": "studio"})
357
+ if not doc:
358
+ doc = col.find_one({"user_id": firebase_uid})
359
+ if not doc and email:
360
+ doc = col.find_one({"email": _normalize_email(email), "product": "studio"})
361
+ if not doc:
362
+ doc = col.find_one({"email": _normalize_email(email)})
363
+ if not doc:
364
+ return None
365
+ plan = (doc.get("tier") or doc.get("plan") or "free").lower()
366
+ if plan not in STUDIO_ENTITLEMENTS:
367
+ plan = "free"
368
+ status = doc.get("status") or ""
369
+ subscribed = plan != "free" and status in ACTIVE_STATUSES | {"active"}
370
+ if status == "canceled" or status == "revoked":
371
+ plan = "free"
372
+ subscribed = False
373
+ return StudioPlanResult(
374
+ plan=plan if subscribed else "free",
375
+ subscribed=subscribed,
376
+ entitlements=entitlements_for(plan if subscribed else "free"),
377
+ matched_by="mongo_cache",
378
+ status=status,
379
+ polar_customer_id=doc.get("polar_customer_id", ""),
380
+ subscription_id=doc.get("polar_subscription_id", ""),
381
+ )
382
+ except Exception as e:
383
+ log.warning(f"[Studio/Polar] Mongo lookup failed: {e}")
384
+ return None
385
+
386
+
387
+ def _mongo_upsert(col, firebase_uid: str, email: str, result: StudioPlanResult) -> None:
388
+ if col is None or not (firebase_uid or email):
389
+ return
390
+ try:
391
+ filter_doc = {"user_id": firebase_uid} if firebase_uid else {"email": _normalize_email(email)}
392
+ col.update_one(
393
+ filter_doc,
394
+ {
395
+ "$set": {
396
+ "user_id": firebase_uid,
397
+ "email": _normalize_email(email),
398
+ "product": "studio",
399
+ "tier": result.plan,
400
+ "plan": result.plan,
401
+ "status": result.status or ("active" if result.subscribed else "inactive"),
402
+ "polar_customer_id": result.polar_customer_id,
403
+ "polar_subscription_id": result.subscription_id,
404
+ "polar_product_id": result.product_id,
405
+ "polar_product_name": result.product_name,
406
+ "polar_verified": result.subscribed,
407
+ "entitlements": result.entitlements,
408
+ "last_verified": datetime.now(timezone.utc),
409
+ }
410
+ },
411
+ upsert=True,
412
+ )
413
+ except Exception as e:
414
+ log.warning(f"[Studio/Polar] Mongo upsert failed: {e}")
415
+
416
+
417
+ # ─────────────────────────────────────────────────────────────
418
+ # MAIN CHECK
419
+ # ─────────────────────────────────────────────────────────────
420
+ async def check_studio_plan(
421
+ email: str = "",
422
+ firebase_uid: str = "",
423
+ subscriptions_col=None,
424
+ fail_open_on_outage: bool = False,
425
+ ) -> StudioPlanResult:
426
+ """
427
+ Resolve Studio plan for a user: free | pro | max | business.
428
+
429
+ Matching order against Polar subscriptions:
430
+ customer.email OR customer.metadata.firebase_uid
431
+ Among matching *active* subs, highest tier wins (business > max > pro).
432
+ """
433
+ if not firebase_uid and not email:
434
+ return StudioPlanResult(
435
+ plan="free",
436
+ subscribed=False,
437
+ entitlements=entitlements_for("free"),
438
+ matched_by="no_identity",
439
+ error="No user_id or email β€” cannot verify Studio plan.",
440
+ )
441
+ if firebase_uid in ("anonymous", "anon", "guest") and not email:
442
+ return StudioPlanResult(
443
+ plan="free",
444
+ subscribed=False,
445
+ entitlements=entitlements_for("free"),
446
+ matched_by="anonymous_user",
447
+ error="Sign in required to load Studio plan.",
448
+ )
449
+ if not POLAR_API_KEY or not POLAR_ORG_ID:
450
+ log.error("[Studio/Polar] API key or org missing β€” returning free.")
451
+ return StudioPlanResult(
452
+ plan="free",
453
+ subscribed=False,
454
+ entitlements=entitlements_for("free"),
455
+ matched_by="polar_not_configured",
456
+ error="Polar not configured on server.",
457
+ )
458
+
459
+ if not email and firebase_uid:
460
+ email = _resolve_firebase_email(firebase_uid)
461
+ email = _normalize_email(email)
462
+ cache_k = _cache_key(email, firebase_uid)
463
+
464
+ cached = _cache.get(cache_k)
465
+ if cached and time.time() < cached["exp"]:
466
+ plan = cached["plan"]
467
+ return StudioPlanResult(
468
+ plan=plan,
469
+ subscribed=cached["subscribed"],
470
+ entitlements=entitlements_for(plan),
471
+ matched_by=f"cache({cached.get('matched_by', '')})",
472
+ status=cached.get("status", ""),
473
+ product_id=cached.get("product_id", ""),
474
+ product_name=cached.get("product_name", ""),
475
+ polar_customer_id=cached.get("polar_customer_id", ""),
476
+ subscription_id=cached.get("subscription_id", ""),
477
+ )
478
+
479
+ polar_exc: Optional[Exception] = None
480
+ try:
481
+ async with httpx.AsyncClient(timeout=15.0, follow_redirects=True) as client:
482
+ all_subs = await _polar_get_all_subscriptions(client)
483
+
484
+ best: Optional[StudioPlanResult] = None
485
+ best_rank = -1
486
+
487
+ for sub in all_subs:
488
+ customer = sub.get("customer") or {}
489
+ sub_status = sub.get("status", "")
490
+ sub_email = _normalize_email(customer.get("email", ""))
491
+ sub_meta = customer.get("metadata") or {}
492
+ sub_uid = str(sub_meta.get("firebase_uid") or "")
493
+
494
+ matched = False
495
+ matched_by = ""
496
+ if email and sub_email and sub_email == email:
497
+ matched, matched_by = True, "email"
498
+ elif firebase_uid and sub_uid and sub_uid == firebase_uid:
499
+ matched, matched_by = True, "firebase_uid"
500
+
501
+ if not matched:
502
+ continue
503
+ if sub_status not in ACTIVE_STATUSES:
504
+ continue
505
+
506
+ product_id, product_name = _extract_product(sub)
507
+ plan = _map_product_to_plan(product_id, product_name)
508
+ if not plan:
509
+ # Unrecognized product still counts as paid Pro-level fallback
510
+ # so the user is not stuck on free after paying a Studio SKU
511
+ # that wasn't mapped yet β€” prefer mapping via env IDs.
512
+ log.warning(
513
+ f"[Studio/Polar] Unmapped product id={product_id} name={product_name!r} "
514
+ f"β€” treating as pro until POLAR_STUDIO_PRODUCT_* is set."
515
+ )
516
+ plan = "pro"
517
+
518
+ rank = _PLAN_RANK.get(plan, 0)
519
+ if rank > best_rank:
520
+ best_rank = rank
521
+ best = StudioPlanResult(
522
+ plan=plan,
523
+ subscribed=True,
524
+ entitlements=entitlements_for(plan),
525
+ matched_by=matched_by,
526
+ status=sub_status,
527
+ product_id=product_id,
528
+ product_name=product_name,
529
+ polar_customer_id=customer.get("id", ""),
530
+ subscription_id=sub.get("id", ""),
531
+ )
532
+
533
+ if best is not None:
534
+ ttl = _POS_CACHE_TTL
535
+ _cache[cache_k] = {
536
+ "plan": best.plan,
537
+ "subscribed": True,
538
+ "exp": time.time() + ttl,
539
+ "matched_by": best.matched_by,
540
+ "status": best.status,
541
+ "product_id": best.product_id,
542
+ "product_name": best.product_name,
543
+ "polar_customer_id": best.polar_customer_id,
544
+ "subscription_id": best.subscription_id,
545
+ }
546
+ _mongo_upsert(subscriptions_col, firebase_uid, email, best)
547
+ return best
548
+
549
+ # No active matching sub
550
+ free = StudioPlanResult(
551
+ plan="free",
552
+ subscribed=False,
553
+ entitlements=entitlements_for("free"),
554
+ matched_by="polar_no_match",
555
+ status="none",
556
+ )
557
+ _cache[cache_k] = {
558
+ "plan": "free",
559
+ "subscribed": False,
560
+ "exp": time.time() + _NEG_CACHE_TTL,
561
+ "matched_by": "polar_no_match",
562
+ "status": "none",
563
+ }
564
+ _mongo_upsert(subscriptions_col, firebase_uid, email, free)
565
+ return free
566
+
567
+ except Exception as e:
568
+ polar_exc = e
569
+ log.error(f"[Studio/Polar] API failed: {e}")
570
+
571
+ mongo = _mongo_lookup(subscriptions_col, firebase_uid, email)
572
+ if mongo is not None:
573
+ return mongo
574
+
575
+ # Auth errors β†’ free (fail closed)
576
+ msg = str(polar_exc or "").lower()
577
+ if "401" in msg or "403" in msg:
578
+ return StudioPlanResult(
579
+ plan="free",
580
+ subscribed=False,
581
+ entitlements=entitlements_for("free"),
582
+ matched_by="polar_auth_error",
583
+ error=str(polar_exc),
584
+ )
585
+
586
+ if fail_open_on_outage and polar_exc is not None:
587
+ # Only if you explicitly opt in β€” still prefer free for Studio UI
588
+ log.warning("[Studio/Polar] fail_open requested but returning free for safety")
589
+
590
+ return StudioPlanResult(
591
+ plan="free",
592
+ subscribed=False,
593
+ entitlements=entitlements_for("free"),
594
+ matched_by="polar_error",
595
+ error=str(polar_exc),
596
+ )
597
+
598
+
599
+ # ─────────────────────────────────────────────────────────────
600
+ # WEBHOOK
601
+ # ─────────────────────────────────────────────────────────────
602
+ async def handle_studio_polar_webhook(
603
+ request: Request,
604
+ subscriptions_col=None,
605
+ ) -> JSONResponse:
606
+ """
607
+ Polar webhook for Studio plans.
608
+ Configure endpoint: https://<api-host>/studio/polar/webhook
609
+ Events: subscription.created, subscription.updated, subscription.active,
610
+ subscription.canceled, subscription.revoked
611
+ """
612
+ try:
613
+ body = await request.body()
614
+ signature = request.headers.get("polar-signature", "")
615
+
616
+ if POLAR_WEBHOOK_SECRET:
617
+ if not signature:
618
+ return JSONResponse({"status": "missing signature"}, status_code=401)
619
+ expected = hmac.new(
620
+ POLAR_WEBHOOK_SECRET.encode(),
621
+ body,
622
+ hashlib.sha256,
623
+ ).hexdigest()
624
+ if not hmac.compare_digest(signature, expected):
625
+ log.warning("[Studio/Polar Webhook] Invalid signature")
626
+ return JSONResponse({"status": "invalid signature"}, status_code=401)
627
+
628
+ payload = json.loads(body)
629
+ event_type = payload.get("type", "")
630
+ data = payload.get("data") or {}
631
+ customer = data.get("customer") or {}
632
+ email = customer.get("email", "")
633
+ user_id = (customer.get("metadata") or {}).get("firebase_uid", "")
634
+ sub_id = data.get("id", "")
635
+ product_id, product_name = _extract_product(data)
636
+ plan = _map_product_to_plan(product_id, product_name) or "pro"
637
+ status = data.get("status", "active")
638
+
639
+ log.info(
640
+ f"[Studio/Polar Webhook] event={event_type} email={email} "
641
+ f"uid={user_id} plan={plan} status={status}"
642
+ )
643
+
644
+ clear_studio_polar_cache(email=email, firebase_uid=user_id)
645
+
646
+ if subscriptions_col is not None and (email or user_id):
647
+ filter_doc = {"user_id": user_id} if user_id else {"email": _normalize_email(email)}
648
+ activate = event_type in (
649
+ "subscription.created",
650
+ "subscription.updated",
651
+ "subscription.active",
652
+ "subscription.uncanceled",
653
+ )
654
+ cancel = event_type in (
655
+ "subscription.canceled",
656
+ "subscription.revoked",
657
+ )
658
+
659
+ if activate:
660
+ subscriptions_col.update_one(
661
+ filter_doc,
662
+ {
663
+ "$set": {
664
+ "user_id": user_id,
665
+ "email": _normalize_email(email),
666
+ "product": "studio",
667
+ "tier": plan,
668
+ "plan": plan,
669
+ "status": status,
670
+ "polar_subscription_id": sub_id,
671
+ "polar_customer_id": customer.get("id", ""),
672
+ "polar_product_id": product_id,
673
+ "polar_product_name": product_name,
674
+ "polar_verified": status in ACTIVE_STATUSES,
675
+ "entitlements": entitlements_for(plan),
676
+ "updated_at": datetime.now(timezone.utc),
677
+ }
678
+ },
679
+ upsert=True,
680
+ )
681
+ log.info(f"[Studio/Polar Webhook] activated {plan} for {email or user_id}")
682
+ elif cancel:
683
+ subscriptions_col.update_one(
684
+ filter_doc,
685
+ {
686
+ "$set": {
687
+ "tier": "free",
688
+ "plan": "free",
689
+ "status": "canceled",
690
+ "polar_verified": False,
691
+ "entitlements": entitlements_for("free"),
692
+ "updated_at": datetime.now(timezone.utc),
693
+ }
694
+ },
695
+ )
696
+ log.info(f"[Studio/Polar Webhook] canceled β†’ free for {email or user_id}")
697
+
698
+ return JSONResponse({"status": "ok", "plan": plan if not cancel else "free"})
699
+
700
+ except json.JSONDecodeError:
701
+ return JSONResponse({"status": "invalid json"}, status_code=400)
702
+ except Exception as e:
703
+ log.error(f"[Studio/Polar Webhook] {e}", exc_info=True)
704
+ return JSONResponse({"status": "error"}, status_code=500)
705
+
706
+
707
+ # ─────────────────────────────────────────────────────────────
708
+ # ROUTER
709
+ # ─────────────────────────────────────────────────────────────
710
+ studio_polar_router = APIRouter(prefix="/studio/polar", tags=["studio-polar"])
711
+
712
+
713
+ @studio_polar_router.get("/plan")
714
+ async def studio_get_plan(
715
+ uid: str = Query("", description="Firebase UID"),
716
+ email: str = Query("", description="User email"),
717
+ ):
718
+ """
719
+ Main endpoint for the Studio frontend.
720
+ GET /studio/polar/plan?uid=<firebase_uid>&email=<optional>
721
+
722
+ Response:
723
+ {
724
+ "plan": "pro" | "max" | "business" | "free",
725
+ "subscribed": true/false,
726
+ "entitlements": { canFix, canPlan, canDownload, builds, tokens, ... },
727
+ "matched_by": "...",
728
+ "status": "active",
729
+ ...
730
+ }
731
+ """
732
+ if not uid and not email:
733
+ raise HTTPException(400, "Provide ?uid= and/or ?email=")
734
+ result = await check_studio_plan(email=email, firebase_uid=uid)
735
+ return result.to_dict()
736
+
737
+
738
+ @studio_polar_router.post("/webhook")
739
+ async def studio_polar_webhook(request: Request):
740
+ """Polar β†’ Studio plan webhook. Point Polar dashboard here."""
741
+ # Optional: resolve subscriptions_col from main app if present
742
+ col = None
743
+ try:
744
+ import sys
745
+ main = sys.modules.get("main")
746
+ if main is not None and hasattr(main, "subscriptions_col"):
747
+ col = main.subscriptions_col
748
+ except Exception:
749
+ pass
750
+ return await handle_studio_polar_webhook(request, subscriptions_col=col)
751
+
752
+
753
+ @studio_polar_router.get("/diagnose")
754
+ async def studio_polar_diagnose(
755
+ email: str = "",
756
+ uid: str = "",
757
+ ):
758
+ """Debug why a user is free vs pro/max/business."""
759
+ if not email and not uid:
760
+ raise HTTPException(400, "Provide ?email= or ?uid=")
761
+ clear_studio_polar_cache(email=email, firebase_uid=uid)
762
+ out: Dict[str, Any] = {
763
+ "input": {"email": email, "firebase_uid": uid},
764
+ "normalized_email": _normalize_email(email),
765
+ "config": {
766
+ "POLAR_API_KEY_set": bool(POLAR_API_KEY),
767
+ "POLAR_ORG_ID": POLAR_ORG_ID or "(not set)",
768
+ "PRODUCT_PRO": POLAR_STUDIO_PRODUCT_PRO or "(name match)",
769
+ "PRODUCT_MAX": POLAR_STUDIO_PRODUCT_MAX or "(name match)",
770
+ "PRODUCT_BIZ": POLAR_STUDIO_PRODUCT_BIZ or "(name match)",
771
+ },
772
+ "entitlements_table": STUDIO_ENTITLEMENTS,
773
+ }
774
+ raw_subs: List[dict] = []
775
+ if POLAR_API_KEY and POLAR_ORG_ID:
776
+ try:
777
+ async with httpx.AsyncClient(timeout=15.0, follow_redirects=True) as client:
778
+ r = await client.get(
779
+ f"{POLAR_API_BASE}/subscriptions/",
780
+ params={"organization_id": POLAR_ORG_ID, "limit": 50},
781
+ headers=_polar_headers(),
782
+ )
783
+ out["polar_http_status"] = r.status_code
784
+ if r.status_code == 200:
785
+ data = r.json()
786
+ out["polar_response_keys"] = list(data.keys())
787
+ raw_subs = data.get("result") or data.get("items") or []
788
+ else:
789
+ out["polar_body"] = r.text[:500]
790
+ except Exception as e:
791
+ out["polar_error"] = str(e)
792
+ out["polar_total_subs"] = len(raw_subs)
793
+ norm = _normalize_email(email)
794
+ matches = []
795
+ for sub in raw_subs:
796
+ customer = sub.get("customer") or {}
797
+ se = _normalize_email(customer.get("email", ""))
798
+ su = (customer.get("metadata") or {}).get("firebase_uid", "")
799
+ if (norm and se == norm) or (uid and su == uid):
800
+ pid, pname = _extract_product(sub)
801
+ matches.append({
802
+ "subscription_id": sub.get("id"),
803
+ "status": sub.get("status"),
804
+ "customer_email": customer.get("email"),
805
+ "metadata": customer.get("metadata"),
806
+ "product_id": pid,
807
+ "product_name": pname,
808
+ "mapped_plan": _map_product_to_plan(pid, pname),
809
+ })
810
+ out["matching_subscriptions"] = matches
811
+ out["check_result"] = (await check_studio_plan(email=email, firebase_uid=uid)).to_dict()
812
+ return out
813
+
814
+
815
+ @studio_polar_router.post("/invalidate")
816
+ async def studio_polar_invalidate(email: str = "", uid: str = ""):
817
+ cleared = clear_studio_polar_cache(email=email, firebase_uid=uid)
818
+ return {"cleared_entries": cleared}
819
+
820
+
821
+ @studio_polar_router.get("/health")
822
+ async def studio_polar_health():
823
+ return {
824
+ "status": "ok",
825
+ "service": "polar_subs_studio",
826
+ "plans": list(STUDIO_ENTITLEMENTS.keys()),
827
+ "polar_api_key_set": bool(POLAR_API_KEY),
828
+ "polar_org_id_set": bool(POLAR_ORG_ID),
829
+ "webhook_secret_set": bool(POLAR_WEBHOOK_SECRET),
830
+ "product_ids_configured": {
831
+ "pro": bool(POLAR_STUDIO_PRODUCT_PRO),
832
+ "max": bool(POLAR_STUDIO_PRODUCT_MAX),
833
+ "business": bool(POLAR_STUDIO_PRODUCT_BIZ),
834
+ },
835
+ "cache_size": len(_cache),
836
+ }
837
+
838
+
839
+ @studio_polar_router.get("/entitlements")
840
+ async def studio_list_entitlements():
841
+ """Static table of plan β†’ feature flags (no Polar call)."""
842
+ return STUDIO_ENTITLEMENTS
studio_generate.py CHANGED
@@ -5,7 +5,7 @@ NeuraPrompt Studio v2.0 β€” Credit-based autonomous web-app builder
5
  Changes over v1:
6
  * Credit system replaces token usage (5 free/month, 10 pro/month)
7
  * Project statistics tracking (MongoDB)
8
- * Polar subscription checker integration
9
  * Firebase auth email resolution
10
  * Speed optimizations (reduced max_tokens, max_files, continuations)
11
  * /plan endpoint fixed (uses call_openrouter_raw for proper response)
@@ -129,97 +129,271 @@ async def _db_create_index(collection, keys, **kwargs):
129
  return await asyncio.to_thread(lambda: _get_db()[collection].create_index(keys, **kwargs))
130
 
131
 
132
- # ── CREDIT SYSTEM ─────────────────────────────────────────────────────────────
133
- FREE_CREDITS = 5 # 5 builds/month for free users
134
- PRO_CREDITS = 10 # 10 builds/month for Pro users
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
  def _month_key():
137
  return datetime.now(timezone.utc).strftime("%Y-%m")
138
 
139
- async def get_credits(user_id: str) -> dict:
140
- """Get user's credit status. Determines tier via Polar (with timeout)."""
 
 
 
 
 
 
 
 
 
141
  month = _month_key()
142
- # Polar check with 5s timeout β€” don't let it block the whole request
 
143
  try:
144
- is_pro = await asyncio.wait_for(_check_polar(user_id), timeout=5.0)
 
 
 
 
 
145
  except (asyncio.TimeoutError, Exception) as e:
146
- print(f"[Studio] Polar check timed out or failed ({e}) β€” defaulting to free tier")
147
- is_pro = False
 
 
 
 
 
148
 
149
  doc = await _db_find_one("studio_credits", {"user_id": user_id, "month_key": month})
150
  if doc:
151
- remaining = doc.get("credits_remaining", FREE_CREDITS)
152
- total = doc.get("credits_total", PRO_CREDITS if is_pro else FREE_CREDITS)
153
- # If tier changed (free→pro), update total
154
- if is_pro and total < PRO_CREDITS:
155
- remaining += (PRO_CREDITS - total)
156
- total = PRO_CREDITS
157
- await _db_update_one("studio_credits",
 
 
 
158
  {"user_id": user_id, "month_key": month},
159
- {"$set": {"credits_remaining": remaining, "credits_total": total, "tier": "pro"}}
 
 
 
 
 
160
  )
161
- elif not is_pro and total > FREE_CREDITS:
162
- total = FREE_CREDITS
163
- remaining = min(remaining, FREE_CREDITS)
164
- await _db_update_one("studio_credits",
 
 
165
  {"user_id": user_id, "month_key": month},
166
- {"$set": {"credits_remaining": remaining, "credits_total": total, "tier": "free"}}
 
 
 
 
 
167
  )
168
- return {"remaining": remaining, "total": total, "tier": "pro" if is_pro else "free", "month": month}
 
 
 
 
 
 
 
 
 
 
169
  # New month β€” create record
170
- total = PRO_CREDITS if is_pro else FREE_CREDITS
171
  await _db_insert_one("studio_credits", {
172
- "user_id": user_id, "month_key": month,
173
- "credits_remaining": total, "credits_total": total,
174
- "tier": "pro" if is_pro else "free",
175
- "history": [], "created_at": datetime.now(timezone.utc),
 
 
 
 
176
  })
177
- return {"remaining": total, "total": total, "tier": "pro" if is_pro else "free", "month": month}
 
 
 
 
 
 
 
 
 
178
 
179
  async def consume_credit(user_id: str, action: str, project_id: str = "") -> bool:
180
  """Consume 1 credit. Returns True if successful, False if no credits."""
181
  month = _month_key()
182
- result = await _db_update_one("studio_credits",
 
183
  {"user_id": user_id, "month_key": month, "credits_remaining": {"$gt": 0}},
184
- {"$inc": {"credits_remaining": -1},
185
- "$push": {"history": {"action": action, "project_id": project_id, "timestamp": datetime.now(timezone.utc).isoformat()}}},
 
 
 
 
 
 
 
 
186
  )
187
  return result.modified_count > 0
188
 
189
- async def check_credits(user_id: str) -> tuple:
190
- """Returns (has_credits, remaining, total, tier)."""
191
- status = await get_credits(user_id)
 
192
  return status["remaining"] > 0, status["remaining"], status["total"], status["tier"]
193
 
194
- # ── POLAR SUBSCRIPTION CHECKER ────────────────────────────────────────────────
195
- async def _check_polar(user_id: str) -> bool:
196
- """Check Polar subscription. Reuses the polar_subscription module.
197
- Falls back to MongoDB cache. Fail-closed on errors (return False = free tier).
198
- All network calls have timeouts so this never blocks the request."""
199
- # Try the polar_subscription module first (with 4s timeout)
 
 
 
 
200
  try:
201
- import sys
202
- main_mod = sys.modules.get("main")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  if main_mod and hasattr(main_mod, "verify_polar_subscription"):
204
  email = await _resolve_email(user_id)
205
  result = await asyncio.wait_for(
206
  main_mod.verify_polar_subscription(email=email, firebase_uid=user_id),
207
- timeout=4.0
208
  )
209
  return bool(result)
210
  except asyncio.TimeoutError:
211
- print(f"[Studio] Polar check timed out for {user_id} β€” defaulting to free")
212
  except Exception as e:
213
- print(f"[Studio] Polar check error: {e}")
214
- # Fallback: check MongoDB subscriptions collection (fast, local)
215
  try:
216
  doc = await _db_find_one("subscriptions", {"user_id": user_id})
217
- if doc and doc.get("status") == "active" and doc.get("tier") in ("pro", "ultra"):
 
 
218
  return True
219
  except Exception:
220
  pass
221
  return False
222
 
 
 
 
 
 
 
 
223
  # ── FIREBASE EMAIL RESOLUTION ─────────────────────────────────────────────────
224
  _firebase_inited = False
225
  _fb_auth = None
@@ -306,15 +480,15 @@ async def _update_stats():
306
  print(f"[Studio] Stats update error: {e}")
307
 
308
  # ── MODELS ────────────────────────────────────────────────────────────────────
309
- BUILD_MODEL = "inclusionai/ling-3.0-flash:free" # Fast model (was tencent/hy3:free β€” too slow)
310
- STRONG_MODEL = "inclusionai/ling-3.0-flash:free" # Strong model (for index.html only)
311
- FAST_MODEL = "nvidia/nemotron-3-embed-1b:free"
312
  FALLBACK_MODEL = "poolside/laguna-xs-2.1:free"
313
- PLAN_MODEL = "nvidia/nemotron-3-embed-1b:free"
314
- FIX_MODEL = "inclusionai/ling-3.0-flash:free"
315
 
316
  # ── SPEED OPTIMIZATIONS ───────────────────────────────────────────────────────
317
- MAX_TOKENS_PER_CALL = 10000 # Was 18000 β€” most web files are under 4K tokens
318
  RATE_LIMIT_WAIT = 15 # Was 45 β€” enough for OpenRouter free tier
319
  MAX_BUILD_RETRIES = 2 # Was 3 β€” fail faster
320
  MAX_CONTINUATIONS = 3 # Was 6 β€” most files complete in 1 call
@@ -633,10 +807,28 @@ async def plan_chat(request: Request):
633
  if not message:
634
  return JSONResponse({"error": "Message required"}, status_code=400)
635
 
636
- # Check credits
637
- has_credits, remaining, total, tier = await check_credits(user_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
638
  if not has_credits:
639
- return JSONResponse({"error": "No credits remaining this month", "credits": {"remaining": 0, "total": total, "tier": tier}}, status_code=402)
640
 
641
  # Build conversation context from history
642
  conversation_context = ""
@@ -727,10 +919,28 @@ async def fix_project(request: Request):
727
  if not files:
728
  return JSONResponse({"error": "No files to fix"}, status_code=400)
729
 
730
- # Check + consume credit
731
- has_credits, remaining, total, tier = await check_credits(user_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
732
  if not has_credits:
733
- return JSONResponse({"error": "No credits remaining", "credits": {"remaining": 0, "total": total, "tier": tier}}, status_code=402)
734
  consumed = await consume_credit(user_id, "fix", project_id)
735
  if not consumed:
736
  return JSONResponse({"error": "Could not consume credit"}, status_code=402)
@@ -803,24 +1013,29 @@ async def fix_project(request: Request):
803
 
804
  # ── CREDITS ENDPOINT ──────────────────────────────────────────────────────────
805
  @router.get("/credits/{user_id}")
806
- async def get_user_credits(user_id: str):
807
- """Get credit status for a user."""
808
- credits = await get_credits(user_id)
809
  return {"user_id": user_id, **credits}
810
 
811
  # ── USAGE ENDPOINT (token stats for display) ──────────────────────────────────
812
  @router.get("/usage/{user_id}")
813
- async def get_studio_usage(user_id: str):
814
- """Get studio token usage (for stats display, credits are the gate)."""
815
- credits = await get_credits(user_id)
816
  return {
817
  "user_id": user_id,
818
  "credits_remaining": credits["remaining"],
819
  "credits_total": credits["total"],
820
  "tier": credits["tier"],
 
821
  "month": credits["month"],
822
- "free_credits": FREE_CREDITS,
823
- "pro_credits": PRO_CREDITS,
 
 
 
 
824
  }
825
 
826
  # ── STATS ENDPOINT (admin) ────────────────────────────────────────────────────
@@ -856,17 +1071,27 @@ async def generate_app(request: Request):
856
  if is_non_web_request(user_prompt):
857
  yield sse("error", {"message": "Studio builds web apps only. Try a website, dashboard, or web tool."}); return
858
 
859
- # Credit check
860
- has_credits, remaining, total, tier = await check_credits(user_id)
861
- if not has_credits:
862
- yield sse("error", {"message": f"No credits remaining this month. You get {total} credits/month ({tier} tier). Upgrade to Pro for {PRO_CREDITS} credits.", "credits": {"remaining": 0, "total": total, "tier": tier}}); return
863
-
864
- max_files = MAX_FILES_PRO if tier == "pro" else MAX_FILES_FREE
 
 
 
 
 
 
 
 
 
 
865
 
866
  yield sse("status", {"message": "Initialising Studio Engine..."})
867
  yield sse("target", {"target": "web", "previewable": True})
868
  yield sse("status", {"message": "Designing your app architecture..."})
869
- yield sse("credits", {"remaining": remaining, "total": total, "tier": tier})
870
 
871
  # PLANNER
872
  plan = None
 
5
  Changes over v1:
6
  * Credit system replaces token usage (5 free/month, 10 pro/month)
7
  * Project statistics tracking (MongoDB)
8
+ * Polar multi-plan via polar_subs_studio (free/pro/max/business credits + features)
9
  * Firebase auth email resolution
10
  * Speed optimizations (reduced max_tokens, max_files, continuations)
11
  * /plan endpoint fixed (uses call_openrouter_raw for proper response)
 
129
  return await asyncio.to_thread(lambda: _get_db()[collection].create_index(keys, **kwargs))
130
 
131
 
132
+ # ── CREDIT SYSTEM (aligned with polar_subs_studio entitlements) ───────────────
133
+ # Monthly build credits = plan.builds from Studio Polar entitlements.
134
+ # free: 1 | pro: 5 | max: 10 | business: 15
135
+ FREE_CREDITS = 1
136
+ PLAN_CREDITS = {
137
+ "free": 1,
138
+ "pro": 5,
139
+ "max": 10,
140
+ "business": 15,
141
+ }
142
+ # Legacy alias used in error messages / usage payload
143
+ PRO_CREDITS = PLAN_CREDITS["max"]
144
+
145
+ # Feature flags by plan (mirror polar_subs_studio.STUDIO_ENTITLEMENTS)
146
+ PLAN_FEATURES = {
147
+ "free": {"canFix": False, "canPlan": False, "canDownload": False, "canBuild": True},
148
+ "pro": {"canFix": False, "canPlan": False, "canDownload": True, "canBuild": True},
149
+ "max": {"canFix": True, "canPlan": True, "canDownload": True, "canBuild": True},
150
+ "business": {"canFix": True, "canPlan": True, "canDownload": True, "canBuild": True},
151
+ }
152
+
153
 
154
  def _month_key():
155
  return datetime.now(timezone.utc).strftime("%Y-%m")
156
 
157
+
158
+ def _credits_for_plan(plan: str) -> int:
159
+ return PLAN_CREDITS.get((plan or "free").lower(), FREE_CREDITS)
160
+
161
+
162
+ def _features_for_plan(plan: str) -> dict:
163
+ return dict(PLAN_FEATURES.get((plan or "free").lower(), PLAN_FEATURES["free"]))
164
+
165
+
166
+ async def get_credits(user_id: str, email: str = "") -> dict:
167
+ """Get user's credit status. Tier comes from polar_subs_studio (pro/max/business/free)."""
168
  month = _month_key()
169
+ plan = "free"
170
+ entitlements: dict = {}
171
  try:
172
+ plan_result = await asyncio.wait_for(
173
+ _check_studio_plan(user_id, email=email),
174
+ timeout=5.0,
175
+ )
176
+ plan = plan_result.get("plan") or "free"
177
+ entitlements = plan_result.get("entitlements") or _features_for_plan(plan)
178
  except (asyncio.TimeoutError, Exception) as e:
179
+ print(f"[Studio] Studio Polar check timed out or failed ({e}) β€” defaulting to free tier")
180
+ plan = "free"
181
+ entitlements = _features_for_plan("free")
182
+
183
+ plan = plan if plan in PLAN_CREDITS else "free"
184
+ target_total = _credits_for_plan(plan)
185
+ features = entitlements if entitlements else _features_for_plan(plan)
186
 
187
  doc = await _db_find_one("studio_credits", {"user_id": user_id, "month_key": month})
188
  if doc:
189
+ remaining = int(doc.get("credits_remaining", target_total))
190
+ total = int(doc.get("credits_total", target_total))
191
+ prev_plan = (doc.get("tier") or doc.get("plan") or "free").lower()
192
+
193
+ # Upgrade: grant the difference when moving to a higher credit allowance
194
+ if target_total > total:
195
+ remaining += (target_total - total)
196
+ total = target_total
197
+ await _db_update_one(
198
+ "studio_credits",
199
  {"user_id": user_id, "month_key": month},
200
+ {"$set": {
201
+ "credits_remaining": remaining,
202
+ "credits_total": total,
203
+ "tier": plan,
204
+ "plan": plan,
205
+ }},
206
  )
207
+ # Downgrade or plan rename: clamp remaining to new total
208
+ elif target_total < total or prev_plan != plan:
209
+ total = target_total
210
+ remaining = min(remaining, target_total)
211
+ await _db_update_one(
212
+ "studio_credits",
213
  {"user_id": user_id, "month_key": month},
214
+ {"$set": {
215
+ "credits_remaining": remaining,
216
+ "credits_total": total,
217
+ "tier": plan,
218
+ "plan": plan,
219
+ }},
220
  )
221
+
222
+ return {
223
+ "remaining": remaining,
224
+ "total": total,
225
+ "tier": plan,
226
+ "plan": plan,
227
+ "month": month,
228
+ "features": features,
229
+ "entitlements": features,
230
+ }
231
+
232
  # New month β€” create record
 
233
  await _db_insert_one("studio_credits", {
234
+ "user_id": user_id,
235
+ "month_key": month,
236
+ "credits_remaining": target_total,
237
+ "credits_total": target_total,
238
+ "tier": plan,
239
+ "plan": plan,
240
+ "history": [],
241
+ "created_at": datetime.now(timezone.utc),
242
  })
243
+ return {
244
+ "remaining": target_total,
245
+ "total": target_total,
246
+ "tier": plan,
247
+ "plan": plan,
248
+ "month": month,
249
+ "features": features,
250
+ "entitlements": features,
251
+ }
252
+
253
 
254
  async def consume_credit(user_id: str, action: str, project_id: str = "") -> bool:
255
  """Consume 1 credit. Returns True if successful, False if no credits."""
256
  month = _month_key()
257
+ result = await _db_update_one(
258
+ "studio_credits",
259
  {"user_id": user_id, "month_key": month, "credits_remaining": {"$gt": 0}},
260
+ {
261
+ "$inc": {"credits_remaining": -1},
262
+ "$push": {
263
+ "history": {
264
+ "action": action,
265
+ "project_id": project_id,
266
+ "timestamp": datetime.now(timezone.utc).isoformat(),
267
+ }
268
+ },
269
+ },
270
  )
271
  return result.modified_count > 0
272
 
273
+
274
+ async def check_credits(user_id: str, email: str = "") -> tuple:
275
+ """Returns (has_credits, remaining, total, tier/plan)."""
276
+ status = await get_credits(user_id, email=email)
277
  return status["remaining"] > 0, status["remaining"], status["total"], status["tier"]
278
 
279
+
280
+ # ── POLAR (Studio multi-plan via polar_subs_studio) ────────────────────────────
281
+ _studio_polar_mod = None
282
+
283
+
284
+ def _get_studio_polar():
285
+ """Lazy-load polar_subs_studio (sibling module or package import)."""
286
+ global _studio_polar_mod
287
+ if _studio_polar_mod is not None:
288
+ return _studio_polar_mod
289
  try:
290
+ import polar_subs_studio as _ps
291
+ _studio_polar_mod = _ps
292
+ return _ps
293
+ except ImportError:
294
+ try:
295
+ from . import polar_subs_studio as _ps
296
+ _studio_polar_mod = _ps
297
+ return _ps
298
+ except ImportError as e:
299
+ print(f"[Studio] polar_subs_studio not available: {e}")
300
+ return None
301
+
302
+
303
+ async def _check_studio_plan(user_id: str, email: str = "") -> dict:
304
+ """
305
+ Resolve Studio plan via polar_subs_studio.
306
+ Returns dict with plan, entitlements, subscribed, matched_by, ...
307
+ Fail-closed β†’ free.
308
+ """
309
+ ps = _get_studio_polar()
310
+ if ps is None:
311
+ is_paid = await _check_polar_legacy(user_id)
312
+ plan = "pro" if is_paid else "free"
313
+ return {
314
+ "plan": plan,
315
+ "subscribed": is_paid,
316
+ "entitlements": _features_for_plan(plan),
317
+ "matched_by": "legacy_fallback",
318
+ }
319
+
320
+ try:
321
+ if not email:
322
+ email = await _resolve_email(user_id)
323
+ subs_col = None
324
+ try:
325
+ main_mod = _sys.modules.get("main")
326
+ if main_mod and hasattr(main_mod, "subscriptions_col"):
327
+ subs_col = main_mod.subscriptions_col
328
+ except Exception:
329
+ pass
330
+
331
+ result = await ps.check_studio_plan(
332
+ email=email or "",
333
+ firebase_uid=user_id or "",
334
+ subscriptions_col=subs_col,
335
+ fail_open_on_outage=False,
336
+ )
337
+ data = result.to_dict() if hasattr(result, "to_dict") else {
338
+ "plan": getattr(result, "plan", "free"),
339
+ "subscribed": getattr(result, "subscribed", False),
340
+ "entitlements": getattr(result, "entitlements", None) or _features_for_plan("free"),
341
+ "matched_by": getattr(result, "matched_by", ""),
342
+ "status": getattr(result, "status", ""),
343
+ }
344
+ plan = (data.get("plan") or "free").lower()
345
+ if plan not in PLAN_CREDITS:
346
+ plan = "free"
347
+ data["plan"] = plan
348
+ data["entitlements"] = data.get("entitlements") or _features_for_plan(plan)
349
+ print(
350
+ f"[Studio] Polar plan uid={user_id}: plan={plan} "
351
+ f"matched_by={data.get('matched_by')} status={data.get('status')}"
352
+ )
353
+ return data
354
+ except Exception as e:
355
+ print(f"[Studio] polar_subs_studio error: {e}")
356
+ return {
357
+ "plan": "free",
358
+ "subscribed": False,
359
+ "entitlements": _features_for_plan("free"),
360
+ "matched_by": "error",
361
+ "error": str(e),
362
+ }
363
+
364
+
365
+ async def _check_polar_legacy(user_id: str) -> bool:
366
+ """Binary subscribed check (Kype polar_subscription or Mongo). Fail-closed."""
367
+ try:
368
+ main_mod = _sys.modules.get("main")
369
  if main_mod and hasattr(main_mod, "verify_polar_subscription"):
370
  email = await _resolve_email(user_id)
371
  result = await asyncio.wait_for(
372
  main_mod.verify_polar_subscription(email=email, firebase_uid=user_id),
373
+ timeout=4.0,
374
  )
375
  return bool(result)
376
  except asyncio.TimeoutError:
377
+ print(f"[Studio] Legacy Polar check timed out for {user_id}")
378
  except Exception as e:
379
+ print(f"[Studio] Legacy Polar check error: {e}")
 
380
  try:
381
  doc = await _db_find_one("subscriptions", {"user_id": user_id})
382
+ if doc and doc.get("status") == "active" and doc.get("tier") in (
383
+ "pro", "max", "business", "ultra", "premium"
384
+ ):
385
  return True
386
  except Exception:
387
  pass
388
  return False
389
 
390
+
391
+ async def _check_polar(user_id: str) -> bool:
392
+ """Backward-compatible bool: True if plan is any paid Studio tier."""
393
+ data = await _check_studio_plan(user_id)
394
+ return bool(data.get("subscribed")) or (data.get("plan") or "free") != "free"
395
+
396
+
397
  # ── FIREBASE EMAIL RESOLUTION ─────────────────────────────────────────────────
398
  _firebase_inited = False
399
  _fb_auth = None
 
480
  print(f"[Studio] Stats update error: {e}")
481
 
482
  # ── MODELS ────────────────────────────────────────────────────────────────────
483
+ BUILD_MODEL = "poolside/laguna-xs-2.1:free" # Fast model (was tencent/hy3:free β€” too slow)
484
+ STRONG_MODEL = "poolside/laguna-xs-2.1:free" # Strong model (for index.html only)
485
+ FAST_MODEL = "poolside/laguna-xs-2.1:free"
486
  FALLBACK_MODEL = "poolside/laguna-xs-2.1:free"
487
+ PLAN_MODEL = "poolside/laguna-xs-2.1:free"
488
+ FIX_MODEL = "poolside/laguna-xs-2.1:free"
489
 
490
  # ── SPEED OPTIMIZATIONS ───────────────────────────────────────────────────────
491
+ MAX_TOKENS_PER_CALL = 8000 # Was 18000 β€” most web files are under 4K tokens
492
  RATE_LIMIT_WAIT = 15 # Was 45 β€” enough for OpenRouter free tier
493
  MAX_BUILD_RETRIES = 2 # Was 3 β€” fail faster
494
  MAX_CONTINUATIONS = 3 # Was 6 β€” most files complete in 1 call
 
807
  if not message:
808
  return JSONResponse({"error": "Message required"}, status_code=400)
809
 
810
+ # Plan feature + credits (Max/Business only for /plan chat)
811
+ credits_info = await get_credits(user_id)
812
+ features = credits_info.get("features") or _features_for_plan(credits_info["tier"])
813
+ if not features.get("canPlan"):
814
+ return JSONResponse({
815
+ "error": "Planning before building is a Max feature. Upgrade to Max or Business.",
816
+ "credits": {
817
+ "remaining": credits_info["remaining"],
818
+ "total": credits_info["total"],
819
+ "tier": credits_info["tier"],
820
+ "plan": credits_info.get("plan", credits_info["tier"]),
821
+ "features": features,
822
+ },
823
+ }, status_code=402)
824
+ has_credits, remaining, total, tier = (
825
+ credits_info["remaining"] > 0,
826
+ credits_info["remaining"],
827
+ credits_info["total"],
828
+ credits_info["tier"],
829
+ )
830
  if not has_credits:
831
+ return JSONResponse({"error": "No credits remaining this month", "credits": {"remaining": 0, "total": total, "tier": tier, "plan": tier, "features": features}}, status_code=402)
832
 
833
  # Build conversation context from history
834
  conversation_context = ""
 
919
  if not files:
920
  return JSONResponse({"error": "No files to fix"}, status_code=400)
921
 
922
+ # Fix is Max/Business only + credits
923
+ credits_info = await get_credits(user_id)
924
+ features = credits_info.get("features") or _features_for_plan(credits_info["tier"])
925
+ if not features.get("canFix"):
926
+ return JSONResponse({
927
+ "error": "Fix bugs is a Max feature. Upgrade to Max or Business.",
928
+ "credits": {
929
+ "remaining": credits_info["remaining"],
930
+ "total": credits_info["total"],
931
+ "tier": credits_info["tier"],
932
+ "plan": credits_info.get("plan", credits_info["tier"]),
933
+ "features": features,
934
+ },
935
+ }, status_code=402)
936
+ has_credits, remaining, total, tier = (
937
+ credits_info["remaining"] > 0,
938
+ credits_info["remaining"],
939
+ credits_info["total"],
940
+ credits_info["tier"],
941
+ )
942
  if not has_credits:
943
+ return JSONResponse({"error": "No credits remaining", "credits": {"remaining": 0, "total": total, "tier": tier, "plan": tier, "features": features}}, status_code=402)
944
  consumed = await consume_credit(user_id, "fix", project_id)
945
  if not consumed:
946
  return JSONResponse({"error": "Could not consume credit"}, status_code=402)
 
1013
 
1014
  # ── CREDITS ENDPOINT ──────────────────────────────────────────────────────────
1015
  @router.get("/credits/{user_id}")
1016
+ async def get_user_credits(user_id: str, email: str = ""):
1017
+ """Get credit status + Studio plan/features for a user."""
1018
+ credits = await get_credits(user_id, email=email)
1019
  return {"user_id": user_id, **credits}
1020
 
1021
  # ── USAGE ENDPOINT (token stats for display) ──────────────────────────────────
1022
  @router.get("/usage/{user_id}")
1023
+ async def get_studio_usage(user_id: str, email: str = ""):
1024
+ """Credits + plan for Studio UI (stats / badge). Credits are the gate."""
1025
+ credits = await get_credits(user_id, email=email)
1026
  return {
1027
  "user_id": user_id,
1028
  "credits_remaining": credits["remaining"],
1029
  "credits_total": credits["total"],
1030
  "tier": credits["tier"],
1031
+ "plan": credits.get("plan", credits["tier"]),
1032
  "month": credits["month"],
1033
+ "features": credits.get("features") or _features_for_plan(credits["tier"]),
1034
+ "free_credits": PLAN_CREDITS["free"],
1035
+ "pro_credits": PLAN_CREDITS["pro"],
1036
+ "max_credits": PLAN_CREDITS["max"],
1037
+ "business_credits": PLAN_CREDITS["business"],
1038
+ "plan_credits": PLAN_CREDITS,
1039
  }
1040
 
1041
  # ── STATS ENDPOINT (admin) ────────────────────────────────────────────────────
 
1071
  if is_non_web_request(user_prompt):
1072
  yield sse("error", {"message": "Studio builds web apps only. Try a website, dashboard, or web tool."}); return
1073
 
1074
+ # Credit + plan check (polar_subs_studio)
1075
+ credits_info = await get_credits(user_id)
1076
+ remaining = credits_info["remaining"]
1077
+ total = credits_info["total"]
1078
+ tier = credits_info["tier"]
1079
+ features = credits_info.get("features") or _features_for_plan(tier)
1080
+ if remaining <= 0:
1081
+ yield sse("error", {"message": f"No credits remaining this month. You get {total} credits/month ({tier} plan). Upgrade for more builds.", "credits": {"remaining": 0, "total": total, "tier": tier, "plan": tier, "features": features}}); return
1082
+
1083
+ # File caps by plan
1084
+ if tier == "business":
1085
+ max_files = max(MAX_FILES_PRO, 20)
1086
+ elif tier in ("pro", "max"):
1087
+ max_files = MAX_FILES_PRO
1088
+ else:
1089
+ max_files = MAX_FILES_FREE
1090
 
1091
  yield sse("status", {"message": "Initialising Studio Engine..."})
1092
  yield sse("target", {"target": "web", "previewable": True})
1093
  yield sse("status", {"message": "Designing your app architecture..."})
1094
+ yield sse("credits", {"remaining": remaining, "total": total, "tier": tier, "plan": tier, "features": features})
1095
 
1096
  # PLANNER
1097
  plan = None