-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.py
More file actions
3135 lines (2532 loc) · 136 KB
/
cli.py
File metadata and controls
3135 lines (2532 loc) · 136 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Command-line interface for the Job Prospect Automation system.
"""
import sys
import os
import json
from pathlib import Path
from typing import (
Optional,
Dict,
Any,
List
)
from datetime import datetime
import click
import yaml
from rich.console import Console
from rich.table import Table
from rich.progress import (
Progress,
SpinnerColumn,
TextColumn
)
# Import Windows-compatible progress for cross-platform compatibility
from utils.windows_progress import replace_spinner_progress
from rich.panel import Panel
# Platform detection utility
import platform
def get_platform_safe_text(text: str, emoji: str = "", fallback: str = "") -> str:
"""Get platform-safe text with optional emoji for Windows compatibility.
Args:
text: The main text to display
emoji: Emoji to prepend (will be omitted on Windows)
fallback: Fallback text for Windows (without emoji)
Returns:
Platform-appropriate formatted text
"""
if platform.system().lower() == "windows":
# On Windows, avoid Unicode emojis that cause encoding issues
return fallback if fallback else text
else:
# On other platforms, include emojis
return f"{emoji} {text}" if emoji else text
def get_platform_safe_emoji_text(text: str, check_emoji: str = "✅", cross_emoji: str = "❌",
light_emoji: str = "💡", phone_emoji: str = "📱",
link_emoji: str = "🔗", target_emoji: str = "🎯",
fallback_text: str = "") -> str:
"""Get platform-safe text with multiple emojis for Windows compatibility.
Args:
text: The main text to display
check_emoji: Checkmark emoji
cross_emoji: Cross emoji
light_emoji: Light bulb emoji
phone_emoji: Phone emoji
link_emoji: Link emoji
target_emoji: Target emoji
fallback_text: Complete fallback text for Windows
Returns:
Platform-appropriate formatted text
"""
if platform.system().lower() == "windows":
# On Windows, avoid Unicode emojis that cause encoding issues
return fallback_text if fallback_text else text
else:
# Replace emoji placeholders with actual emojis
result = text.replace("{check}", check_emoji)
result = result.replace("{cross}", cross_emoji)
result = result.replace("{light}", light_emoji)
result = result.replace("{phone}", phone_emoji)
result = result.replace("{link}", link_emoji)
result = result.replace("{target}", target_emoji)
return result
# Import CLI profile commands
try:
from scripts.cli_profile_commands import profile
except ImportError:
profile = None
print("Warning: cli_profile_commands import failed")
# Import setup dashboard function
try:
from scripts.setup_dashboard import setup_dashboard as setup_func
except ImportError:
setup_func = None
# Import setup issues database function
try:
from scripts.setup_issues_database import setup_issues_database
except ImportError:
setup_issues_database = None
from controllers.prospect_automation_controller import ProspectAutomationController
from utils.config import Config
from utils.logging_config import setup_logging
from models.data_models import CompanyData, ValidationError, EmailTemplate
from services.sender_profile_manager import SenderProfileManager
from services.notification_manager import NotificationManager
from services.ai_provider_manager import get_provider_manager, AIProviderManager
from services.issue_reporter import IssueReporter
# Initialize console with Windows compatibility
if platform.system().lower() == "windows":
# Try to handle Windows encoding issues
try:
# Attempt to use UTF-8 encoding if available
console = Console(force_terminal=True, legacy_windows=False)
except Exception:
# Fallback to basic console without Unicode characters
console = Console(force_terminal=True, no_color=True)
else:
console = Console()
def suggest_issue_report(error_type: str = "error", error_message: str = "") -> None:
"""
Suggest issue reporting for certain types of errors.
Args:
error_type: Type of error (error, timeout, config, api)
error_message: The actual error message
"""
# Only suggest for certain error types that users might want to report
suggest_types = {
"config": "Configuration or setup issues",
"api": "API or service connectivity problems",
"timeout": "Timeout or performance issues",
"validation": "Data validation problems",
"unexpected": "Unexpected errors or crashes"
}
if error_type in suggest_types or "timeout" in error_message.lower() or "api" in error_message.lower():
console.print(f"[yellow]💡 Had an issue? Report it: python cli.py report-issue[/yellow]")
class CLIConfig:
"""Extended configuration class for CLI operations."""
def __init__(self, config_file: Optional[str] = None, dry_run: bool = False):
self.dry_run = dry_run
self.config_file = config_file
self.base_config = self._load_config()
def _load_config(self) -> Config:
"""Load configuration from file or environment."""
if self.config_file and os.path.exists(self.config_file):
return self._load_from_file()
return Config.from_env()
def _load_from_file(self) -> Config:
"""Load configuration from YAML or JSON file."""
with open(self.config_file, 'r') as f:
if self.config_file.endswith('.yaml') or self.config_file.endswith('.yml'):
data = yaml.safe_load(f)
else:
data = json.load(f)
# Set environment variables from config file
for key, value in data.items():
os.environ[key.upper()] = str(value)
return Config.from_env()
def setup_cli_logging(verbose: bool = False):
"""Setup logging for CLI operations."""
log_level = "DEBUG" if verbose else "INFO"
setup_logging(log_level=log_level)
@click.group()
@click.option('--config', '-c', help='Configuration file path (YAML or JSON)')
@click.option('--dry-run', is_flag=True, help='Run in dry-run mode (no actual API calls)')
@click.option('--verbose', '-v', is_flag=True, help='Enable verbose logging')
@click.pass_context
def cli(ctx, config, dry_run, verbose):
""">> Job Prospect Automation CLI - Complete automation workflow in one command!
QUICK COMMANDS:
• quick-start - Complete setup + first campaign (beginners)
• run-campaign - Full workflow: discovery -> emails -> analytics
• discover - Discovery only (advanced users)
SETUP COMMANDS:
• setup-dashboard - One-time Notion dashboard setup
• validate-config - Check your configuration
"""
ctx.ensure_object(dict)
ctx.obj['config_file'] = config
ctx.obj['dry_run'] = dry_run
ctx.obj['verbose'] = verbose
setup_cli_logging(verbose)
if dry_run:
console.print("[yellow]Running in DRY-RUN mode - no actual API calls will be made[/yellow]")
# Add the profile command group to the main CLI if available
if profile:
cli.add_command(profile)
@cli.command('setup-dashboard')
@click.pass_context
def setup_dashboard(ctx):
"""Set up the Notion progress dashboard."""
try:
cli_config = CLIConfig(ctx.obj['config_file'], ctx.obj['dry_run'])
if cli_config.dry_run:
console.print("[yellow]DRY-RUN: Would set up Notion progress dashboard[/yellow]")
return
console.print("[blue]Setting up Notion progress dashboard...[/blue]")
dashboard_info = setup_func()
if dashboard_info:
console.print("[green]✅ Dashboard setup completed successfully![/green]")
return 0
else:
console.print("[red]❌ Dashboard setup failed[/red]")
return 1
except Exception as e:
console.print(f"[red]Error setting up dashboard: {str(e)}[/red]")
suggest_issue_report("config", str(e))
return 1
@cli.command('campaign-status')
@click.pass_context
def campaign_status(ctx):
"""Show current campaign status and progress."""
try:
cli_config = CLIConfig(ctx.obj['config_file'], ctx.obj['dry_run'])
controller = ProspectAutomationController(cli_config.base_config)
progress = controller.get_campaign_progress()
if not progress:
console.print("[yellow]No active campaign found[/yellow]")
return
# Create progress table
table = Table(title="Campaign Progress")
table.add_column("Metric", style="cyan")
table.add_column("Value", style="green")
table.add_row("Campaign Name", progress['name'])
table.add_row("Status", progress['status'])
table.add_row("Progress", f"{progress['progress_percentage']:.1f}%")
table.add_row("Current Step", progress['current_step'])
table.add_row("Current Company", progress.get('current_company', 'N/A'))
table.add_row("Companies Processed", f"{progress['companies_processed']}/{progress['companies_target']}")
table.add_row("Prospects Found", str(progress['prospects_found']))
table.add_row("Emails Generated", str(progress['emails_generated']))
table.add_row("Success Rate", f"{progress['success_rate']:.1f}%")
table.add_row("Errors", str(progress['error_count']))
console.print(table)
except Exception as e:
console.print(f"[red]Error getting campaign status: {str(e)}[/red]")
return 1
@cli.command('daily-summary')
@click.pass_context
def daily_summary(ctx):
"""Create or update today's daily analytics summary."""
try:
cli_config = CLIConfig(ctx.obj['config_file'], ctx.obj['dry_run'])
if cli_config.dry_run:
console.print("[yellow]DRY-RUN: Would create daily summary[/yellow]")
return
controller = ProspectAutomationController(cli_config.base_config)
analytics_db_id = cli_config.base_config.analytics_db_id
if not analytics_db_id:
console.print("[red]Analytics database not configured. Run setup-dashboard first.[/red]")
return 1
success = controller.create_daily_summary(analytics_db_id)
if success:
console.print("[green]✅ Daily summary updated successfully![/green]")
else:
console.print("[red]❌ Failed to update daily summary[/red]")
return 1
except Exception as e:
console.print(f"[red]Error creating daily summary: {str(e)}[/red]")
return 1
@cli.command('email-queue')
@click.option('--action', type=click.Choice(['list', 'approve', 'reject']), default='list',
help='Action to perform on email queue')
@click.option('--email-id', help='Email ID for approve/reject actions')
@click.pass_context
def email_queue(ctx, action, email_id):
"""Manage the email approval queue."""
try:
cli_config = CLIConfig(ctx.obj['config_file'], ctx.obj['dry_run'])
if cli_config.dry_run:
console.print(f"[yellow]DRY-RUN: Would {action} email queue[/yellow]")
return
controller = ProspectAutomationController(cli_config.base_config)
email_queue_db_id = cli_config.base_config.email_queue_db_id
if not email_queue_db_id:
console.print("[red]Email queue database not configured. Run setup-dashboard first.[/red]")
return 1
if action == 'list':
# List pending emails
pending_emails = controller.check_email_approvals(email_queue_db_id)
if not pending_emails:
console.print("[yellow]No emails pending approval[/yellow]")
return
table = Table(title="Email Approval Queue")
table.add_column("Email ID", style="cyan")
table.add_column("Prospect", style="green")
table.add_column("Company", style="blue")
table.add_column("Subject", style="yellow")
for email in pending_emails:
table.add_row(
email['email_id'][:20] + "...",
email['prospect_name'],
email['company'],
email['subject'][:50] + "..." if len(email['subject']) > 50 else email['subject']
)
console.print(table)
elif action in ['approve', 'reject']:
if not email_id:
console.print("[red]Email ID required for approve/reject actions[/red]")
return 1
# Find email by ID and update status
# This would need to be implemented with proper email ID lookup
console.print(f"[yellow]Email {action} functionality coming soon![/yellow]")
except Exception as e:
console.print(f"[red]Error managing email queue: {str(e)}[/red]")
return 1
@cli.command('test-notifications')
@click.pass_context
def test_notifications(ctx):
"""Test all notification types to see how they appear in Notion."""
try:
cli_config = CLIConfig(ctx.obj['config_file'], ctx.obj['dry_run'])
if cli_config.dry_run:
console.print("[yellow]DRY-RUN: Would test all notification types[/yellow]")
return
controller = ProspectAutomationController(cli_config.base_config)
notification_manager = NotificationManager(cli_config.base_config, controller.notion_manager)
console.print("[blue]Testing all notification types...[/blue]")
# Test campaign completion (success)
success_data = {
'name': 'Test Success Campaign',
'companies_processed': 5,
'prospects_found': 12,
'success_rate': 0.95,
'duration_minutes': 15.5,
'status': 'Completed'
}
notification_manager.send_campaign_completion_notification(success_data)
console.print("[green]✅ Campaign completion notification sent[/green]")
# Test daily summary
daily_stats = controller._calculate_daily_stats()
notification_manager.send_daily_summary_notification(daily_stats)
console.print("[green]✅ Daily summary notification sent[/green]")
# Test error alert
error_data = {
'component': 'Test Component',
'error_message': 'This is a test error for demonstration',
'campaign_name': 'Test Campaign',
'company_name': 'Test Company'
}
notification_manager.send_error_alert(error_data)
console.print("[green]✅ Error alert notification sent[/green]")
console.print(f"\n[cyan]Check your Daily Analytics database for notification sub-pages![/cyan]")
console.print(f"[dim]Analytics DB: https://notion.so/{cli_config.base_config.analytics_db_id.replace('-', '') if cli_config.base_config.analytics_db_id else 'not-configured'}[/dim]")
console.print(f"\n[yellow]💡 To get push notifications:[/yellow]")
console.print(f"1. Go to the notification pages in Daily Analytics")
console.print(f"2. Replace '@mention-user-here' with your actual @mention")
console.print(f"3. This will trigger push notifications on mobile/desktop")
console.print(f"\n[dim]Run 'python setup_user_mentions.py' to configure automatic mentions[/dim]")
except Exception as e:
console.print(f"[red]Error testing notifications: {str(e)}[/red]")
return 1
@cli.command('send-notification')
@click.option('--type', 'notification_type', type=click.Choice(['daily', 'test']), default='test',
help='Type of notification to send')
@click.pass_context
def send_notification(ctx, notification_type):
"""Send a test notification or daily summary."""
try:
cli_config = CLIConfig(ctx.obj['config_file'], ctx.obj['dry_run'])
if cli_config.dry_run:
console.print(f"[yellow]DRY-RUN: Would send {notification_type} notification[/yellow]")
return
controller = ProspectAutomationController(cli_config.base_config)
notification_manager = NotificationManager(cli_config.base_config, controller.notion_manager)
if notification_type == 'daily':
daily_stats = controller._calculate_daily_stats()
success = notification_manager.send_daily_summary_notification(daily_stats)
else:
# Send test notification
test_data = {
'name': 'Test Campaign',
'companies_processed': 5,
'prospects_found': 12,
'success_rate': 0.85,
'duration_minutes': 15.5,
'status': 'Completed'
}
success = notification_manager.send_campaign_completion_notification(test_data)
if success:
console.print(f"[green]✅ {notification_type.title()} notification sent successfully![/green]")
else:
console.print(f"[red]❌ Failed to send {notification_type} notification[/red]")
return 1
except Exception as e:
console.print(f"[red]Error sending notification: {str(e)}[/red]")
return 1
@cli.command('analytics-report')
@click.option('--period', type=click.Choice(['daily', 'weekly', 'monthly']), default='daily',
help='Report period')
@click.pass_context
def analytics_report(ctx, period):
"""Generate advanced analytics report."""
try:
cli_config = CLIConfig(ctx.obj['config_file'], ctx.obj['dry_run'])
if cli_config.dry_run:
console.print(f"[yellow]DRY-RUN: Would generate {period} analytics report[/yellow]")
return
controller = ProspectAutomationController(cli_config.base_config)
if period == 'daily':
stats = controller._calculate_daily_stats()
table = Table(title=f"Daily Analytics Report - {datetime.now().strftime('%Y-%m-%d')}")
table.add_column("Metric", style="cyan")
table.add_column("Value", style="green")
table.add_row("Campaigns Run", str(stats.get('campaigns_run', 0)))
table.add_row("Companies Processed", str(stats.get('companies_processed', 0)))
table.add_row("Prospects Found", str(stats.get('prospects_found', 0)))
table.add_row("Emails Generated", str(stats.get('emails_generated', 0)))
table.add_row("Success Rate", f"{stats.get('success_rate', 0) * 100:.1f}%")
table.add_row("Processing Time", f"{stats.get('processing_time_minutes', 0):.1f} min")
table.add_row("API Calls", str(stats.get('api_calls', 0)))
table.add_row("Top Campaign", stats.get('top_campaign', 'N/A'))
console.print(table)
else:
console.print(f"[yellow]{period.title()} reports coming soon![/yellow]")
except Exception as e:
console.print(f"[red]Error generating analytics report: {str(e)}[/red]")
return 1
@cli.command('quick-start')
@click.option('--limit', '-l', default=5, help='Number of companies to process (start small)')
@click.pass_context
def quick_start(ctx, limit):
""">> QUICK START: Complete setup and first campaign in one command!"""
try:
cli_config = CLIConfig(ctx.obj['config_file'], ctx.obj['dry_run'])
if cli_config.dry_run:
console.print("[yellow]DRY-RUN: Would run complete quick-start workflow[/yellow]")
return
console.print(Panel.fit(
"[bold green]>> Job Prospect Automation - Quick Start[/bold green]\n"
"This will set up everything and run your first campaign!",
border_style="green"
))
# Step 1: Check configuration
console.print("\n[bold blue]Step 1: Configuration Check[/bold blue]")
try:
config = cli_config.base_config
config.validate()
console.print("[green]✅ Configuration valid[/green]")
except Exception as e:
console.print(f"[red]❌ Configuration error: {str(e)}[/red]")
console.print("[yellow]Please check your .env file or config.yaml[/yellow]")
return 1
# Step 2: Dashboard setup
console.print("\n[bold blue]Step 2: Dashboard Setup[/bold blue]")
if not config.dashboard_id:
console.print("[yellow]Setting up Notion dashboard...[/yellow]")
dashboard_info = setup_func()
if not dashboard_info:
console.print("[red]❌ Dashboard setup failed[/red]")
return 1
console.print("[green]✅ Dashboard created successfully![/green]")
else:
console.print("[green]✅ Dashboard already configured[/green]")
# Step 3: Run first campaign
console.print(f"\n[bold blue]Step 3: First Campaign (Processing {limit} companies)[/bold blue]")
controller = ProspectAutomationController(cli_config.base_config)
campaign_name = f"Quick Start Campaign {datetime.now().strftime('%Y-%m-%d %H:%M')}"
# Run discovery
results = controller.run_discovery_pipeline(limit=limit, campaign_name=campaign_name)
prospects_found = results['summary']['prospects_found']
console.print(f"[green]✅ Discovery completed: {prospects_found} prospects found[/green]")
# Generate emails if prospects found
if prospects_found > 0:
console.print("\n[bold blue]Step 4: Email Generation[/bold blue]")
prospects = controller.notion_manager.get_prospects()
recent_prospects = [p for p in prospects if p.id][-prospects_found:]
prospect_ids = [p.id for p in recent_prospects if p.email]
if prospect_ids:
email_results = controller.generate_outreach_emails(
prospect_ids=prospect_ids[:3], # Limit to 3 for quick start
template_type=EmailTemplate.COLD_OUTREACH
)
console.print(f"[green]✅ Generated {len(email_results.get('successful', []))} emails[/green]")
# Update analytics
if config.analytics_db_id:
controller.create_daily_summary(config.analytics_db_id)
console.print(Panel.fit(
"[bold green]*** Quick Start Completed! ***[/bold green]\n\n"
"✅ Dashboard created in Notion\n"
"✅ Companies discovered and processed\n"
"✅ Prospects extracted and stored\n"
"✅ Emails generated (ready for review)\n"
"✅ Analytics updated\n\n"
"Next steps:\n"
"* Check your Notion dashboard\n"
"* Review generated emails\n"
"* Run more campaigns with: python cli.py run-campaign",
border_style="green"
))
return 0
except Exception as e:
console.print(f"[red]❌ Quick start failed: {str(e)}[/red]")
suggest_issue_report("config", str(e))
return 1
@cli.command('generate-emails-recent')
@click.option('--limit', '-l', default=10, help='Number of recent prospects to generate emails for')
@click.option('--template', type=click.Choice(['cold_outreach', 'referral_followup', 'product_interest', 'networking']),
default='cold_outreach', help='Email template type')
@click.option('--send', is_flag=True, help='Send emails immediately after generation')
@click.pass_context
def generate_emails_recent(ctx, limit, template, send):
""">> Generate emails for the most recently discovered prospects."""
try:
cli_config = CLIConfig(ctx.obj['config_file'], ctx.obj['dry_run'])
if cli_config.dry_run:
console.print(f"[yellow]DRY-RUN: Would generate emails for {limit} recent prospects[/yellow]")
return
controller = ProspectAutomationController(cli_config.base_config)
console.print(f"[blue]>> Generating emails for {limit} most recent prospects...[/blue]")
# Get recent prospects with emails
prospects = controller.notion_manager.get_prospects()
prospects_with_emails = [p for p in prospects if p.email]
# Sort by created_at to get truly recent ones, then take the most recent
prospects_with_emails.sort(key=lambda x: x.created_at, reverse=True) # Most recent first
recent_prospects = prospects_with_emails[:limit] # Take first N (most recent)
if not recent_prospects:
console.print("[yellow]WARNING: No recent prospects with emails found.[/yellow]")
console.print("[dim]Run discovery first: python cli.py discover --limit 5[/dim]")
return 1
prospect_ids = [p.id for p in recent_prospects]
console.print(f"[dim]Found {len(recent_prospects)} recent prospects with emails:[/dim]")
for p in recent_prospects:
console.print(f" • {p.name} at {p.company}")
# Generate emails
template_map = {
'cold_outreach': EmailTemplate.COLD_OUTREACH,
'referral_followup': EmailTemplate.REFERRAL_FOLLOWUP,
'product_interest': EmailTemplate.PRODUCT_INTEREST,
'networking': EmailTemplate.NETWORKING
}
email_results = controller.generate_outreach_emails(
prospect_ids=prospect_ids,
template_type=template_map[template]
)
successful = len(email_results.get('successful', []))
failed = len(email_results.get('failed', []))
console.print(f"[green]✅ Email generation completed: {successful} successful, {failed} failed[/green]")
# Show generated emails
if successful > 0:
console.print(f"\n[bold]*** Generated Emails:[/bold]")
for result in email_results.get('successful', [])[:3]: # Show first 3
console.print(f" • {result['prospect_name']} at {result['company']}")
console.print(f" Subject: {result['email_content']['subject']}")
console.print(f" Preview: {result['email_content']['body'][:100]}...")
console.print()
# Send emails if requested
if send and successful > 0:
console.print(f"[blue]>> Sending {successful} emails...[/blue]")
send_results = controller.generate_and_send_outreach_emails(
prospect_ids=prospect_ids,
template_type=template_map[template],
send_immediately=True,
delay_between_emails=2.0
)
emails_sent = send_results.get('emails_sent', 0)
console.print(f"[green]✅ Emails sent: {emails_sent}[/green]")
# Update analytics
if cli_config.base_config.analytics_db_id:
controller.create_daily_summary(cli_config.base_config.analytics_db_id)
console.print(f"\n[cyan]* Check your Notion Email Queue database for email details![/cyan]")
return 0
except Exception as e:
console.print(f"[red]❌ Email generation failed: {str(e)}[/red]")
return 1
@cli.command('profile-setup')
@click.option('--interactive', is_flag=True, help='Create profile interactively')
@click.option('--template', is_flag=True, help='Generate a profile template')
@click.option('--format', '-f', type=click.Choice(['markdown', 'json', 'yaml']), default='markdown',
help='Output format for the profile')
@click.option('--output', '-o', help='Output file path')
@click.option('--set-default', is_flag=True, help='Set as default profile')
@click.pass_context
def profile_setup(ctx, interactive, template, format, output, set_default):
"""Set up a sender profile for email personalization."""
try:
cli_config = CLIConfig(ctx.obj['config_file'], ctx.obj['dry_run'])
if cli_config.dry_run:
console.print("[yellow]DRY-RUN: Would set up sender profile[/yellow]")
if interactive:
console.print("[yellow]Would create profile interactively[/yellow]")
if template:
console.print(f"[yellow]Would generate {format} template[/yellow]")
if output:
console.print(f"[yellow]Would save to: {output}[/yellow]")
if set_default:
console.print("[yellow]Would set as default profile[/yellow]")
return
manager = SenderProfileManager()
# Determine output path if not provided
if not output:
if interactive:
output = f"profiles/profile_{format}.{format if format != 'markdown' else 'md'}"
elif template:
output = f"profiles/template_{format}.{format if format != 'markdown' else 'md'}"
else:
console.print("[red]Output path is required when not using --interactive or --template[/red]")
return 1
# Create directory if it doesn't exist
Path(output).parent.mkdir(parents=True, exist_ok=True)
# Generate template or create interactively
if template:
console.print(f"[blue]Generating {format} template...[/blue]")
template_content = manager.create_profile_template(format)
with open(output, 'w', encoding='utf-8') as f:
f.write(template_content)
console.print(f"[green]Template saved to: {output}[/green]")
console.print("[yellow]Please edit the file with your information.[/yellow]")
elif interactive:
console.print("[blue]Starting interactive profile creation...[/blue]")
# Check for existing profiles
try:
existing_profiles = manager.discover_existing_profiles()
if existing_profiles:
console.print(f"[yellow]Found {len(existing_profiles)} existing profile(s)[/yellow]")
# Use the new functionality to handle existing profiles
profile = manager.create_profile_interactively(check_existing=True)
else:
# No existing profiles, create new one
profile = manager.create_profile_interactively(check_existing=False)
except KeyboardInterrupt:
console.print("[yellow]Profile setup cancelled by user[/yellow]")
return 1
except Exception as e:
console.print(f"[red]Error during profile discovery: {e}[/red]")
# Fallback to direct creation
profile = manager.create_profile_interactively(check_existing=False)
console.print(f"[green]Profile created successfully for {profile.name}![/green]")
# Save profile to file
if format == 'markdown':
manager.save_profile_to_markdown(profile, output)
elif format == 'json':
manager.save_profile_to_json(profile, output)
elif format == 'yaml':
manager.save_profile_to_yaml(profile, output)
console.print(f"[green]Profile saved to: {output}[/green]")
# Set as default if requested
if set_default:
# Create config directory if it doesn't exist
config_dir = Path.home() / '.job_prospect_automation'
config_dir.mkdir(exist_ok=True)
# Set default profile
config_file = config_dir / 'config.json'
config = {}
if config_file.exists():
try:
with open(config_file, 'r') as f:
config = json.load(f)
except json.JSONDecodeError:
config = {}
# Convert to absolute path
abs_path = str(Path(output).resolve())
config['default_sender_profile'] = abs_path
config['default_sender_profile_format'] = format
with open(config_file, 'w') as f:
json.dump(config, f, indent=2)
console.print(f"[green]Set {abs_path} as default sender profile[/green]")
else:
console.print("[red]Either --interactive or --template must be specified[/red]")
return 1
except Exception as e:
console.print(f"[red]Error setting up profile: {e}[/red]")
sys.exit(1)
@cli.command('run-campaign')
@click.option('--limit', '-l', default=10, help='Maximum number of companies to process')
@click.option('--campaign-name', '-c', help='Name for this campaign')
@click.option('--sender-profile', '-p', help='Path to sender profile file')
@click.option('--generate-emails', is_flag=True, help='Generate emails for found prospects')
@click.option('--send-emails', is_flag=True, help='Send generated emails immediately')
@click.option('--auto-setup', is_flag=True, help='Auto-setup dashboard if not configured')
@click.pass_context
def run_campaign(ctx, limit, campaign_name, sender_profile, generate_emails, send_emails, auto_setup):
""">> Run the COMPLETE automation workflow - from discovery to email sending!"""
try:
cli_config = CLIConfig(ctx.obj['config_file'], ctx.obj['dry_run'])
if cli_config.dry_run:
console.print("[yellow]DRY-RUN: Would run complete campaign workflow[/yellow]")
console.print(f"[yellow] • Discover up to {limit} companies[/yellow]")
console.print(f"[yellow] • Campaign: {campaign_name or 'Auto-generated'}[/yellow]")
if generate_emails:
console.print("[yellow] • Generate personalized emails[/yellow]")
if send_emails:
console.print("[yellow] • Send emails immediately[/yellow]")
return
# Step 0: Auto-setup dashboard if requested and not configured
if auto_setup and not cli_config.base_config.dashboard_id:
console.print("[blue]🔧 Setting up dashboard automatically...[/blue]")
dashboard_info = setup_func()
if not dashboard_info:
console.print("[red]❌ Dashboard setup failed. Please run setup manually.[/red]")
return 1
console.print("[green]✅ Dashboard setup completed![/green]\n")
# Initialize controller
controller = ProspectAutomationController(cli_config.base_config)
# Set sender profile if provided
if sender_profile:
controller.set_sender_profile(sender_profile)
# Generate campaign name if not provided
if not campaign_name:
campaign_name = f"Campaign {datetime.now().strftime('%Y-%m-%d %H:%M')}"
console.print(Panel.fit(
f"[bold green]>> Starting Complete Campaign Workflow[/bold green]\n"
f"Campaign: {campaign_name}\n"
f"Target: {limit} companies\n"
f"Generate Emails: {'Yes' if generate_emails else 'No'}\n"
f"Send Emails: {'Yes' if send_emails else 'No'}",
border_style="green"
))
# Step 1: Discovery Pipeline
console.print("\n[bold blue]* Step 1: Company Discovery & Prospect Extraction[/bold blue]")
# Use platform-safe text to avoid Unicode encoding issues on Windows
safe_text = get_platform_safe_text(
"Monitor real-time progress in your Notion dashboard",
"💡",
"Monitor real-time progress in your Notion dashboard"
)
console.print(f"[dim]{safe_text}[/dim]")
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
) as progress:
task = progress.add_task("Running discovery pipeline...", total=None)
results = controller.run_discovery_pipeline(limit=limit, campaign_name=campaign_name)
progress.update(task, description="Discovery completed!")
# Display discovery results
_display_results(results)
prospects_found = results['summary']['prospects_found']
# Initialize result variables
email_results = {'emails_generated': 0, 'successful': []}
send_results = {'emails_sent': 0}
if prospects_found == 0:
console.print("[yellow]WARNING: No prospects found. Campaign completed.[/yellow]")
return 0
# Step 2: Email Generation (if requested)
if generate_emails:
console.print(f"\n[bold blue]* Step 2: Email Generation[/bold blue]")
# Get prospect IDs from the results
# Use the same logic as generate-emails-recent command for consistency
all_prospects = controller.notion_manager.get_prospects()
prospects_with_ids = [p for p in all_prospects if p.id]
if prospects_with_ids and prospects_found > 0:
# Sort by created_at to get truly recent ones (same as generate-emails-recent)
prospects_with_ids.sort(key=lambda x: x.created_at, reverse=True) # Most recent first
recent_prospects = prospects_with_ids[:prospects_found] # Take the exact number we found
console.print(f"[dim]Debug: Selected prospects for email generation:[/dim]")
for p in recent_prospects:
console.print(f"[dim] - {p.name} at {getattr(p, 'company', 'Unknown')} (created: {p.created_at.strftime('%H:%M:%S')})[/dim]")
else:
recent_prospects = []
prospect_ids = [p.id for p in recent_prospects] # All prospects (email generation doesn't require existing emails)
if not prospect_ids:
console.print("[yellow]WARNING: No prospects with emails found for email generation.[/yellow]")
else:
console.print(f"[dim]Generating emails for {len(prospect_ids)} prospects...[/dim]")
email_results = controller.generate_outreach_emails(
prospect_ids=prospect_ids,
template_type=EmailTemplate.COLD_OUTREACH
)
successful_emails = len(email_results.get('successful', []))
failed_emails = len(email_results.get('failed', []))
console.print(f"[green]✅ Email generation: {successful_emails} successful, {failed_emails} failed[/green]")
# Step 3: Email Sending (if requested)
if send_emails and successful_emails > 0:
console.print(f"\n[bold blue]>> Step 3: Email Sending[/bold blue]")
send_results = controller.generate_and_send_outreach_emails(
prospect_ids=prospect_ids,
template_type=EmailTemplate.COLD_OUTREACH,
send_immediately=True,
delay_between_emails=2.0
)
emails_sent = send_results.get('emails_sent', 0)
console.print(f"[green]✅ Emails sent: {emails_sent}[/green]")
# Step 4: Update Analytics
console.print(f"\n[bold blue]* Step 4: Analytics Update[/bold blue]")
analytics_db_id = cli_config.base_config.analytics_db_id
if analytics_db_id:
success = controller.create_daily_summary(analytics_db_id)
if success:
console.print("[green]✅ Daily analytics updated[/green]")
else:
console.print("[yellow]WARNING: Analytics update failed[/yellow]")
# Final Summary
safe_phone_text = get_platform_safe_emoji_text(
"{phone} Check your Notion dashboard for detailed progress and notifications!",
phone_emoji="📱",
fallback_text="Check your Notion dashboard for detailed progress and notifications!"
)
console.print(Panel.fit(
f"[bold green]*** Campaign Completed Successfully! ***[/bold green]\n\n"
f"* Results Summary:\n"
f"• Companies Processed: {results['summary']['companies_processed']}\n"
f"• Prospects Found: {prospects_found}\n"
f"• Emails Generated: {email_results.get('emails_generated', 0) if generate_emails else 'Skipped'}\n"
f"• Emails Sent: {send_results.get('emails_sent', 0) if send_emails else 'Skipped'}\n"
f"• Success Rate: {results['summary']['success_rate']:.1f}%\n"
f"• Duration: {results['summary']['duration_seconds']:.1f} seconds\n\n"
f"{safe_phone_text}",
border_style="green"
))
# Show dashboard links
if cli_config.base_config.dashboard_id:
safe_link_text = get_platform_safe_emoji_text(
"{link} Quick Links:",
link_emoji="🔗",
fallback_text="Quick Links:"
)
console.print(f"\n[cyan]{safe_link_text}[/cyan]")
console.print(f"* Dashboard: https://notion.so/{cli_config.base_config.dashboard_id.replace('-', '')}")
if cli_config.base_config.campaigns_db_id:
safe_target_text = get_platform_safe_emoji_text(
"{target} Campaign Details: https://notion.so/{cli_config.base_config.campaigns_db_id.replace('-', '')}",
target_emoji="🎯",