feat: Implement mail campaign feature with CRUD operations and email sending capabilities

This commit is contained in:
baodev0
2026-08-21 16:57:32 +07:00
parent 8d0a5322ea
commit eec2c5906e
11 changed files with 593 additions and 3 deletions
@@ -0,0 +1,218 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\Admin\MailCampaign;
use App\Http\Controllers\Controller;
use App\Jobs\Mail\SendMailCampaignRecipient;
use App\Models\Customer;
use App\Models\Mail;
use App\Models\MailCampaign;
use App\Models\Template;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
final class MailCampaignController extends Controller
{
public function index(Request $request): JsonResponse
{
$limit = min((int) $request->get('per_page', 20), 200);
$paginator = MailCampaign::query()
->with('template')
->orderByDesc('created_at')
->paginate($limit);
return response()->json([
'error' => false,
'data' => [
'items' => $paginator->getCollection()->map($this->mapCampaign(...))->all(),
'total' => $paginator->total(),
'per_page' => $paginator->perPage(),
'current_page' => $paginator->currentPage(),
'last_page' => $paginator->lastPage(),
],
]);
}
public function show(string $uuid): JsonResponse
{
$campaign = MailCampaign::with('template')->where('uuid', $uuid)->first();
if (!$campaign) {
return response()->json(['error' => true, 'message' => 'Không tìm thấy chiến dịch'], 404);
}
$logs = Mail::with('customer')
->where('campaign_id', $campaign->id)
->orderByDesc('created_at')
->get()
->map(fn (Mail $log) => [
'id' => $log->id,
'to_email' => $log->to,
'to_name' => $log->customer->fullname ?? null,
'customer_id' => $log->customer_id,
'status' => $log->status,
'created_at' => $log->created_at,
]);
return response()->json([
'error' => false,
'data' => [
...$this->mapCampaign($campaign),
'logs' => $logs,
],
]);
}
public function preview(Request $request): JsonResponse
{
$data = $request->validate([
'template_id' => 'nullable|integer|exists:template,id',
'subject' => 'required_without:template_id|nullable|string|max:255',
'message' => 'required_without:template_id|nullable|string',
]);
$subject = trim((string) ($data['subject'] ?? ''));
$message = trim((string) ($data['message'] ?? ''));
if (!empty($data['template_id'])) {
$template = Template::find($data['template_id']);
$subject = trim((string) ($template->subject ?? $subject));
$message = trim((string) ($template->message ?? $message));
}
return response()->json([
'error' => false,
'data' => ['html' => $this->renderPreview($subject, $message)],
]);
}
public function previewCampaign(string $uuid): JsonResponse
{
$campaign = MailCampaign::where('uuid', $uuid)->first();
if (!$campaign) {
return response()->json(['error' => true, 'message' => 'Không tìm thấy chiến dịch'], 404);
}
return response()->json([
'error' => false,
'data' => ['html' => $this->renderPreview($campaign->subject, $campaign->message)],
]);
}
private function renderPreview(string $subject, string $message): string
{
return view('emails.customer.template-camp', [
'content' => $message,
'emailSubject' => $subject,
])->render();
}
public function store(Request $request): JsonResponse
{
$data = $request->validate([
'recipient_type' => 'required|in:all,selected',
'uuids' => 'required_if:recipient_type,selected|array|min:1',
'uuids.*' => 'string|exists:customers,uuid',
'template_id' => 'nullable|integer|exists:template,id',
'subject' => 'required_without:template_id|nullable|string|max:255',
'message' => 'required_without:template_id|nullable|string',
'name' => 'nullable|string|max:255',
'cc' => 'nullable|string|max:1000',
'bcc' => 'nullable|string|max:1000',
]);
$template = null;
$subject = trim((string) ($data['subject'] ?? ''));
$message = trim((string) ($data['message'] ?? ''));
if (!empty($data['template_id'])) {
$template = Template::query()
->whereKey($data['template_id'])
->where('status', 1)
->first();
if (!$template) {
return response()->json([
'error' => true,
'message' => 'Template không tồn tại hoặc đang bị tắt.',
], 422);
}
$subject = trim((string) $template->subject);
$message = trim((string) $template->message);
}
if ($subject === '' || $message === '') {
return response()->json([
'error' => true,
'message' => 'Subject và content không được để trống.',
], 422);
}
$customers = $data['recipient_type'] === 'all'
? Customer::query()->whereNotNull('email')->get(['id', 'email'])
: Customer::query()->whereIn('uuid', $data['uuids'])->get(['id', 'email']);
if ($customers->isEmpty()) {
return response()->json([
'error' => true,
'message' => 'Không tìm thấy khách hàng nào để gửi.',
], 422);
}
$admin = Auth::guard('admin')->user();
$campaign = MailCampaign::create([
'name' => trim((string) ($data['name'] ?? '')) ?: $subject,
'template_id' => $template->id ?? null,
'subject' => $subject,
'message' => $message,
'cc' => $data['cc'] ?? null,
'bcc' => $data['bcc'] ?? null,
'recipient_type' => $data['recipient_type'],
'total_recipients' => $customers->count(),
'status' => 'queued',
'created_by' => $admin->id ?? null,
]);
foreach ($customers as $customer) {
SendMailCampaignRecipient::dispatch(
$campaign->id,
$customer->id,
$subject,
$message,
$data['cc'] ?? null,
$data['bcc'] ?? null,
);
}
return response()->json([
'error' => false,
'message' => 'Chiến dịch đã được tạo và đang gửi.',
'data' => $this->mapCampaign($campaign),
]);
}
private function mapCampaign(MailCampaign $campaign): array
{
return [
'id' => $campaign->id,
'uuid' => $campaign->uuid,
'name' => $campaign->name,
'subject' => $campaign->subject,
'template_id' => $campaign->template_id,
'template_name' => $campaign->template->name ?? null,
'total_recipients' => $campaign->total_recipients,
'sent_count' => $campaign->sent_count,
'failed_count' => $campaign->failed_count,
'status' => $campaign->status,
'completed_at' => $campaign->completed_at,
'created_at' => $campaign->created_at,
];
}
}
+104
View File
@@ -0,0 +1,104 @@
<?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(),
]);
}
}
}
+4 -1
View File
@@ -24,7 +24,10 @@ class ManualCustomerEmail extends Mailable
public function content(): Content
{
return new Content(htmlString: $this->htmlContent);
return new Content(
view: 'emails.customer.template-camp',
with: ['content' => $this->htmlContent, 'emailSubject' => $this->emailSubject],
);
}
public function attachments(): array
+6
View File
@@ -12,6 +12,7 @@ class Mail extends Model
protected $table = 'mail';
protected $fillable = [
'campaign_id',
'template_id',
'subject',
'to',
@@ -42,4 +43,9 @@ class Mail extends Model
{
return $this->belongsTo(Template::class, 'template_id');
}
public function campaign()
{
return $this->belongsTo(MailCampaign::class, 'campaign_id');
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class MailCampaign extends Model
{
use HasFactory;
protected $table = 'mail_campaigns';
protected $fillable = [
'uuid',
'name',
'template_id',
'subject',
'message',
'cc',
'bcc',
'recipient_type',
'total_recipients',
'sent_count',
'failed_count',
'status',
'created_by',
'completed_at',
];
protected $casts = [
'total_recipients' => 'integer',
'sent_count' => 'integer',
'failed_count' => 'integer',
'completed_at' => 'datetime',
];
protected static function booted(): void
{
static::creating(function (self $campaign) {
$campaign->uuid ??= (string) Str::uuid();
});
}
public function logs()
{
return $this->hasMany(Mail::class, 'campaign_id');
}
public function template()
{
return $this->belongsTo(Template::class, 'template_id');
}
}
+15 -2
View File
@@ -54,12 +54,25 @@ class OrderRepository extends BaseRepository implements OrderRepositoryInterface
$model = $model->where("invoice_id", $data['invoice_id']);
}
}
if (isset($data['status']) && ! empty($data['status']) && $data['status'] != 'full') {
$model = $model->where("status", match ($data['status']) {
if (isset($data['status']) && $data['status'] !== '' && $data['status'] !== null && $data['status'] != 'full') {
$status = match ($data['status']) {
'active' => 1,
'pending' => 0,
'processing' => 3,
'cancel' => 2,
default => $data['status'],
};
$model = $model->where("status", $status);
}
if (isset($data['filter']) && $data['filter'] !== '') {
$search = $data['filter'];
$model = $model->where(function ($query) use ($search) {
$query->where('order_num', 'like', "%{$search}%")
->orWhereHas('customer', function ($query) use ($search) {
$query->where('fullname', 'like', "%{$search}%")
->orWhere('email', 'like', "%{$search}%");
});
});
}