Spaces:
Paused

CBV01 commited on
Commit
14fbecd
·
1 Parent(s): ed191e7

Refine Monetization, Admin Template View, Plan Expiry, and Include/Exclude Logic

Browse files
backend/database.py CHANGED
@@ -310,6 +310,7 @@ def init_db():
310
  max_accounts INTEGER DEFAULT 1,
311
  max_daily_keywords INTEGER DEFAULT 5,
312
  scrape_limit INTEGER DEFAULT 50,
 
313
  has_premium_access INTEGER DEFAULT 0,
314
  perks TEXT -- JSON string of perks
315
  )""",
@@ -364,7 +365,9 @@ def init_db():
364
  ("max_daily_keywords", "INTEGER DEFAULT 5"),
365
  ("daily_keyword_count", "INTEGER DEFAULT 0"),
366
  ("last_reset_date", "TEXT"),
367
- ("permanent_excludes", "TEXT DEFAULT '[]'")
 
 
368
  ]
369
  for col_name, col_def in user_cols:
370
  try:
@@ -404,16 +407,16 @@ def init_db():
404
 
405
  # Seed default plans
406
  plans = [
407
- ('free', 'Free', 0, 20, 1, 5, 50, 0, '["20 campaigns / day", "1 Telegram account", "50 leads per search", "5 keyword searches / day"]'),
408
- ('basic', 'Basic', 2000, 50, 1, 10, 50, 1, '["50 campaigns / day", "1 Telegram account", "50 leads per search", "10 keyword searches / day"]'),
409
- ('standard', 'Standard', 3500, 150, 2, 15, 150, 1, '["150 campaigns / day", "2 Telegram accounts", "150 leads per search", "15 keyword searches / day"]'),
410
- ('premium', 'Premium', 5000, 300, 3, 30, 350, 1, '["300 campaigns / day", "3 Telegram accounts", "350 leads per search", "30 keyword searches / day"]'),
411
- ('unlimited', 'Unlimited', 10000, 999999, 99, 999999, 1000, 1, '["Unlimited everything", "Priority support"]')
412
  ]
413
  for p in plans:
414
  conn.execute("""INSERT OR IGNORE INTO plans
415
- (key, name, price, max_daily_campaigns, max_accounts, max_daily_keywords, scrape_limit, has_premium_access, perks)
416
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""", p)
417
 
418
  # Seed default settings
419
  conn.execute("INSERT OR IGNORE INTO system_settings (key, value) VALUES ('admin_password', 'admin123')")
 
310
  max_accounts INTEGER DEFAULT 1,
311
  max_daily_keywords INTEGER DEFAULT 5,
312
  scrape_limit INTEGER DEFAULT 50,
313
+ max_templates INTEGER DEFAULT 1,
314
  has_premium_access INTEGER DEFAULT 0,
315
  perks TEXT -- JSON string of perks
316
  )""",
 
365
  ("max_daily_keywords", "INTEGER DEFAULT 5"),
366
  ("daily_keyword_count", "INTEGER DEFAULT 0"),
367
  ("last_reset_date", "TEXT"),
368
+ ("permanent_excludes", "TEXT DEFAULT '[]'"),
369
+ ("plan_activated_at", "TEXT"),
370
+ ("plan_expires_at", "TEXT")
371
  ]
372
  for col_name, col_def in user_cols:
373
  try:
 
407
 
408
  # Seed default plans
409
  plans = [
410
+ ('free', 'Free', 0, 20, 1, 5, 50, 1, 0, '["20 campaigns / day", "1 Telegram account", "50 leads per search", "5 keyword searches / day", "1 Message Template"]'),
411
+ ('basic', 'Basic', 2000, 50, 1, 10, 50, 1, 1, '["50 campaigns / day", "1 Telegram account", "50 leads per search", "10 keyword searches / day", "1 Message Template"]'),
412
+ ('standard', 'Standard', 3500, 150, 2, 15, 150, 2, 1, '["150 campaigns / day", "2 Telegram accounts", "150 leads per search", "15 keyword searches / day", "2 Message Templates"]'),
413
+ ('premium', 'Premium', 5000, 300, 3, 30, 350, 3, 1, '["300 campaigns / day", "3 Telegram accounts", "350 leads per search", "30 keyword searches / day", "3 Message Templates"]'),
414
+ ('unlimited', 'Unlimited', 10000, 999999, 99, 999999, 1000, 999, 1, '["Unlimited everything", "Priority support"]')
415
  ]
