CBV01 commited on
Commit
bfaa533
·
1 Parent(s): de1901b

Refine campaign management, dynamic limits, and premium UI aesthetics

Browse files
backend/main.py CHANGED
@@ -2167,6 +2167,23 @@ async def bulk_delete_members(req: BulkDeleteRequest, user_id: str = Depends(get
2167
 
2168
  # Removed redundant get_accounts (already refactored earlier)
2169
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2170
  @app.get("/api/telegram/campaigns")
2171
  async def get_campaigns(user_id: str = Depends(get_current_user_id)):
2172
  conn = get_db_connection()
@@ -2203,14 +2220,12 @@ async def create_campaign(req: CampaignRequest, user_id: str = Depends(get_curre
2203
  current_daily = user_row["daily_campaign_count"] or 0
2204
  groups_count = len(req.groups)
2205
 
2206
- if current_daily + groups_count > max_daily and plan != "unlimited":
2207
  if hasattr(conn, "close"): conn.close()
2208
- raise HTTPException(status_code=403, detail=f"Daily group selection limit reached. You can only select {max_daily - current_daily} more group(s) today on your current plan.")
2209
 
2210
- # Increment usage
2211
- if plan != "unlimited":
2212
- conn.execute("UPDATE users SET daily_campaign_count = daily_campaign_count + ? WHERE id = ?", (groups_count, user_id))
2213
- if hasattr(conn, "commit"): conn.commit()
2214
 
2215
  try:
2216
  # The schedule_time sent by the frontend must already be in UTC.
@@ -2643,6 +2658,32 @@ async def task_poller():
2643
  sent_ok_stats = [0]
2644
  # High Fidelity Extraction Loop
2645
  for raw_group in target_groups:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2646
  try:
2647
  # Clean and resolve ID format (int vs str)
2648
  group = str(raw_group).strip()
@@ -2708,6 +2749,8 @@ async def task_poller():
2708
  # INSTANT COUNT UPDATE (Every message)
2709
  u_conn = get_db_connection()
2710
  u_conn.execute("UPDATE tasks SET sent_count = ? WHERE id = ?", (sent_ok_stats[0], task_id))
 
 
2711
  if hasattr(u_conn, "commit"): u_conn.commit()
2712
 
2713
  # BATCH LOG UPDATE (Every 5 messages - prevents DB choking)
@@ -2738,18 +2781,27 @@ async def task_poller():
2738
 
2739
  # Final Batch Update (One Connection)
2740
  conn = get_db_connection()
2741
- if int(interval) > 0:
2742
- new_time = (datetime.now(timezone.utc) + timedelta(hours=int(interval))).strftime('%Y-%m-%dT%H:%M')
2743
- # RESET sent_count TO 0 for next batch cycle
2744
- conn.execute(
2745
- "UPDATE tasks SET status = 'pending', scheduled_time = ?, batch_number = batch_number + 1, sent_count = 0, failed_groups = ? WHERE id = ?",
2746
- (new_time, json.dumps(failed_list), task_id)
2747
- )
2748
- print(f"BKG: Task {task_id} rescheduled for {new_time} (Successful: {sent_ok_stats[0]})")
2749
- else:
2750
- conn.execute("UPDATE tasks SET status = 'completed', sent_count = ?, failed_groups = ? WHERE id = ?", (sent_ok_stats[0], json.dumps(failed_list), task_id))
2751
- print(f"BKG: Task {task_id} marked COMPLETED (Successful: {sent_ok_stats[0]})")
2752
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2753
  if hasattr(conn, "commit"): conn.commit()
2754
  if hasattr(conn, "close"): conn.close()
2755
 
 
2167
 
2168
  # Removed redundant get_accounts (already refactored earlier)
2169
 
2170
+ @app.post("/api/telegram/campaigns/{task_id}/stop")
2171
+ async def stop_campaign(task_id: int, user_id: str = Depends(get_current_user_id)):
2172
+ conn = get_db_connection()
2173
+ try:
2174
+ # Verify ownership
2175
+ row = conn.execute("SELECT user_id FROM tasks WHERE id = ?", (task_id,)).fetchone()
2176
+ if not row:
2177
+ raise HTTPException(status_code=404, detail="Task not found")
2178
+ if row["user_id"] != user_id and user_id != "admin_virtual_id":
2179
+ raise HTTPException(status_code=403, detail="Unauthorized")
2180
+
2181
+ conn.execute("UPDATE tasks SET status = 'stopped' WHERE id = ?", (task_id,))
2182
+ if hasattr(conn, "commit"): conn.commit()
2183
+ return {"status": "success"}
2184
+ finally:
2185
+ if hasattr(conn, "close"): conn.close()
2186
+
2187
  @app.get("/api/telegram/campaigns")
2188
  async def get_campaigns(user_id: str = Depends(get_current_user_id)):
2189
  conn = get_db_connection()
 
2220
  current_daily = user_row["daily_campaign_count"] or 0
2221
  groups_count = len(req.groups)
2222
 
2223
+ if current_daily >= max_daily and plan != "unlimited":
2224
  if hasattr(conn, "close"): conn.close()
2225
+ raise HTTPException(status_code=403, detail=f"Daily limit reached ({max_daily}/{max_daily}). Upgrade your plan to send more.")
2226
 
2227
+ # WE NO LONGER INCREMENT HERE. WE INCREMENT ON SUCCESSFUL SEND IN THE BACKGROUND.
2228
+
 
 
2229
 
2230
  try:
2231
  # The schedule_time sent by the frontend must already be in UTC.
 
2658
  sent_ok_stats = [0]
2659
  # High Fidelity Extraction Loop
2660
  for raw_group in target_groups:
2661
+ # Dynamic Status Check (Abort if User Stopped the Campaign)
2662
+ status_conn = get_db_connection()
2663
+ current_status = status_conn.execute("SELECT status FROM tasks WHERE id = ?", (task_id,)).fetchone()
2664
+ if hasattr(status_conn, "close"): status_conn.close()
2665
+ if not current_status or current_status["status"] != "processing":
2666
+ log_debug(f"BKG_TASK[{task_id}]: Task externally aborted or stopped. Status: {current_status['status'] if current_status else 'None'}. Halting sender loop.")
2667
+ break
2668
+
2669
+ # Global User Limit Check (Enforce Plan Quotas in Real-Time)
2670
+ quota_conn = get_db_connection()
2671
+ try:
2672
+ u_row = quota_conn.execute("SELECT plan, daily_campaign_count, max_daily_campaigns FROM users WHERE id = ?", (u_id,)).fetchone()
2673
+ if u_row:
2674
+ u_plan = u_row["plan"] or "free"
2675
+ u_count = u_row["daily_campaign_count"] or 0
2676
+ u_cfg = PLAN_CONFIGS.get(u_plan, PLAN_CONFIGS["free"])
2677
+ u_max = u_row["max_daily_campaigns"] or u_cfg["max_daily_campaigns"]
2678
+
2679
+ if u_plan != "unlimited" and u_count >= u_max:
2680
+ log_debug(f"BKG_TASK[{task_id}]: GLOBAL QUOTA REACHED ({u_count}/{u_max}). Stopping campaign for today.")
2681
+ quota_conn.execute("UPDATE tasks SET status = 'completed' WHERE id = ?", (task_id,))
2682
+ if hasattr(quota_conn, "commit"): quota_conn.commit()
2683
+ break
2684
+ finally:
2685
+ if hasattr(quota_conn, "close"): quota_conn.close()
2686
+
2687
  try:
2688
  # Clean and resolve ID format (int vs str)
2689
  group = str(raw_group).strip()
 
2749
  # INSTANT COUNT UPDATE (Every message)
2750
  u_conn = get_db_connection()
2751
  u_conn.execute("UPDATE tasks SET sent_count = ? WHERE id = ?", (sent_ok_stats[0], task_id))
2752
+ # INCREMENT USER GLOBAL DAILY COUNT
2753
+ u_conn.execute("UPDATE users SET daily_campaign_count = daily_campaign_count + 1 WHERE id = ?", (u_id,))
2754
  if hasattr(u_conn, "commit"): u_conn.commit()
2755
 
2756
  # BATCH LOG UPDATE (Every 5 messages - prevents DB choking)
 
2781
 
2782
  # Final Batch Update (One Connection)
2783
  conn = get_db_connection()
2784
+ # Double check if it was stopped externally before saving final state
2785
+ final_status_row = conn.execute("SELECT status FROM tasks WHERE id = ?", (task_id,)).fetchone()
2786
+ current_status = final_status_row["status"] if final_status_row else "processing"
 
 
 
 
 
 
 
 
2787
 
2788
+ if current_status == "processing":
2789
+ if int(interval) > 0:
2790
+ new_time = (datetime.now(timezone.utc) + timedelta(hours=int(interval))).strftime('%Y-%m-%dT%H:%M')
2791
+ # RESET sent_count TO 0 for next batch cycle
2792
+ conn.execute(
2793
+ "UPDATE tasks SET status = 'pending', scheduled_time = ?, batch_number = batch_number + 1, sent_count = 0, failed_groups = ? WHERE id = ?",
2794
+ (new_time, json.dumps(failed_list), task_id)
2795
+ )
2796
+ print(f"BKG: Task {task_id} rescheduled for {new_time} (Successful: {sent_ok_stats[0]})")
2797
+ else:
2798
+ conn.execute("UPDATE tasks SET status = 'completed', sent_count = ?, failed_groups = ? WHERE id = ?", (sent_ok_stats[0], json.dumps(failed_list), task_id))
2799
+ print(f"BKG: Task {task_id} marked COMPLETED (Successful: {sent_ok_stats[0]})")
2800
+ else:
2801
+ log_debug(f"BKG: Task {task_id} already marked as {current_status}, skipping auto-complete.")
2802
+ # We still update the final stats so the UI is accurate
2803
+ conn.execute("UPDATE tasks SET sent_count = ?, failed_groups = ? WHERE id = ?", (sent_ok_stats[0], json.dumps(failed_list), task_id))
2804
+
2805
  if hasattr(conn, "commit"): conn.commit()
2806
  if hasattr(conn, "close"): conn.close()
2807
 
check_turso.py DELETED
@@ -1,42 +0,0 @@
1
- import os
2
- import sys
3
- from dotenv import load_dotenv # type: ignore
4
-
5
- # Add current folder to sys.path
6
- sys.path.append(os.path.join(os.getcwd(), 'backend'))
7
-
8
- load_dotenv(os.path.join('backend', '.env'))
9
-
10
- from database import get_db_connection # type: ignore
11
-
12
- def check():
13
- url = os.getenv('TURSO_DATABASE_URL')
14
- if url:
15
- truncated_url = ""
16
- for i, char in enumerate(url):
17
- if i >= 30: break
18
- truncated_url += char
19
- print(f"URL: {truncated_url}...")
20
- else:
21
- print("URL: None")
22
- conn = get_db_connection()
23
- try:
24
- # Get users
25
- print("\n--- USERS ---")
26
- users = conn.execute("SELECT id, username, role FROM users").fetchall()
27
- for u in users:
28
- print(f"ID: {u[0]} | User: {u[1]} | Role: {u[2]}")
29
-
30
- # Get accounts
31
- print("\n--- ACCOUNTS ---")
32
- accounts = conn.execute("SELECT phone_number, user_id, status FROM accounts").fetchall()
33
- for a in accounts:
34
- print(f"Phone: {a[0]} | UID: {a[1]} | Status: {a[2]}")
35
-
36
- except Exception as e:
37
- print(f"Error: {e}")
38
- finally:
39
- if hasattr(conn, "close"): conn.close()
40
-
41
- if __name__ == "__main__":
42
- check()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/src/app/campaigns/page.tsx CHANGED
@@ -1,7 +1,7 @@
1
  "use client";
2
 
3
  import React, { useState, useEffect } from 'react';
4
- import { Megaphone, Plus, Clock, Users, X, Send, Calendar, CheckCircle2, Loader2, Search, Check, ChevronLeft, ChevronRight, Trash2, MessageCircle, AlertCircle } from 'lucide-react';
5
  import { apiFetch } from '@/lib/auth';
6
  import { Preloader } from '@/components/Preloader';
7
 
@@ -34,6 +34,22 @@ export default function CampaignsPage() {
34
  const [currentPage, setCurrentPage] = useState(1);
35
  const pageSize = 15;
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  useEffect(() => {
38
  const urlParams = new URLSearchParams(window.location.search);
39
  if (urlParams.get('preselect') === 'true') {
@@ -126,9 +142,13 @@ export default function CampaignsPage() {
126
  }, []);
127
 
128
  const toggleGroup = (id: string) => {
129
- setSelectedGroups(prev =>
130
- prev.includes(id) ? prev.filter(g => g !== id) : [...prev, id]
131
- );
 
 
 
 
132
  };
133
 
134
  const handleSubmit = async (e: React.FormEvent) => {
@@ -162,6 +182,8 @@ export default function CampaignsPage() {
162
  if (res.ok) {
163
  setSuccess(true);
164
  fetchCampaigns();
 
 
165
  setTimeout(() => {
166
  setSuccess(false);
167
  setIsCreating(false);
@@ -213,6 +235,20 @@ export default function CampaignsPage() {
213
  return text.includes('{') && text.includes('}') && text.includes('|');
214
  };
215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  const handleDelete = async (id: number) => {
217
  if (!confirm("Are you sure you want to delete this campaign?")) return;
218
  try {
@@ -362,6 +398,15 @@ export default function CampaignsPage() {
362
  } catch (e) {}
363
  return null;
364
  })()}
 
 
 
 
 
 
 
 
 
365
  <button
366
  onClick={() => handleEdit(camp)}
367
  className="p-2 text-foreground/40 hover:text-indigo-400 hover:bg-indigo-400/10 rounded-lg transition-all"
 
1
  "use client";
2
 
3
  import React, { useState, useEffect } from 'react';
4
+ import { Megaphone, Plus, Clock, Users, X, Send, Calendar, CheckCircle2, Loader2, Search, Check, ChevronLeft, ChevronRight, Trash2, MessageCircle, AlertCircle, Pause } from 'lucide-react';
5
  import { apiFetch } from '@/lib/auth';
6
  import { Preloader } from '@/components/Preloader';
7
 
 
34
  const [currentPage, setCurrentPage] = useState(1);
35
  const pageSize = 15;
36
 
37
+ const [userStatus, setUserStatus] = useState<any>(null);
38
+
39
+ const fetchStatus = async () => {
40
+ try {
41
+ const res = await apiFetch('/api/monetization/status');
42
+ if (res.ok) {
43
+ const data = await res.json();
44
+ setUserStatus(data);
45
+ }
46
+ } catch (e) {}
47
+ };
48
+
49
+ useEffect(() => {
50
+ fetchStatus();
51
+ }, []);
52
+
53
  useEffect(() => {
54
  const urlParams = new URLSearchParams(window.location.search);
55
  if (urlParams.get('preselect') === 'true') {
 
142
  }, []);
143
 
144
  const toggleGroup = (id: string) => {
145
+ setSelectedGroups(prev => {
146
+ if (prev.includes(id)) {
147
+ return prev.filter(g => g !== id);
148
+ } else {
149
+ return [...prev, id];
150
+ }
151
+ });
152
  };
153
 
154
  const handleSubmit = async (e: React.FormEvent) => {
 
182
  if (res.ok) {
183
  setSuccess(true);
184
  fetchCampaigns();
185
+ // Refresh sidebar usage counters
186
+ window.dispatchEvent(new Event('update_status'));
187
  setTimeout(() => {
188
  setSuccess(false);
189
  setIsCreating(false);
 
235
  return text.includes('{') && text.includes('}') && text.includes('|');
236
  };
237
 
238
+ const handleStop = async (id: number) => {
239
+ if (!confirm("Stop this campaign? It will cease all pending transmissions.")) return;
240
+ try {
241
+ const res = await apiFetch(`/api/telegram/campaigns/${id}/stop`, { method: 'POST' });
242
+ if (res.ok) {
243
+ fetchCampaigns();
244
+ } else {
245
+ alert('Failed to stop campaign.');
246
+ }
247
+ } catch (e: any) {
248
+ alert(e.message);
249
+ }
250
+ };
251
+
252
  const handleDelete = async (id: number) => {
253
  if (!confirm("Are you sure you want to delete this campaign?")) return;
254
  try {
 
398
  } catch (e) {}
399
  return null;
400
  })()}
401
+ {camp.status === 'processing' && (
402
+ <button
403
+ onClick={() => handleStop(camp.id)}
404
+ className="p-2 text-amber-500 hover:bg-amber-500/10 rounded-lg transition-all"
405
+ title="Stop Campaign"
406
+ >
407
+ <Pause size={16} />
408
+ </button>
409
+ )}
410
  <button
411
  onClick={() => handleEdit(camp)}
412
  className="p-2 text-foreground/40 hover:text-indigo-400 hover:bg-indigo-400/10 rounded-lg transition-all"
frontend/src/app/scraper/page.tsx CHANGED
@@ -242,6 +242,9 @@ export default function ScraperPage() {
242
  setResults([]);
243
  setScrapeStatus('Connecting to Scrape Engine...');
244
 
 
 
 
245
  if (abortControllerRef.current) abortControllerRef.current.abort();
246
  const controller = new AbortController();
247
  abortControllerRef.current = controller;
@@ -282,6 +285,8 @@ export default function ScraperPage() {
282
  });
283
  } else if (parsed.type === 'done') {
284
  setScrapeStatus('Scrape Complete!');
 
 
285
  } else if (parsed.type === 'error') {
286
  setError(parsed.msg);
287
  }
@@ -302,6 +307,8 @@ export default function ScraperPage() {
302
  } finally {
303
  setLoading(false);
304
  abortControllerRef.current = null;
 
 
305
  }
306
  };
307
 
 
242
  setResults([]);
243
  setScrapeStatus('Connecting to Scrape Engine...');
244
 
245
+ // Immediately notify sidebar – backend increments keyword count before streaming starts
246
+ window.dispatchEvent(new Event('update_status'));
247
+
248
  if (abortControllerRef.current) abortControllerRef.current.abort();
249
  const controller = new AbortController();
250
  abortControllerRef.current = controller;
 
285
  });
286
  } else if (parsed.type === 'done') {
287
  setScrapeStatus('Scrape Complete!');
288
+ // Notify sidebar to refresh keyword count
289
+ window.dispatchEvent(new Event('update_status'));
290
  } else if (parsed.type === 'error') {
291
  setError(parsed.msg);
292
  }
 
307
  } finally {
308
  setLoading(false);
309
  abortControllerRef.current = null;
310
+ // Always refresh sidebar status counts after scrape ends
311
+ window.dispatchEvent(new Event('update_status'));
312
  }
313
  };
314
 
frontend/src/components/MonetizationOverlay.tsx CHANGED
@@ -143,7 +143,7 @@ export const MonetizationOverlay: React.FC<MonetizationOverlayProps> = ({ childr
143
  {children}
144
 
145
  {isLocked && (
146
- <div className="fixed inset-0 z-[100] flex flex-col items-center justify-center p-4 h-[100dvh] w-screen overflow-hidden bg-background">
147
  {/* Dark Solid Backdrop for Mobile, Glass for Desktop */}
148
  <div className="absolute inset-0 bg-background/95 lg:bg-background/90 lg:backdrop-blur-3xl" />
149
  <div className="hidden lg:block absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[500px] h-[500px] bg-indigo-500/8 rounded-full blur-[120px] pointer-events-none" />
 
143
  {children}
144
 
145
  {isLocked && (
146
+ <div className="absolute inset-0 z-50 flex flex-col items-center justify-center p-4 overflow-hidden rounded-[inherit]">
147
  {/* Dark Solid Backdrop for Mobile, Glass for Desktop */}
148
  <div className="absolute inset-0 bg-background/95 lg:bg-background/90 lg:backdrop-blur-3xl" />
149
  <div className="hidden lg:block absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[500px] h-[500px] bg-indigo-500/8 rounded-full blur-[120px] pointer-events-none" />
frontend/src/components/Sidebar.tsx CHANGED
@@ -81,6 +81,25 @@ export function Sidebar({ children }: { children: React.ReactNode }) {
81
  }
82
  };
83
  fetchUser();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  }, [pathname, router]);
85
 
86
  const handleLogout = () => {
@@ -173,7 +192,7 @@ export function Sidebar({ children }: { children: React.ReactNode }) {
173
  </button>
174
 
175
  {/* Navigation Links */}
176
- <div className="space-y-1.5 flex-1 px-3">
177
  {navItems.map((item) => {
178
  const isActive = pathname === item.href;
179
  return (
 
81
  }
82
  };
83
  fetchUser();
84
+
85
+ const updateStatus = () => {
86
+ if (getToken()) {
87
+ apiFetch('/api/monetization/status')
88
+ .then(res => res.ok ? res.json() : null)
89
+ .then(data => {
90
+ if (data) setStatus(data);
91
+ })
92
+ .catch(() => {});
93
+ }
94
+ };
95
+
96
+ window.addEventListener('update_status', updateStatus);
97
+ const intervalId = setInterval(updateStatus, 15000);
98
+
99
+ return () => {
100
+ window.removeEventListener('update_status', updateStatus);
101
+ clearInterval(intervalId);
102
+ };
103
  }, [pathname, router]);
104
 
105
  const handleLogout = () => {
 
192
  </button>
193
 
194
  {/* Navigation Links */}
195
+ <div className="space-y-1.5 flex-1 px-3 overflow-y-auto overflow-x-hidden custom-scrollbar">
196
  {navItems.map((item) => {
197
  const isActive = pathname === item.href;
198
  return (