CBV01 commited on
Commit
ed191e7
·
1 Parent(s): 3b741cc

Implement Permanent Excludes, Templates selection, and UI refinements

Browse files
backend/database.py CHANGED
@@ -313,6 +313,13 @@ def init_db():
313
  has_premium_access INTEGER DEFAULT 0,
314
  perks TEXT -- JSON string of perks
315
  )""",
 
 
 
 
 
 
 
316
  ]
317
 
318
  conn = cast(Any, get_db_connection())
@@ -356,7 +363,8 @@ def init_db():
356
  ("daily_campaign_count", "INTEGER DEFAULT 0"),
357
  ("max_daily_keywords", "INTEGER DEFAULT 5"),
358
  ("daily_keyword_count", "INTEGER DEFAULT 0"),
359
- ("last_reset_date", "TEXT")
 
360
  ]
361
  for col_name, col_def in user_cols:
362
  try:
 
313
  has_premium_access INTEGER DEFAULT 0,
314
  perks TEXT -- JSON string of perks
315
  )""",
316
+ """CREATE TABLE IF NOT EXISTS templates (
317
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
318
+ user_id TEXT NOT NULL,
319
+ name TEXT NOT NULL,
320
+ content TEXT NOT NULL,
321
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
322
+ )""",
323
  ]
324
 
325
  conn = cast(Any, get_db_connection())
 
363
  ("daily_campaign_count", "INTEGER DEFAULT 0"),
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:
backend/main.py CHANGED
@@ -614,6 +614,13 @@ class CampaignRequest(BaseModel):
614
  class AdminLoginRequest(BaseModel):
615
  password: str
616
 
 
 
 
 
 
 
 
617
  # --- Authentication Endpoints ---
618
 
619
  @app.post("/api/auth/register")
