1namespace App\Console\Commands;
2
3use App\Mail\TrialExpiringSoon;
4use App\Team;
5use Exception;
6use Illuminate\Console\Command;
7use Illuminate\Support\Facades\Mail;
8
9class EmailTeamsWithExpiringTrials extends Command
10{
11 protected $signature = 'ohdear:email-teams-with-expiring-trials';
12
13 protected $description = 'Email teams with expiring trials.';
14
15 protected $mailsSent = 0;
16
17 protected $mailFailures = 0;
18
19 public function handle()
20 {
21 $this->info('Sending trial expiring soon mails...');
22
23 Team::all()
24 ->filter->onSoonExpiringTrial()
25 ->each(function (Team $team) {
26 $this->sendTrialEndingSoonMail($team);
27 });
28
29 $this->info("{$this->mailsSent} trial expiring mails sent!");
30
31 if ($this->mailFailures > 0) {
32 $this->error("Failed to send {$this->mailFailures} trial expiring mails!");
33 }
34 }
35
36 protected function sendTrialEndingSoonMail(Team $team)
37 {
38 try {
39 if ($team->wasAlreadySentTrialExpiringSoonMail()) {
40 return;
41 }
42
43 $this->comment("Mailing {$team->owner->email} (team {$team->name})");
44 Mail::to($team->owner->email)->send(new TrialExpiringSoon($team));
45
46 $this->mailsSent++;
47
48 $team->rememberHasBeenSentTrialExpiringSoonMail();
49 } catch (Exception $exception) {
50 $this->error("exception when sending mail to team {$team->id}", $exception);
51 report($exception);
52 $this->mailFailures++;
53 }
54 }
55}
56