Files
portal-api/app/Jobs/Mail/SendMailCampaignRecipient.php
T
baodev0andClaude Opus 5.5 bf78f3b810 feat: hồ sơ khách (ngày sinh, tỉnh/phường theo mã), gộp menu + nút tắt, thông báo theo uuid
- PUT v1/client/update: gender theo enum ClientGender (0 Nam/1 Nữ), thêm
  birthday (cột mới), province_code/ward_code validate theo bảng provinces/wards
  (phường phải thuộc tỉnh). Migration nạp dữ liệu hành chính 2025 từ
  province_ward_import.sql (chỉ bảng trống), API GET v1/provinces[/{code}/wards].
- CustomerObserver/OrderObserver log giá trị cũ bằng getRawOriginal: getOriginal
  trả enum object, nối chuỗi gây 500 khi khách đổi giới tính.
- ClientResource: các cờ trả boolean, CCCD chỉ trả cccd_updated (không lộ ảnh/số).
- GET v1/setting/menu trả cả items + quick_links, bỏ v1/setting/quick-links.
- Thông báo admin/khách tra theo uuid thay vì id tự tăng.
- Chặn gửi template marketing cho khách đã tắt nhận email marketing.
- Xoá ProvinceWardSeeder và Customer::$updatable không dùng.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:03:18 +07:00

118 lines
4.4 KiB
PHP

<?php
namespace App\Jobs\Mail;
use App\Mail\GenericTemplateMail;
use App\Models\Customer;
use App\Models\Mail as MailLog;
use App\Models\MailCampaign;
use App\Models\Notification;
use App\Services\Email\MailCampaignRenderer;
use App\Support\EmailRecipients;
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\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
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 $email,
) {}
public function handle(MailCampaignRenderer $renderer): void
{
$campaign = MailCampaign::with('template')->find($this->campaignId);
if (!$campaign) {
return;
}
$customer = $this->customerId ? Customer::find($this->customerId) : null;
if ($customer && $campaign->isMarketing() && !$customer->acceptsMarketingEmail()) {
$this->markDone($campaign, true);
return;
}
$rendered = $renderer->render($campaign, $renderer->recipientValues($campaign, $customer, $this->email));
$cc = EmailRecipients::parse($campaign->cc);
$bcc = EmailRecipients::parse($campaign->bcc);
$mailConfig = Arr::only($campaign->template?->mailConfig() ?? [], ['from_email', 'from_name', 'reply_to', 'reply_to_name']);
$failed = false;
try {
$mailer = Mail::to($this->email);
if ($cc) {
$mailer->cc($cc);
}
if ($bcc) {
$mailer->bcc($bcc);
}
$failed = $mailer->send(new GenericTemplateMail(
$rendered['subject'],
$rendered['html'],
$mailConfig,
)) === null;
} catch (\Throwable $e) {
$failed = true;
Log::warning('Gửi email chiến dịch thất bại', [
'campaign_id' => $campaign->id,
'to' => $this->email,
'error' => $e->getMessage(),
]);
}
MailLog::create([
'campaign_id' => $campaign->id,
'template_id' => $campaign->template_id ?? 0,
'subject' => $rendered['subject'],
'from_address' => $mailConfig['from_email'] ?? config('mail.from.address'),
'to' => $this->email,
'cc' => implode(', ', $cc),
'bcc' => implode(', ', $bcc),
'customer_id' => $customer?->id,
'sent_by' => $campaign->created_by,
'message' => $rendered['html'],
'status' => $failed ? 'failed' : 'sent',
]);
$this->markDone($campaign, $failed);
}
private function markDone(MailCampaign $campaign, bool $failed): void
{
$campaign->increment($failed ? 'failed_count' : 'sent_count');
$finished = MailCampaign::whereKey($campaign->id)
->whereIn('status', ['queued', 'sending'])
->whereRaw('sent_count + failed_count >= total_recipients')
->update([
'status' => DB::raw("CASE WHEN sent_count = 0 THEN 'failed' ELSE 'completed' END"),
'completed_at' => now(),
]);
if ($finished && $campaign->created_by) {
$campaign->refresh();
Notification::create([
'recipient_type' => 'admin',
'recipient_id' => $campaign->created_by,
'type' => 'mail_campaign_completed',
'title' => $campaign->status === 'failed' ? 'Gửi email thất bại' : 'Đã gửi email thành công',
'body' => "{$campaign->name}: {$campaign->sent_count}/{$campaign->total_recipients} email đã gửi"
. ($campaign->failed_count ? ", {$campaign->failed_count} lỗi." : '.'),
'link' => "/mail-campaigns/{$campaign->uuid}",
'data' => ['campaign_uuid' => $campaign->uuid],
]);
}
}
}