@@ -1128,8 +1135,8 @@ async def _scrape_lyzem(base_query: str, max_pages: int = 10, queue: Optional[as
1128
  "source": "lyzem"
1129
  }
1130
  results.append(item)
1131
- # Fire and forget save to not block the stream
1132
- if user_id: asyncio.create_task(asyncio.to_thread(lambda: save_scraped_group(user_id, item))) # type: ignore
1133
  if queue:
1134
  await queue.put({"type": "result", "layer": 2, "data": item}) # type: ignore
1135
 
@@ -2441,6 +2448,48 @@ async def bulk_delete_members(req: BulkDeleteRequest, user_id: str = Depends(get
2441
 
2442
 
2443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2444
  # Removed redundant get_accounts (already refactored earlier)
2445
 
2446
  @app.post("/api/telegram/campaigns/{task_id}/toggle-pause")
@@ -2978,8 +3027,22 @@ async def task_poller():
2978
  except:
2979
  exclude_list = []
2980
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2981
  # Normalize exclude_list
2982
- exclude_list = [str(e).strip() for e in (exclude_list if isinstance(exclude_list, list) else [])]
2983
 
2984
  def recursive_spin(text: str) -> str:
2985
  text_obj = str(text)
 
614
  class AdminLoginRequest(BaseModel):
615
  password: str
616
 
617
+ class TemplateRequest(BaseModel):
618
+ name: str
619
+ content: str
620
+
621
+ class PermanentExcludeRequest(BaseModel):
622
+ ids: list[str]
623
+
624
  # --- Authentication Endpoints ---
625
 
626
  @app.post("/api/auth/register")
 
1135
  "source": "lyzem"
1136
  }
1137
  results.append(item)
1138
+ # Auto-saving disabled - user must manually select and save to leads
1139
+ # if user_id: asyncio.create_task(asyncio.to_thread(lambda: save_scraped_group(user_id, item))) # type: ignore
1140
  if queue:
1141
  await queue.put({"type": "result", "layer": 2, "data": item}) # type: ignore
1142
 
 
2448
 
2449
 
2450
 
2451
+ # --- TEMPLATES ENDPOINTS ---
2452
+ @app.get("/api/telegram/templates")
2453
+ async def get_templates(user_id: str = Depends(get_current_user_id)):
2454
+ conn = get_db_connection()
2455
+ rows = conn.execute("SELECT id, name, content FROM templates WHERE user_id = ? ORDER BY created_at DESC", (user_id,)).fetchall()
2456
+ if hasattr(conn, "close"): conn.close()
2457
+ return {"templates": [dict(id=r[0], name=r[1], content=r[2]) for r in rows]}
2458
+
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()
2470
+ conn.execute("DELETE FROM templates WHERE id = ? AND user_id = ?", (template_id, user_id))
2471
+ if hasattr(conn, "commit"): conn.commit()
2472
+ if hasattr(conn, "close"): conn.close()
2473
+ return {"status": "success"}
2474
+
2475
+ # --- PERMANENT EXCLUDES ---
2476
+ @app.get("/api/users/permanent-excludes")
2477
+ async def get_permanent_excludes(user_id: str = Depends(get_current_user_id)):
2478
+ conn = get_db_connection()
2479
+ row = conn.execute("SELECT permanent_excludes FROM users WHERE id = ?", (user_id,)).fetchone()
2480
+ if hasattr(conn, "close"): conn.close()
2481
+ if row:
2482
+ return {"ids": json.loads(row[0] or "[]")}
2483
+ return {"ids": []}
2484
+
2485
+ @app.post("/api/users/permanent-excludes")
2486
+ async def update_permanent_excludes(req: PermanentExcludeRequest, user_id: str = Depends(get_current_user_id)):
2487
+ conn = get_db_connection()
2488
+ conn.execute("UPDATE users SET permanent_excludes = ? WHERE id = ?", (json.dumps(req.ids), user_id))
2489
+ if hasattr(conn, "commit"): conn.commit()
2490
+ if hasattr(conn, "close"): conn.close()
2491
+ return {"status": "success"}
2492
+
2493
  # Removed redundant get_accounts (already refactored earlier)
2494
 
2495
  @app.post("/api/telegram/campaigns/{task_id}/toggle-pause")
 
3027
  except:
3028
  exclude_list = []
3029
 
3030
+ # Fetch and merge permanent excludes for this user
3031
+ try:
3032
+ ex_conn = get_db_connection()
3033
+ u_ex_row = ex_conn.execute("SELECT permanent_excludes FROM users WHERE id = ?", (u_id,)).fetchone()
3034
+ if u_ex_row and u_ex_row[0]:
3035
+ try:
3036
+ p_ex = json.loads(u_ex_row[0])
3037
+ if isinstance(p_ex, list):
3038
+ exclude_list.extend(p_ex)
3039
+ except: pass
3040
+ if hasattr(ex_conn, "close"): ex_conn.close()
3041
+ except Exception as e:
3042
+ print(f"BKG_TASK[{task_id}]: Error loading permanent excludes: {e}")
3043
+
3044
  # Normalize exclude_list
3045
+ exclude_list = list(set([str(e).strip() for e in (exclude_list if isinstance(exclude_list, list) else [])]))
3046
 
3047
  def recursive_spin(text: str) -> str:
3048
  text_obj = str(text)
frontend/src/app/campaigns/page.tsx CHANGED
@@ -38,6 +38,8 @@ export default function CampaignsPage() {
38
  const pageSize = 15;
39
 
40
  const [userStatus, setUserStatus] = useState<any>(null);
 
 
41
 
42
  const fetchStatus = async () => {
43
  try {
@@ -51,6 +53,8 @@ export default function CampaignsPage() {
51
 
52
  useEffect(() => {
53
  fetchStatus();
 
 
54
  }, []);
55
 
56
  useEffect(() => {
@@ -104,6 +108,36 @@ export default function CampaignsPage() {
104
  }
105
  };
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  const fetchAccounts = async () => {
108
  try {
109
  const res = await apiFetch('/api/telegram/accounts');
@@ -153,13 +187,32 @@ export default function CampaignsPage() {
153
  }, []);
154
 
155
  const toggleGroup = (id: string) => {
156
- setSelectedGroups(prev => {
157
- if (prev.includes(id)) {
158
- return prev.filter(g => g !== id);
159
- } else {
160
- return [...prev, id];
161
- }
162
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  };
164
 
165
  const handleSubmit = async (e: React.FormEvent) => {
@@ -310,7 +363,7 @@ export default function CampaignsPage() {
310
 
311
  return (
312
  <div className="animate-in fade-in slide-in-from-bottom-4 duration-700">
313
- <header className="flex justify-between items-center mb-10">
314
  <div>
315
  <h2 className="text-2xl font-bold mb-1 tracking-tight text-foreground">Campaigns</h2>
316
  <p className="text-sm text-foreground/40 font-medium">Underground scheduling for autonomous broadcasts.</p>
@@ -373,8 +426,8 @@ export default function CampaignsPage() {
373
  </div>
374
  </div>
375
 
376
- <div className="flex flex-col md:flex-row md:items-center gap-4 md:gap-8 mt-4 md:mt-0">
377
- <div className="flex-1 w-full md:w-48">
378
  <div className="flex justify-between items-center mb-1.5">
379
  <div className="flex items-center gap-2">
380
  <p className="text-[9px] uppercase tracking-widest text-foreground/40 font-bold">Delivery Progress</p>
@@ -404,7 +457,7 @@ export default function CampaignsPage() {
404
  </div>
405
 
406
  <div className="flex items-center justify-between md:justify-end gap-4 w-full md:w-auto">
407
- <div className={`px-3 py-1.5 rounded-lg text-[9px] font-bold uppercase tracking-widest border ${getStatusColor(camp.status)}`}>
408
  {camp.status}
409
  </div>
410
 
@@ -463,10 +516,10 @@ export default function CampaignsPage() {
463
  <div className="bg-card border border-border rounded-[32px] w-full max-w-4xl shadow-2xl relative animate-in zoom-in-95 duration-300 max-h-[90vh] flex flex-col overflow-hidden">
464
  <div className="absolute top-0 left-1/2 -translate-x-1/2 w-1/2 h-[2px] bg-gradient-to-r from-transparent via-indigo-500 to-transparent"></div>
465
 
466
- <div className="flex justify-between items-center p-6 border-b border-border shrink-0">
467
- <div className="flex items-center gap-4">
468
- <div className="p-3 bg-indigo-500/10 rounded-2xl text-indigo-500">
469
- <Megaphone size={24} />
470
  </div>
471
  <div>
472
  <h3 className="font-bold text-xl text-foreground tracking-tight">{editingId ? 'Modify Transmission' : 'Create Underground Campaign'}</h3>
@@ -476,7 +529,7 @@ export default function CampaignsPage() {
476
  <button onClick={() => { setIsCreating(false); setEditingId(null); }} className="text-foreground/20 hover:text-foreground p-2 hover:bg-foreground/5 rounded-full"><X size={24} /></button>
477
  </div>
478
 
479
- <div className="p-6 overflow-y-auto custom-scrollbar flex-1">
480
  {success ? (
481
  <div className="text-center py-20">
482
  <div className="w-20 h-20 bg-emerald-500/10 text-emerald-500 rounded-full flex items-center justify-center mx-auto mb-6"><CheckCircle2 size={40} /></div>
@@ -484,8 +537,8 @@ export default function CampaignsPage() {
484
  <p className="text-sm text-foreground/40">Your campaign has been successfully queued.</p>
485
  </div>
486
  ) : (
487
- <form onSubmit={handleSubmit} className="space-y-6">
488
- <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
489
  <div className="space-y-5">
490
  <div className="space-y-2">
491
  <label className="text-xs font-bold text-foreground/30 uppercase tracking-widest">Sending Account</label>
@@ -497,7 +550,7 @@ export default function CampaignsPage() {
497
  setCampaignData({ ...campaignData, phone_number: val });
498
  fetchDialogs(val);
499
  }}
500
- className="w-full bg-input border border-border rounded-xl py-3.5 px-4 text-sm text-foreground focus:ring-2 focus:ring-indigo-500/50 outline-none"
501
  >
502
  <option value="">Select an account...</option>
503
  {accounts.map((acc, idx) => (<option key={idx} value={acc.phone_number}>{acc.phone_number}</option>))}
@@ -516,7 +569,7 @@ export default function CampaignsPage() {
516
  />
517
  </div>
518
  <div className="space-y-2">
519
- <label className="text-xs font-bold text-foreground/30 uppercase tracking-widest">Repeat (Hrs/Min)</label>
520
  <div className="flex gap-2">
521
  <select
522
  value={campaignData.interval_hours}
@@ -544,7 +597,7 @@ export default function CampaignsPage() {
544
  </div>
545
  </div>
546
 
547
- <div className="space-y-4">
548
  <div className="bg-indigo-500/5 border border-indigo-500/10 rounded-2xl p-3">
549
  <h4 className="text-[10px] font-bold text-indigo-500 uppercase tracking-widest mb-3 flex items-center gap-2">
550
  <MessageCircle size={14} /> Optimization Guide (ChatGPT Prompt)
@@ -572,7 +625,22 @@ export default function CampaignsPage() {
572
  </div>
573
  <div className="space-y-2">
574
  <div className="flex justify-between items-center px-1">
575
- <label className="text-xs font-bold text-foreground/30 uppercase tracking-widest">Message Payload</label>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
576
  {!isSpintaxValid(campaignData.message) && campaignData.message.length > 0 && (
577
  <span className="text-[9px] font-bold text-amber-500 uppercase">Non-Spintax detected</span>
578
  )}
@@ -591,7 +659,7 @@ export default function CampaignsPage() {
591
  <div className="space-y-4 flex flex-col h-full">
592
  <div className="flex justify-between items-end">
593
  <div className="flex items-center gap-4">
594
- <label className="text-xs font-bold text-foreground/30 uppercase tracking-widest">Target Groups</label>
595
  <div className="flex bg-foreground/5 p-1 rounded-lg">
596
  <button
597
  type="button"
@@ -616,7 +684,7 @@ export default function CampaignsPage() {
616
  </div>
617
 
618
  {/* Filters & Toggles */}
619
- <div className="flex items-center justify-between gap-4">
620
  <div className="flex bg-foreground/5 p-1 rounded-xl w-fit">
621
  {(['all', 'groups', 'channels'] as const).map(t => (
622
  <button
@@ -635,21 +703,25 @@ export default function CampaignsPage() {
635
  onClick={() => {
636
  const visibleIds = filteredDialogs.map((d: any) => d.id);
637
  if (selectionMode === 'include') {
638
- const allSelected = visibleIds.length > 0 && visibleIds.every((id: any) => selectedGroups.includes(id));
 
639
  if (allSelected) {
640
  setSelectedGroups(prev => prev.filter(id => !visibleIds.includes(id)));
641
  } else {
642
- setSelectedGroups(prev => Array.from(new Set([...prev, ...visibleIds])));
643
- setExcludedGroups(prev => prev.filter(id => !visibleIds.includes(id)));
644
  }
645
  } else {
646
  const allExcluded = visibleIds.length > 0 && visibleIds.every((id: any) => excludedGroups.includes(id));
 
647
  if (allExcluded) {
648
- setExcludedGroups(prev => prev.filter(id => !visibleIds.includes(id)));
649
  } else {
650
- setExcludedGroups(prev => Array.from(new Set([...prev, ...visibleIds])));
651
  setSelectedGroups(prev => prev.filter(id => !visibleIds.includes(id)));
652
  }
 
 
 
653
  }
654
  }}
655
  className={`text-[10px] font-bold uppercase tracking-widest px-4 py-2 hover:bg-foreground/10 transition-all rounded-xl border flex items-center gap-2
 
38
  const pageSize = 15;
39
 
40
  const [userStatus, setUserStatus] = useState<any>(null);
41
+ const [templates, setTemplates] = useState<any[]>([]);
42
+ const [permanentExcludes, setPermanentExcludes] = useState<string[]>([]);
43
 
44
  const fetchStatus = async () => {
45
  try {
 
53
 
54
  useEffect(() => {
55
  fetchStatus();
56
+ fetchTemplates();
57
+ fetchPermanentExcludes();
58
  }, []);
59
 
60
  useEffect(() => {
 
108
  }
109
  };
110
 
111
+ const fetchTemplates = async () => {
112
+ try {
113
+ const res = await apiFetch('/api/telegram/templates');
114
+ if (res.ok) {
115
+ const data = await res.json();
116
+ setTemplates(data.templates || []);
117
+ }
118
+ } catch (e) { }
119
+ };
120
+
121
+ const fetchPermanentExcludes = async () => {
122
+ try {
123
+ const res = await apiFetch('/api/users/permanent-excludes');
124
+ if (res.ok) {
125
+ const data = await res.json();
126
+ setPermanentExcludes(data.ids || []);
127
+ setExcludedGroups(data.ids || []);
128
+ }
129
+ } catch (e) { }
130
+ };
131
+
132
+ const updatePermanentExcludes = async (ids: string[]) => {
133
+ try {
134
+ await apiFetch('/api/users/permanent-excludes', {
135
+ method: 'POST',
136
+ body: JSON.stringify({ ids })
137
+ });
138
+ } catch (e) { }
139
+ };
140
+
141
  const fetchAccounts = async () => {
142
  try {
143
  const res = await apiFetch('/api/telegram/accounts');
 
187
  }, []);
188
 
189
  const toggleGroup = (id: string) => {
190
+ if (selectionMode === 'include') {
191
+ setSelectedGroups(prev => {
192
+ if (prev.includes(id)) {
193
+ return prev.filter(g => g !== id);
194
+ } else {
195
+ // Remove from exclude if we include it
196
+ setExcludedGroups(ex => ex.filter(g => g !== id));
197
+ return [...prev, id];
198
+ }
199
+ });
200
+ } else {
201
+ setExcludedGroups(prev => {
202
+ let next;
203
+ if (prev.includes(id)) {
204
+ next = prev.filter(g => g !== id);
205
+ } else {
206
+ // Remove from selected if we exclude it
207
+ setSelectedGroups(sel => sel.filter(g => g !== id));
208
+ next = [...prev, id];
209
+ }
210
+ // Save to permanent excludes immediately
211
+ updatePermanentExcludes(next);
212
+ setPermanentExcludes(next);
213
+ return next;
214
+ });
215
+ }
216
  };
217
 
218
  const handleSubmit = async (e: React.FormEvent) => {
 
363
 
364
  return (
365
  <div className="animate-in fade-in slide-in-from-bottom-4 duration-700">
366
+ <header className="flex justify-between items-center mb-6">
367
  <div>
368
  <h2 className="text-2xl font-bold mb-1 tracking-tight text-foreground">Campaigns</h2>
369
  <p className="text-sm text-foreground/40 font-medium">Underground scheduling for autonomous broadcasts.</p>
 
426
  </div>
427
  </div>
428
 
429
+ <div className="flex flex-1 items-center gap-6 mt-4 md:mt-0 px-2 lg:px-4 border-l border-border/50 ml-6">
430
+ <div className="flex-1 min-w-[140px] max-w-[200px]">
431
  <div className="flex justify-between items-center mb-1.5">
432
  <div className="flex items-center gap-2">
433
  <p className="text-[9px] uppercase tracking-widest text-foreground/40 font-bold">Delivery Progress</p>
 
457
  </div>
458
 
459
  <div className="flex items-center justify-between md:justify-end gap-4 w-full md:w-auto">
460
+ <div className={`px-2 py-1 rounded-lg text-[8px] font-black uppercase tracking-[0.15em] border ${getStatusColor(camp.status)}`}>
461
  {camp.status}
462
  </div>
463
 
 
516
  <div className="bg-card border border-border rounded-[32px] w-full max-w-4xl shadow-2xl relative animate-in zoom-in-95 duration-300 max-h-[90vh] flex flex-col overflow-hidden">
517
  <div className="absolute top-0 left-1/2 -translate-x-1/2 w-1/2 h-[2px] bg-gradient-to-r from-transparent via-indigo-500 to-transparent"></div>
518
 
519
+ <div className="flex justify-between items-center p-4 border-b border-border shrink-0">
520
+ <div className="flex items-center gap-3">
521
+ <div className="p-2.5 bg-indigo-500/10 rounded-xl text-indigo-500">
522
+ <Megaphone size={20} />
523
  </div>
524
  <div>
525
  <h3 className="font-bold text-xl text-foreground tracking-tight">{editingId ? 'Modify Transmission' : 'Create Underground Campaign'}</h3>
 
529
  <button onClick={() => { setIsCreating(false); setEditingId(null); }} className="text-foreground/20 hover:text-foreground p-2 hover:bg-foreground/5 rounded-full"><X size={24} /></button>
530
  </div>
531
 
532
+ <div className="p-5 overflow-y-auto custom-scrollbar flex-1">
533
  {success ? (
534
  <div className="text-center py-20">
535
  <div className="w-20 h-20 bg-emerald-500/10 text-emerald-500 rounded-full flex items-center justify-center mx-auto mb-6"><CheckCircle2 size={40} /></div>
 
537
  <p className="text-sm text-foreground/40">Your campaign has been successfully queued.</p>
538
  </div>
539
  ) : (
540
+ <form onSubmit={handleSubmit} className="space-y-4">
541
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
542
  <div className="space-y-5">
543
  <div className="space-y-2">
544
  <label className="text-xs font-bold text-foreground/30 uppercase tracking-widest">Sending Account</label>
 
550
  setCampaignData({ ...campaignData, phone_number: val });
551
  fetchDialogs(val);
552
  }}
553
+ className="w-full bg-input border border-border rounded-xl py-3 px-4 text-sm text-foreground focus:ring-2 focus:ring-indigo-500/50 outline-none"
554
  >
555
  <option value="">Select an account...</option>
556
  {accounts.map((acc, idx) => (<option key={idx} value={acc.phone_number}>{acc.phone_number}</option>))}
 
569
  />
570
  </div>
571
  <div className="space-y-2">
572
+ <label className="text-[10px] font-bold text-foreground/30 uppercase tracking-widest">Repeat (Hrs/Min)</label>
573
  <div className="flex gap-2">
574
  <select
575
  value={campaignData.interval_hours}
 
597
  </div>
598
  </div>
599
 
600
+ <div className="space-y-3">
601
  <div className="bg-indigo-500/5 border border-indigo-500/10 rounded-2xl p-3">
602
  <h4 className="text-[10px] font-bold text-indigo-500 uppercase tracking-widest mb-3 flex items-center gap-2">
603
  <MessageCircle size={14} /> Optimization Guide (ChatGPT Prompt)
 
625
  </div>
626
  <div className="space-y-2">
627
  <div className="flex justify-between items-center px-1">
628
+ <label className="text-[10px] font-bold text-foreground/30 uppercase tracking-widest">Message Payload</label>
629
+ {templates.length > 0 && (
630
+ <select
631
+ className="text-[10px] bg-background border border-border rounded-md px-2 py-1 font-bold text-indigo-500 outline-none focus:ring-1 focus:ring-indigo-500/20"
632
+ onChange={(e) => {
633
+ const t = templates.find(x => x.id.toString() === e.target.value);
634
+ if (t) setCampaignData({ ...campaignData, message: t.content });
635
+ e.target.value = ""; // Reset
636
+ }}
637
+ >
638
+ <option value="">Load Template...</option>
639
+ {templates.map(t => (
640
+ <option key={t.id} value={t.id}>{t.name}</option>
641
+ ))}
642
+ </select>
643
+ )}
644
  {!isSpintaxValid(campaignData.message) && campaignData.message.length > 0 && (
645
  <span className="text-[9px] font-bold text-amber-500 uppercase">Non-Spintax detected</span>
646
  )}
 
659
  <div className="space-y-4 flex flex-col h-full">
660
  <div className="flex justify-between items-end">
661
  <div className="flex items-center gap-4">
662
+ <label className="text-[10px] font-bold text-foreground/30 uppercase tracking-widest">Target Groups</label>
663
  <div className="flex bg-foreground/5 p-1 rounded-lg">
664
  <button
665
  type="button"
 
684
  </div>
685
 
686
  {/* Filters & Toggles */}
687
+ <div className="flex items-center justify-between gap-3">
688
  <div className="flex bg-foreground/5 p-1 rounded-xl w-fit">
689
  {(['all', 'groups', 'channels'] as const).map(t => (
690
  <button
 
703
  onClick={() => {
704
  const visibleIds = filteredDialogs.map((d: any) => d.id);
705
  if (selectionMode === 'include') {
706
+ const selectableIds = visibleIds.filter((id: any) => !excludedGroups.includes(id));
707
+ const allSelected = selectableIds.length > 0 && selectableIds.every((id: any) => selectedGroups.includes(id));
708
  if (allSelected) {
709
  setSelectedGroups(prev => prev.filter(id => !visibleIds.includes(id)));
710
  } else {
711
+ setSelectedGroups(prev => Array.from(new Set([...prev, ...selectableIds])));
 
712
  }
713
  } else {
714
  const allExcluded = visibleIds.length > 0 && visibleIds.every((id: any) => excludedGroups.includes(id));
715
+ let nextExcludes;
716
  if (allExcluded) {
717
+ nextExcludes = excludedGroups.filter(id => !visibleIds.includes(id));
718
  } else {
719
+ nextExcludes = Array.from(new Set([...excludedGroups, ...visibleIds]));
720
  setSelectedGroups(prev => prev.filter(id => !visibleIds.includes(id)));
721
  }
722
+ setExcludedGroups(nextExcludes);
723
+ setPermanentExcludes(nextExcludes);
724
+ updatePermanentExcludes(nextExcludes);
725
  }
726
  }}
727
  className={`text-[10px] font-bold uppercase tracking-widest px-4 py-2 hover:bg-foreground/10 transition-all rounded-xl border flex items-center gap-2
frontend/src/app/templates/page.tsx ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import React, { useState, useEffect } from 'react';
4
+ import { Plus, FileText, Trash2, Edit3, Loader2, CheckCircle2, AlertCircle, Search } from 'lucide-react';
5
+ import { apiFetch } from '@/lib/auth';
6
+
7
+ interface Template {
8
+ id: number;
9
+ name: string;
10
+ content: string;
11
+ }
12
+
13
+ export default function TemplatesPage() {
14
+ const [templates, setTemplates] = useState<Template[]>([]);
15
+ const [loading, setLoading] = useState(true);
16
+ const [isCreating, setIsCreating] = useState(false);
17
+ const [editingId, setEditingId] = useState<number | null>(null);
18
+ const [error, setError] = useState("");
19
+ const [success, setSuccess] = useState(false);
20
+ const [searchTerm, setSearchTerm] = useState("");
21
+
22
+ const [formData, setFormData] = useState({
23
+ name: '',
24
+ content: ''
25
+ });
26
+
27
+ const fetchTemplates = async () => {
28
+ setLoading(true);
29
+ try {
30
+ const res = await apiFetch('/api/telegram/templates');
31
+ if (res.ok) {
32
+ const data = await res.json();
33
+ setTemplates(data.templates || []);
34
+ }
35
+ } catch (err) {
36
+ console.error("Failed to fetch templates", err);
37
+ } finally {
38
+ setLoading(false);
39
+ }
40
+ };
41
+
42
+ useEffect(() => {
43
+ fetchTemplates();
44
+ }, []);
45
+
46
+ const handleSubmit = async (e: React.FormEvent) => {
47
+ e.preventDefault();
48
+ setError("");
49
+ setLoading(true);
50
+
51
+ try {
52
+ const res = await apiFetch('/api/telegram/templates', {
53
+ method: 'POST',
54
+ body: JSON.stringify(formData)
55
+ });
56
+
57
+ if (res.ok) {
58
+ setSuccess(true);
59
+ setFormData({ name: '', content: '' });
60
+ fetchTemplates();
61
+ setTimeout(() => {
62
+ setIsCreating(false);
63
+ setSuccess(false);
64
+ }, 1500);
65
+ } else {
66
+ const data = await res.json();
67
+ setError(data.detail || "Failed to save template");
68
+ }
69
+ } catch (err) {
70
+ setError("Network error occurred");
71
+ } finally {
72
+ setLoading(false);
73
+ }
74
+ };
75
+
76
+ const handleDelete = async (id: number) => {
77
+ if (!confirm("Are you sure you want to delete this template?")) return;
78
+
79
+ try {
80
+ const res = await apiFetch(`/api/telegram/templates/${id}`, {
81
+ method: 'DELETE'
82
+ });
83
+ if (res.ok) {
84
+ fetchTemplates();
85
+ }
86
+ } catch (err) {
87
+ console.error("Delete failed", err);
88
+ }
89
+ };
90
+
91
+ const filteredTemplates = templates.filter(t =>
92
+ t.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
93
+ t.content.toLowerCase().includes(searchTerm.toLowerCase())
94
+ );
95
+
96
+ return (
97
+ <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-700">
98
+ {/* Header Section */}
99
+ <div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
100
+ <div>
101
+ <h1 className="text-4xl font-black text-foreground tracking-tight mb-2">
102
+ Message <span className="text-indigo-500">Templates</span>
103
+ </h1>
104
+ <p className="text-foreground/40 font-medium">Manage and organize your mission-critical message snippets.</p>
105
+ </div>
106
+ <button
107
+ onClick={() => { setIsCreating(true); setEditingId(null); setFormData({ name: '', content: '' }); }}
108
+ className="flex items-center gap-3 bg-indigo-500 hover:bg-indigo-600 text-white px-8 py-4 rounded-2xl font-bold shadow-xl shadow-indigo-500/20 transition-all hover:scale-[1.02] active:scale-95 shrink-0"
109
+ >
110
+ <Plus size={20} />
111
+ Create New Snippet
112
+ </button>
113
+ </div>
114
+
115
+ {/* Main Content */}
116
+ <div className="grid grid-cols-1 gap-6">
117
+ <div className="relative group">
118
+ <div className="absolute left-5 top-1/2 -translate-y-1/2 text-foreground/20 group-focus-within:text-indigo-500 transition-colors">
119
+ <Search size={20} />
120
+ </div>
121
+ <input
122
+ type="text"
123
+ placeholder="Search your knowledge base..."
124
+ className="w-full bg-card border border-border rounded-2xl py-5 pl-14 pr-6 text-foreground placeholder:text-foreground/20 focus:ring-2 focus:ring-indigo-500/20 outline-none transition-all shadow-sm"
125
+ value={searchTerm}
126
+ onChange={(e) => setSearchTerm(e.target.value)}
127
+ />
128
+ </div>
129
+
130
+ {loading && templates.length === 0 ? (
131
+ <div className="flex flex-col items-center justify-center py-20 bg-card rounded-[32px] border border-border border-dashed">
132
+ <Loader2 className="animate-spin text-indigo-500 mb-4" size={32} />
133
+ <p className="text-foreground/30 font-bold uppercase tracking-widest text-xs">Accessing Archives...</p>
134
+ </div>
135
+ ) : filteredTemplates.length === 0 ? (
136
+ <div className="flex flex-col items-center justify-center py-20 bg-card rounded-[32px] border border-border">
137
+ <div className="p-6 bg-foreground/5 rounded-full mb-6">
138
+ <FileText size={48} className="text-foreground/10" />
139
+ </div>
140
+ <h3 className="text-xl font-bold text-foreground mb-2">No Templates Found</h3>
141
+ <p className="text-foreground/40 max-w-md text-center text-sm px-6">Your message library is empty. Start by creating a high-converting template for your next campaign.</p>
142
+ </div>
143
+ ) : (
144
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
145
+ {filteredTemplates.map((template) => (
146
+ <div
147
+ key={template.id}
148
+ className="bg-card border border-border rounded-[32px] p-8 hover:border-indigo-500/30 transition-all group relative overflow-hidden flex flex-col h-full shadow-sm hover:shadow-xl hover:shadow-indigo-500/5 transition-all duration-500"
149
+ >
150
+ <div className="absolute top-0 right-0 p-4 opacity-0 group-hover:opacity-100 transition-opacity">
151
+ <button
152
+ onClick={() => handleDelete(template.id)}
153
+ className="p-2.5 bg-red-500/10 text-red-500 rounded-xl hover:bg-red-500 hover:text-white transition-all shadow-lg shadow-red-500/10"
154
+ >
155
+ <Trash2 size={16} />
156
+ </button>
157
+ </div>
158
+ <div className="p-3 w-fit bg-indigo-500/10 rounded-2xl text-indigo-500 mb-6 group-hover:bg-indigo-500 group-hover:text-white transition-all duration-500">
159
+ <FileText size={24} />
160
+ </div>
161
+ <h4 className="text-xl font-bold text-foreground mb-4 line-clamp-1">{template.name}</h4>
162
+ <div className="flex-1 bg-foreground/[0.02] border border-border rounded-2xl p-5 mb-6">
163
+ <p className="text-xs text-foreground/50 leading-loose line-clamp-6 font-medium italic">
164
+ "{template.content}"
165
+ </p>
166
+ </div>
167
+ <div className="flex items-center justify-between pt-2">
168
+ <span className="text-[10px] font-bold text-foreground/20 uppercase tracking-widest">Storage: Local Disk</span>
169
+ <button
170
+ onClick={() => {
171
+ setFormData({ name: template.name, content: template.content });
172
+ setEditingId(template.id);
173
+ setIsCreating(true);
174
+ }}
175
+ className="text-[10px] font-black text-indigo-500 uppercase tracking-widest hover:text-indigo-400 flex items-center gap-2"
176
+ >
177
+ Edit Snippet <Edit3 size={12} />
178
+ </button>
179
+ </div>
180
+ </div>
181
+ ))}
182
+ </div>
183
+ )}
184
+ </div>
185
+
186
+ {/* Creator Modal */}
187
+ {isCreating && (
188
+ <div className="fixed inset-0 bg-black/80 backdrop-blur-md z-[100] flex items-center justify-center p-6">
189
+ <div className="bg-card border border-border rounded-[32px] w-full max-w-2xl shadow-2xl relative animate-in zoom-in-95 duration-300 overflow-hidden">
190
+ <div className="absolute top-0 left-1/2 -translate-x-1/2 w-1/2 h-[2px] bg-gradient-to-r from-transparent via-indigo-500 to-transparent"></div>
191
+
192
+ <div className="p-10">
193
+ {success ? (
194
+ <div className="text-center py-10">
195
+ <div className="w-20 h-20 bg-emerald-500/10 text-emerald-500 rounded-full flex items-center justify-center mx-auto mb-6">
196
+ <CheckCircle2 size={40} />
197
+ </div>
198
+ <h4 className="text-2xl font-bold text-foreground mb-3">Snippet Secured</h4>
199
+ <p className="text-sm text-foreground/40 font-medium">Your template has been encrypted and saved.</p>
200
+ </div>
201
+ ) : (
202
+ <form onSubmit={handleSubmit} className="space-y-8">
203
+ <div className="flex items-center gap-4 mb-2">
204
+ <div className="p-3 bg-indigo-500/10 rounded-2xl text-indigo-500">
205
+ <FileText size={24} />
206
+ </div>
207
+ <div>
208
+ <h3 className="font-bold text-2xl text-foreground tracking-tight">Template Engine</h3>
209
+ <p className="text-xs text-foreground/30 font-bold uppercase tracking-widest mt-0.5">Define your transmission core.</p>
210
+ </div>
211
+ </div>
212
+
213
+ <div className="space-y-6">
214
+ <div className="space-y-2">
215
+ <label className="text-xs font-bold text-foreground/30 uppercase tracking-widest ml-1">Template Alias</label>
216
+ <input
217
+ required
218
+ type="text"
219
+ placeholder="e.g., IPTV Outreach - High Intent"
220
+ className="w-full bg-input border border-border rounded-2xl py-4 px-6 text-sm text-foreground placeholder:text-foreground/20 focus:ring-2 focus:ring-indigo-500/20 outline-none transition-all"
221
+ value={formData.name}
222
+ onChange={(e) => setFormData({...formData, name: e.target.value})}
223
+ />
224
+ </div>
225
+
226
+ <div className="space-y-2">
227
+ <label className="text-xs font-bold text-foreground/30 uppercase tracking-widest ml-1">Message Content (Spintax Recommended)</label>
228
+ <textarea
229
+ required
230
+ rows={8}
231
+ placeholder="'{Hello|Hi|Hey} {{First Name}}, I noticed...'"
232
+ className="w-full bg-input border border-border rounded-2xl py-4 px-6 text-sm text-foreground placeholder:text-foreground/20 focus:ring-2 focus:ring-indigo-500/20 outline-none transition-all resize-none font-medium leading-relaxed"
233
+ value={formData.content}
234
+ onChange={(e) => setFormData({...formData, content: e.target.value})}
235
+ />
236
+ </div>
237
+ </div>
238
+
239
+ {error && (
240
+ <div className="flex items-center gap-3 p-4 bg-red-500/10 border border-red-500/20 rounded-2xl text-red-500 text-xs font-bold animate-in fade-in slide-in-from-top-2">
241
+ <AlertCircle size={14} />
242
+ {error}
243
+ </div>
244
+ )}
245
+
246
+ <div className="flex justify-end gap-4 pt-4 border-t border-border">
247
+ <button
248
+ type="button"
249
+ onClick={() => setIsCreating(false)}
250
+ className="px-8 py-4 rounded-2xl text-sm font-bold text-foreground/40 hover:text-foreground transition-all"
251
+ >
252
+ Discard Changes
253
+ </button>
254
+ <button
255
+ type="submit"
256
+ disabled={loading}
257
+ className="bg-indigo-500 hover:bg-indigo-600 text-white px-10 py-4 rounded-2xl text-sm font-bold shadow-xl shadow-indigo-500/20 disabled:opacity-50 transition-all active:scale-95"
258
+ >
259
+ {loading ? <Loader2 size={18} className="animate-spin shrink-0" /> : 'Apply & Save'}
260
+ </button>
261
+ </div>
262
+ </form>
263
+ )}
264
+ </div>
265
+ </div>
266
+ </div>
267
+ )}
268
+ </div>
269
+ );
270
+ }
frontend/src/components/Sidebar.tsx CHANGED
@@ -16,7 +16,8 @@ import {
16
  ChevronLeft,
17
  LogOut,
18
  Shield,
19
- Bookmark
 
20
  } from "lucide-react";
21
  import { getToken, removeToken, apiFetch } from "@/lib/auth";
22
  import { BroadcastBanner } from "./BroadcastBanner";
@@ -117,6 +118,7 @@ export function Sidebar({ children }: { children: React.ReactNode }) {
117
  { name: "Campaigns", href: "/campaigns", icon: Megaphone },
118
  { name: "Scraper", href: "/scraper", icon: Search },
119
  { name: "Leads", href: "/leads", icon: Bookmark },
 
120
  ];
121
 
122
  if (user?.role === 'admin') {
 
16
  ChevronLeft,
17
  LogOut,
18
  Shield,
19
+ Bookmark,
20
+ FileText
21
  } from "lucide-react";
22
  import { getToken, removeToken, apiFetch } from "@/lib/auth";
23
  import { BroadcastBanner } from "./BroadcastBanner";
 
118
  { name: "Campaigns", href: "/campaigns", icon: Megaphone },
119
  { name: "Scraper", href: "/scraper", icon: Search },
120
  { name: "Leads", href: "/leads", icon: Bookmark },
121
+ { name: "Templates", href: "/templates", icon: FileText },
122
  ];
123
 
124
  if (user?.role === 'admin') {