Files
portal-api/app/Jobs/Mail/SendMailCampaignRecipient.php
T

105 lines
3.3 KiB
PHP

<?php
namespace App\Jobs\Mail;
use App\Mail\Customer\ManualCustomerEmail;
use App\Models\Customer;
use App\Models\MailCampaign;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;
class SendMailCampaignRecipient implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
private readonly int $campaignId,
private readonly int $customerId,
private readonly string $subject,
private readonly string $message,
private readonly ?string $cc = null,
private readonly ?string $bcc = null,
) {}
public function handle(): void
{
$campaign = MailCampaign::find($this->campaignId);
$customer = Customer::find($this->customerId);
if (!$campaign || !$customer || !$customer->email) {
$this->markSent($campaign, failed: true);
return;
}
try {
$mailer = Mail::to($customer->email);
if ($cc = $this->parseRecipients($this->cc)) {
$mailer->cc($cc);
}
if ($bcc = $this->parseRecipients($this->bcc)) {
$mailer->bcc($bcc);
}
$mailer->send(new ManualCustomerEmail($this->subject, $this->message));
\App\Models\Mail::create([
'campaign_id' => $campaign->id,
'template_id' => $campaign->template_id ?? 0,
'subject' => $this->subject,
'to' => $customer->email,
'customer_id' => $customer->id,
'message' => $this->message,
'status' => 'sent',
]);
$this->markSent($campaign, failed: false);
} catch (\Throwable) {
\App\Models\Mail::create([
'campaign_id' => $campaign->id,
'template_id' => $campaign->template_id ?? 0,
'subject' => $this->subject,
'to' => $customer->email,
'customer_id' => $customer->id,
'message' => $this->message,
'status' => 'failed',
]);
$this->markSent($campaign, failed: true);
}
}
private function parseRecipients(?string $value): array
{
if (!$value) {
return [];
}
return collect(preg_split('/[,;]+/', $value) ?: [])
->map(fn ($email) => trim((string) $email))
->filter(fn ($email) => $email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL))
->unique()
->values()
->all();
}
private function markSent(?MailCampaign $campaign, bool $failed): void
{
if (!$campaign) {
return;
}
$campaign->increment($failed ? 'failed_count' : 'sent_count');
$campaign->refresh();
if ($campaign->sent_count + $campaign->failed_count >= $campaign->total_recipients) {
$campaign->update([
'status' => $campaign->failed_count > 0 && $campaign->sent_count === 0 ? 'failed' : 'completed',
'completed_at' => now(),
]);
}
}
}