416
  for p in plans:
417
  conn.execute("""INSERT OR IGNORE INTO plans
418
+ (key, name, price, max_daily_campaigns, max_accounts, max_daily_keywords, scrape_limit, max_templates, has_premium_access, perks)
419
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", p)
420
 
421
  # Seed default settings
422
  conn.execute("INSERT OR IGNORE INTO system_settings (key, value) VALUES ('admin_password', 'admin123')")
backend/main.py CHANGED
@@ -55,8 +55,8 @@ def log_debug(msg: str):
55
  # --- Tiered Plan Configurations (Dynamic from DB) ---
56
  def get_plan_configs() -> Dict[str, Dict[str, Any]]:
57
  configs: Dict[str, Dict[str, Any]] = {
58
- "free": {"max_daily_campaigns": 20, "max_accounts": 1, "max_daily_keywords": 5, "scrape_limit": 50, "has_premium_access": False},
59
- "unlimited": {"max_daily_campaigns": 999999, "max_accounts": 99, "max_daily_keywords": 999999, "scrape_limit": 1000, "has_premium_access": True}
60
  }
61
  conn = None
62
  try:
@@ -70,6 +70,7 @@ def get_plan_configs() -> Dict[str, Dict[str, Any]]:
70
  "max_accounts": r["max_accounts"],
71
  "max_daily_keywords": r["max_daily_keywords"],
72
  "scrape_limit": r["scrape_limit"],
 
73
  "has_premium_access": bool(r["has_premium_access"]),
74
  "perks": json.loads(r["perks"]) if r["perks"] else []
75
  }
@@ -95,6 +96,24 @@ def check_and_reset_daily_limits(conn, user_id, user_row):
95
  )
96
  if hasattr(conn, "commit"): conn.commit()
97
  return True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  return False
99
 
100
  @asynccontextmanager
@@ -1955,7 +1974,9 @@ async def get_monetization_users(admin_id: str = Depends(get_current_admin)):
1955
  daily_keyword_count=r["daily_keyword_count"],
1956
  is_approved=r["is_approved"],
1957
  total_scraped=r["total_scraped"],
1958
- payment_proof=r["payment_proof"]
 
 
1959
  ) for r in rows]}
1960
 
1961
  @app.post("/api/admin/monetization/users/{uid}/vitals")
@@ -1968,17 +1989,26 @@ async def update_user_vitals(uid: str, req: UserVitalsUpdateRequest, admin_id: s
1968
  m_acc = req.max_accounts if req.max_accounts is not None else plan_cfg["max_accounts"]
1969
  m_camp = req.max_daily_campaigns if req.max_daily_campaigns is not None else plan_cfg["max_daily_campaigns"]
1970
  m_key = req.max_daily_keywords if req.max_daily_keywords is not None else plan_cfg["max_daily_keywords"]
 
 
 
 
 
 
 
 
1971
 
1972
  conn.execute(
1973
  """UPDATE users SET
1974
  plan = ?, scrape_limit = ?, max_accounts = ?,
1975
  max_daily_campaigns = ?, max_daily_keywords = ?,
1976
- is_approved = ? WHERE id = ?""",
1977
- (req.plan, s_limit, m_acc, m_camp, m_key, req.is_approved, uid)
 
1978
  )
1979
  if hasattr(conn, "commit"): conn.commit()
1980
  if hasattr(conn, "close"): conn.close()
1981
- return {"status": "success"}
1982
 
1983
  @app.get("/api/admin/monetization/coupons")
1984
  async def get_coupons_admin(admin_id: str = Depends(get_current_admin)):
@@ -2144,15 +2174,21 @@ async def verify_paystack(req: PaystackVerifyRequest, user_id: str = Depends(get
2144
  plan_key = req.plan_key
2145
  plan_cfg = PLAN_CONFIGS.get(plan_key, PLAN_CONFIGS["basic"])
2146
 
 
 
 
 
 
2147
  conn = get_db_connection()
2148
  try:
2149
  conn.execute(
2150
  """UPDATE users SET
2151
  plan = ?, is_approved = 1, payment_proof = ?,
2152
  scrape_limit = NULL, max_accounts = NULL,
2153
- max_daily_campaigns = NULL, max_daily_keywords = NULL
 
2154
  WHERE id = ?""",
2155
- (plan_key, f"Paystack:{req.reference}", user_id)
2156
  )
2157
  conn.execute(
2158
  "INSERT INTO payments (user_id, amount, proof_details, status) VALUES (?, ?, ?, ?)",
@@ -2193,10 +2229,15 @@ async def paystack_webhook(request: Request):
2193
  if user:
2194
  u_id = user["id"]
2195
  plan_cfg = PLAN_CONFIGS.get(plan_key, PLAN_CONFIGS["basic"])
 
 
 
 
2196
  conn.execute(
2197
- """UPDATE users SET plan = ?, is_approved = 1, payment_proof = ?
 
2198
  WHERE id = ? AND (plan = 'free' OR plan IS NULL)""",
2199
- (plan_key, f"Webhook:{ref}", u_id)
2200
  )
2201
  if hasattr(conn, "commit"): conn.commit()
2202
  finally:
@@ -2459,11 +2500,36 @@ async def get_templates(user_id: str = Depends(get_current_user_id)):
2459
  @app.post("/api/telegram/templates")
2460
  async def create_template(req: TemplateRequest, user_id: str = Depends(get_current_user_id)):
2461
  conn = get_db_connection()
2462
- conn.execute("INSERT INTO templates (user_id, name, content) VALUES (?, ?, ?)", (user_id, req.name, req.content))
2463
- if hasattr(conn, "commit"): conn.commit()
2464
- if hasattr(conn, "close"): conn.close()
 
 
 
 
 
 
 
 
 
 
 
 
2465
  return {"status": "success"}
2466
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2467
  @app.delete("/api/telegram/templates/{template_id}")
2468
  async def delete_template(template_id: int, user_id: str = Depends(get_current_user_id)):
2469
  conn = get_db_connection()
 
55
  # --- Tiered Plan Configurations (Dynamic from DB) ---
56
  def get_plan_configs() -> Dict[str, Dict[str, Any]]:
57
  configs: Dict[str, Dict[str, Any]] = {
58
+ "free": {"max_daily_campaigns": 20, "max_accounts": 1, "max_daily_keywords": 5, "scrape_limit": 50, "max_templates": 1, "has_premium_access": False},
59
+ "unlimited": {"max_daily_campaigns": 999999, "max_accounts": 99, "max_daily_keywords": 999999, "scrape_limit": 1000, "max_templates": 999, "has_premium_access": True}
60
  }
61
  conn = None
62
  try:
 
70
  "max_accounts": r["max_accounts"],
71
  "max_daily_keywords": r["max_daily_keywords"],
72
  "scrape_limit": r["scrape_limit"],
73
+ "max_templates": r["max_templates"],
74
  "has_premium_access": bool(r["has_premium_access"]),
75
  "perks": json.loads(r["perks"]) if r["perks"] else []
76
  }
 
96
  )
97
  if hasattr(conn, "commit"): conn.commit()
98
  return True
99
+
100
+ # Subscription Expiry Check
101
+ expiry_date_str = user_row["plan_expires_at"]
102
+ if expiry_date_str and user_row["plan"] != "free":
103
+ try:
104
+ # Format: 2024-03-24T12:00
105
+ expiry_dt = datetime.fromisoformat(expiry_date_str.replace('Z', ''))
106
+ if datetime.now() > expiry_dt:
107
+ log_debug(f"SUBSCRIPTION: Plan expired for {user_id}. Resetting to Free.")
108
+ conn.execute(
109
+ "UPDATE users SET plan = 'free', plan_expires_at = NULL, is_approved = 0 WHERE id = ?",
110
+ (user_id,)
111
+ )
112
+ if hasattr(conn, "commit"): conn.commit()
113
+ return True
114
+ except:
115
+ pass
116
+
117
  return False
118
 
119
  @asynccontextmanager
 
1974
  daily_keyword_count=r["daily_keyword_count"],
1975
  is_approved=r["is_approved"],
1976
  total_scraped=r["total_scraped"],
1977
+ payment_proof=r["payment_proof"],
1978
+ plan_activated_at=r["plan_activated_at"],
1979
+ plan_expires_at=r["plan_expires_at"]
1980
  ) for r in rows]}
1981
 
1982
  @app.post("/api/admin/monetization/users/{uid}/vitals")
 
1989
  m_acc = req.max_accounts if req.max_accounts is not None else plan_cfg["max_accounts"]
1990
  m_camp = req.max_daily_campaigns if req.max_daily_campaigns is not None else plan_cfg["max_daily_campaigns"]
1991
  m_key = req.max_daily_keywords if req.max_daily_keywords is not None else plan_cfg["max_daily_keywords"]
1992
+
1993
+ # Handle Subscription Dates
1994
+ activated_at = None
1995
+ expires_at = None
1996
+ if req.plan != 'free' and req.is_approved:
1997
+ now = datetime.now()
1998
+ activated_at = now.strftime('%Y-%m-%dT%H:%M')
1999
+ expires_at = (now + timedelta(days=30)).strftime('%Y-%m-%dT%H:%M')
2000
 
2001
  conn.execute(
2002
  """UPDATE users SET
2003
  plan = ?, scrape_limit = ?, max_accounts = ?,
2004
  max_daily_campaigns = ?, max_daily_keywords = ?,
2005
+ is_approved = ?, plan_activated_at = ?, plan_expires_at = ?
2006
+ WHERE id = ?""",
2007
+ (req.plan, s_limit, m_acc, m_camp, m_key, req.is_approved, activated_at, expires_at, uid)
2008
  )
2009
  if hasattr(conn, "commit"): conn.commit()
2010
  if hasattr(conn, "close"): conn.close()
2011
+ return {"status": "success", "activated_at": activated_at, "expires_at": expires_at}
2012
 
2013
  @app.get("/api/admin/monetization/coupons")
2014
  async def get_coupons_admin(admin_id: str = Depends(get_current_admin)):
 
2174
  plan_key = req.plan_key
2175
  plan_cfg = PLAN_CONFIGS.get(plan_key, PLAN_CONFIGS["basic"])
2176
 
2177
+ # Subscription timing
2178
+ now = datetime.now()
2179
+ act_date = now.strftime('%Y-%m-%dT%H:%M')
2180
+ exp_date = (now + timedelta(days=30)).strftime('%Y-%m-%dT%H:%M')
2181
+
2182
  conn = get_db_connection()
2183
  try:
2184
  conn.execute(
2185
  """UPDATE users SET
2186
  plan = ?, is_approved = 1, payment_proof = ?,
2187
  scrape_limit = NULL, max_accounts = NULL,
2188
+ max_daily_campaigns = NULL, max_daily_keywords = NULL,
2189
+ plan_activated_at = ?, plan_expires_at = ?
2190
  WHERE id = ?""",
2191
+ (plan_key, f"Paystack:{req.reference}", act_date, exp_date, user_id)
2192
  )
2193
  conn.execute(
2194
  "INSERT INTO payments (user_id, amount, proof_details, status) VALUES (?, ?, ?, ?)",
 
2229
  if user:
2230
  u_id = user["id"]
2231
  plan_cfg = PLAN_CONFIGS.get(plan_key, PLAN_CONFIGS["basic"])
2232
+ now = datetime.now()
2233
+ act_date = now.strftime('%Y-%m-%dT%H:%M')
2234
+ exp_date = (now + timedelta(days=30)).strftime('%Y-%m-%dT%H:%M')
2235
+
2236
  conn.execute(
2237
+ """UPDATE users SET plan = ?, is_approved = 1, payment_proof = ?,
2238
+ plan_activated_at = ?, plan_expires_at = ?
2239
  WHERE id = ? AND (plan = 'free' OR plan IS NULL)""",
2240
+ (plan_key, f"Webhook:{ref}", act_date, exp_date, u_id)
2241
  )
2242
  if hasattr(conn, "commit"): conn.commit()
2243
  finally:
 
2500
  @app.post("/api/telegram/templates")
2501
  async def create_template(req: TemplateRequest, user_id: str = Depends(get_current_user_id)):
2502
  conn = get_db_connection()
2503
+ try:
2504
+ # Check limits
2505
+ u_row = conn.execute("SELECT plan FROM users WHERE id = ?", (user_id,)).fetchone()
2506
+ plan = u_row["plan"] if u_row else "free"
2507
+ plan_cfg = PLAN_CONFIGS.get(plan, PLAN_CONFIGS["free"])
2508
+ max_templates = plan_cfg.get("max_templates", 1)
2509
+
2510
+ current_count = conn.execute("SELECT COUNT(*) FROM templates WHERE user_id = ?", (user_id,)).fetchone()[0]
2511
+ if current_count >= max_templates:
2512
+ raise HTTPException(status_code=403, detail=f"Your {plan.capitalize()} plan only allows {max_templates} templates.")
2513
+
2514
+ conn.execute("INSERT INTO templates (user_id, name, content) VALUES (?, ?, ?)", (user_id, req.name, req.content))
2515
+ if hasattr(conn, "commit"): conn.commit()
2516
+ finally:
2517
+ if hasattr(conn, "close"): conn.close()
2518
  return {"status": "success"}
2519
 
2520
+ @app.get("/api/admin/templates")
2521
+ async def admin_get_all_templates(admin_id: str = Depends(get_current_admin)):
2522
+ """Allows admin to see all templates from all users."""
2523
+ conn = get_db_connection()
2524
+ rows = conn.execute("""
2525
+ SELECT t.*, u.username as creator
2526
+ FROM templates t
2527
+ JOIN users u ON t.user_id = u.id
2528
+ ORDER BY t.created_at DESC
2529
+ """).fetchall()
2530
+ if hasattr(conn, "close"): conn.close()
2531
+ return {"templates": [dict(r) for r in rows]}
2532
+
2533
  @app.delete("/api/telegram/templates/{template_id}")
2534
  async def delete_template(template_id: int, user_id: str = Depends(get_current_user_id)):
2535
  conn = get_db_connection()
frontend/src/app/admin/page.tsx CHANGED
@@ -35,6 +35,19 @@ export default function AdminDashboard() {
35
  const [broadcastType, setBroadcastType] = useState('info');
36
  const [sendingBroadcast, setSendingBroadcast] = useState(false);
37
  const [selectedUser, setSelectedUser] = useState<any>(null);
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  const [userDetails, setUserDetails] = useState<any>(null);
39
  const [loadingDetails, setLoadingDetails] = useState(false);
40
  const [errorMsg, setErrorMsg] = useState('');
@@ -133,6 +146,8 @@ export default function AdminDashboard() {
133
  fetchMonetizationData();
134
  } else if (activeTab === 'packages') {
135
  fetchPlans();
 
 
136
  }
137
  }, [activeTab]);
138
 
@@ -230,7 +245,7 @@ export default function AdminDashboard() {
230
  </div>
231
 
232
  <div className="flex bg-white/[0.03] backdrop-blur-3xl p-1.5 rounded-2xl border border-white/5 overflow-x-auto">
233
- {['overview', 'users', 'packages', 'monetization', 'settings', 'maintenance'].map((tab) => (
234
  <button
235
  key={tab}
236
  onClick={() => setActiveTab(tab)}
@@ -589,6 +604,58 @@ export default function AdminDashboard() {
589
  )}
590
  </div>
591
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
592
  {activeTab === 'settings' && (
593
  <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
594
  <div className="bg-white/5 border border-white/5 p-8 rounded-3xl space-y-6">
@@ -835,26 +902,31 @@ export default function AdminDashboard() {
835
  <div className="text-[10px] text-foreground/30 font-mono">ID: {u.id}</div>
836
  </td>
837
  <td className="px-6 py-4">
838
- <select
839
- value={u.plan}
840
- onChange={async (e) => {
841
- const newPlan = e.target.value;
842
- // For manual plan changes, we let the backend handle the defaults
843
- await apiFetch(`/api/admin/monetization/users/${u.id}/vitals`, {
844
- method: 'POST',
845
- body: JSON.stringify({ plan: newPlan, is_approved: newPlan === 'free' ? 0 : 1 })
846
- // Pass is_approved=1 for any paid plan
847
- });
848
- fetchMonetizationData();
849
- }}
850
- className={`bg-white/5 border border-white/10 rounded-lg px-3 py-1.5 text-[10px] font-black uppercase transition-all ${u.plan !== 'free' ? 'text-indigo-400 border-indigo-400/30' : 'text-foreground/20'}`}
851
- >
852
- <option value="free">Free</option>
853
- <option value="basic">Basic (50c)</option>
854
- <option value="standard">Standard (150c)</option>
855
- <option value="premium">Premium (300c)</option>
856
- <option value="unlimited">Unlimited (Admin Only)</option>
857
- </select>
 
 
 
 
 
858
  </td>
859
  <td className="px-6 py-4">
860
  <div className="flex flex-wrap gap-2 max-w-[180px]">
@@ -889,16 +961,19 @@ export default function AdminDashboard() {
889
  )}
890
  </td>
891
  <td className="px-6 py-4">
892
- {u.payment_proof && u.plan === 'free' && (
893
  <button
894
  onClick={async () => {
895
- // Default to premium on manual approval unless specified
896
- await apiFetch(`/api/admin/monetization/users/${u.id}/vitals`, {
897
- method: 'POST',
898
- body: JSON.stringify({ plan: 'premium', is_approved: 1 })
899
- });
900
- setSuccessMsg(`Approved ${u.username}!`);
901
- fetchMonetizationData();
 
 
 
902
  }}
903
  className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-emerald-500 text-black text-[10px] font-bold uppercase transition-all hover:bg-emerald-400 active:scale-95 shadow-lg shadow-emerald-500/20"
904
  >
 
35
  const [broadcastType, setBroadcastType] = useState('info');
36
  const [sendingBroadcast, setSendingBroadcast] = useState(false);
37
  const [selectedUser, setSelectedUser] = useState<any>(null);
38
+ const [globalTemplates, setGlobalTemplates] = useState<any[]>([]);
39
+
40
+ const fetchGlobalTemplates = async () => {
41
+ try {
42
+ const res = await apiFetch('/api/admin/templates');
43
+ if (res.ok) {
44
+ const data = await res.json();
45
+ setGlobalTemplates(data.templates || []);
46
+ }
47
+ } catch (e) {
48
+ console.error("Failed to fetch global templates");
49
+ }
50
+ };
51
  const [userDetails, setUserDetails] = useState<any>(null);
52
  const [loadingDetails, setLoadingDetails] = useState(false);
53
  const [errorMsg, setErrorMsg] = useState('');
 
146
  fetchMonetizationData();
147
  } else if (activeTab === 'packages') {
148
  fetchPlans();
149
+ } else if (activeTab === 'templates') { // Added condition for templates tab
150
+ fetchGlobalTemplates();
151
  }
152
  }, [activeTab]);
153
 
 
245
  </div>
246
 
247
  <div className="flex bg-white/[0.03] backdrop-blur-3xl p-1.5 rounded-2xl border border-white/5 overflow-x-auto">
248
+ {['overview', 'users', 'packages', 'monetization', 'templates', 'settings', 'maintenance'].map((tab) => (
249
  <button
250
  key={tab}
251
  onClick={() => setActiveTab(tab)}
 
604
  )}
605
  </div>
606
  )}
607
+ {activeTab === 'templates' && (
608
+ <div className="bg-white/5 border border-white/5 rounded-[32px] overflow-hidden">
609
+ <div className="p-8 border-b border-white/5 flex items-center justify-between">
610
+ <div className="flex items-center gap-3">
611
+ <div className="p-3 bg-indigo-500/10 rounded-2xl text-indigo-400">
612
+ <FileText size={24} />
613
+ </div>
614
+ <div>
615
+ <h3 className="font-bold text-xl">Global Templates</h3>
616
+ <p className="text-xs text-foreground/40 uppercase font-bold tracking-widest mt-1">View all user-created message templates</p>
617
+ </div>
618
+ </div>
619
+ </div>
620
+ <div className="overflow-x-auto">
621
+ <table className="w-full text-left">
622
+ <thead className="text-[10px] uppercase tracking-[0.2em] text-foreground/30 border-b border-white/5">
623
+ <tr>
624
+ <th className="px-6 py-4 font-bold">Creator</th>
625
+ <th className="px-6 py-4 font-bold">Template Name</th>
626
+ <th className="px-6 py-4 font-bold">Content Preview</th>
627
+ <th className="px-6 py-4 font-bold">Created At</th>
628
+ </tr>
629
+ </thead>
630
+ <tbody className="divide-y divide-white/5">
631
+ {globalTemplates.map((t) => (
632
+ <tr key={t.id} className="hover:bg-white/[0.02] transition-colors">
633
+ <td className="px-6 py-4">
634
+ <div className="text-sm font-bold text-foreground">{t.creator}</div>
635
+ <div className="text-[10px] font-mono text-foreground/30">{t.user_id}</div>
636
+ </td>
637
+ <td className="px-6 py-4">
638
+ <div className="text-sm font-bold text-indigo-400">{t.name}</div>
639
+ </td>
640
+ <td className="px-6 py-4">
641
+ <div className="text-xs text-foreground/60 max-w-[400px] truncate">{t.content}</div>
642
+ </td>
643
+ <td className="px-6 py-4">
644
+ <div className="text-[10px] text-foreground/40">{new Date(t.created_at).toLocaleString()}</div>
645
+ </td>
646
+ </tr>
647
+ ))}
648
+ {globalTemplates.length === 0 && (
649
+ <tr>
650
+ <td colSpan={4} className="px-6 py-12 text-center text-foreground/20 italic">No templates found</td>
651
+ </tr>
652
+ )}
653
+ </tbody>
654
+ </table>
655
+ </div>
656
+ </div>
657
+ )}
658
+
659
  {activeTab === 'settings' && (
660
  <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
661
  <div className="bg-white/5 border border-white/5 p-8 rounded-3xl space-y-6">
 
902
  <div className="text-[10px] text-foreground/30 font-mono">ID: {u.id}</div>
903
  </td>
904
  <td className="px-6 py-4">
905
+ <div className="flex flex-col">
906
+ <select
907
+ value={u.plan}
908
+ onChange={async (e) => {
909
+ const newPlan = e.target.value;
910
+ await apiFetch(`/api/admin/monetization/users/${u.id}/vitals`, {
911
+ method: 'POST',
912
+ body: JSON.stringify({ plan: newPlan, is_approved: newPlan === 'free' ? 0 : 1 })
913
+ });
914
+ fetchMonetizationData();
915
+ }}
916
+ className={`bg-white/5 border border-white/10 rounded-lg px-3 py-1.5 text-[10px] font-black uppercase transition-all ${u.plan !== 'free' ? 'text-indigo-400 border-indigo-400/30' : 'text-foreground/20'}`}
917
+ >
918
+ <option value="free">Free</option>
919
+ <option value="basic">Basic (50c)</option>
920
+ <option value="standard">Standard (150c)</option>
921
+ <option value="premium">Premium (300c)</option>
922
+ <option value="unlimited">Unlimited (Admin Only)</option>
923
+ </select>
924
+ {u.plan_expires_at && (
925
+ <div className="text-[9px] font-bold text-foreground/40 mt-1 uppercase tracking-tighter">
926
+ Exp: {new Date(u.plan_expires_at).toLocaleDateString()}
927
+ </div>
928
+ )}
929
+ </div>
930
  </td>
931
  <td className="px-6 py-4">
932
  <div className="flex flex-wrap gap-2 max-w-[180px]">
 
961
  )}
962
  </td>
963
  <td className="px-6 py-4">
964
+ {u.payment_proof && u.is_approved === 0 && (
965
  <button
966
  onClick={async () => {
967
+ // Always use the plan currently selected in the dropdown
968
+ const planToApprove = u.plan === 'free' ? 'premium' : u.plan;
969
+ if (confirm(`Approve ${planToApprove} plan for ${u.username}?`)) {
970
+ await apiFetch(`/api/admin/monetization/users/${u.id}/vitals`, {
971
+ method: 'POST',
972
+ body: JSON.stringify({ plan: planToApprove, is_approved: 1 })
973
+ });
974
+ setSuccessMsg(`Approved ${u.username} for ${planToApprove}!`);
975
+ fetchMonetizationData();
976
+ }
977
  }}
978
  className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-emerald-500 text-black text-[10px] font-bold uppercase transition-all hover:bg-emerald-400 active:scale-95 shadow-lg shadow-emerald-500/20"
979
  >