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}%");
});
});
}
@@ -0,0 +1,40 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('mail_campaigns', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
$table->string('name', 255)->nullable();
$table->bigInteger('template_id')->nullable()->index();
$table->string('subject', 255);
$table->longText('message');
$table->unsignedInteger('total_recipients')->default(0);
$table->unsignedInteger('sent_count')->default(0);
$table->unsignedInteger('failed_count')->default(0);
$table->string('status', 20)->default('queued');
$table->bigInteger('created_by')->nullable()->index();
$table->timestamp('completed_at')->nullable();
$table->timestamps();
});
Schema::table('mail', function (Blueprint $table) {
$table->bigInteger('campaign_id')->nullable()->index()->after('id');
});
}
public function down(): void
{
Schema::table('mail', function (Blueprint $table) {
$table->dropColumn('campaign_id');
});
Schema::dropIfExists('mail_campaigns');
}
};
@@ -0,0 +1,24 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('mail_campaigns', function (Blueprint $table) {
$table->string('cc', 1000)->nullable()->after('message');
$table->string('bcc', 1000)->nullable()->after('cc');
$table->string('recipient_type', 20)->default('selected')->after('bcc');
});
}
public function down(): void
{
Schema::table('mail_campaigns', function (Blueprint $table) {
$table->dropColumn(['cc', 'bcc', 'recipient_type']);
});
}
};
+5
View File
@@ -21,6 +21,11 @@ class RolesAndPermissions extends Seeder
'customer.destroy',
'customer.manager',
// Chiến dịch email
'mail-campaign.view',
'mail-campaign.create',
'mail-campaign.manager',
// Nhân sự
'administrator.view',
'administrator.create',
@@ -0,0 +1,110 @@
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ $emailSubject ?? '' }}</title>
</head>
<body>
<table style="border-collapse: collapse; width: 100%; background-color: #efefef;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="padding: 20px;" align="center" valign="top">
<table style="padding-top: 20px; padding-bottom: 20px; border-collapse: collapse; background-color: #ffffff; width: 700px;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr class="Header">
<td style="width: 700px;" valign="top">
<table align="center" width="700" bgcolor="#ffffff" style="border-collapse: collapse; width: 700px; max-width: 100%; text-align: center; background-color: #ffffff; border-top: 5px solid #f16723;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="padding: 0;">
<a href="https://tgs.com.vn" style="display: block;" target="_blank" rel="noopener">
<img src="https://res.cloudinary.com/izpast9i/image/upload/v1786499308/email_header.png" alt="Thư gửi từ Công Ty Cổ Phần Giải Pháp Công Nghệ Thế Giới Số" style="width: 100%; display: block; border: none;" width="700">
</a>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr class="NoiDungKM">
<td style="width: 700px; padding: 25px; background-color: #ffffff;" valign="top">
{!! $content !!}
</td>
</tr>
<tr class="Footer">
<td align="center" valign="top">
<table border="0" cellpadding="0" cellspacing="0" width="700" align="center" background="https://res.cloudinary.com/izpast9i/image/upload/v1786500298/email_footer.png" bgcolor="#F16723" style="border-collapse: collapse; width: 700px; background-image: url(&quot;https://res.cloudinary.com/izpast9i/image/upload/v1786500298/email_footer.png&quot;); background-size: cover; background-position: center; background-repeat: no-repeat;">
<tbody>
<tr>
<td style="padding: 40px 30px 20px 30px; text-align: center;">
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="border-collapse: separate; border-spacing: 8px 0; width: 100%;">
<tbody>
<tr>
<td width="25%" style="border: 1px solid rgba(255,255,255,0.35); border-radius: 8px; padding: 6px 4px; font-size: 12px; line-height: 16px; color: #ffffff; text-align: center; background-color: rgba(255,255,255,0.18); backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px);">
<a href="https://tgs.com.vn/premium-hosting/" target="_blank" rel="noopener" style="color: #ffffff; text-decoration: none;">Premium Hosting</a>
</td>
<td width="25%" style="border: 1px solid rgba(255,255,255,0.35); border-radius: 8px; padding: 6px 4px; font-size: 12px; line-height: 16px; color: #ffffff; text-align: center; background-color: rgba(255,255,255,0.18); backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px);">
<a href="https://tgs.com.vn/cloud-server/" target="_blank" rel="noopener" style="color: #ffffff; text-decoration: none;">Cloud Server</a>
</td>
<td width="25%" style="border: 1px solid rgba(255,255,255,0.35); border-radius: 8px; padding: 6px 4px; font-size: 12px; line-height: 16px; color: #ffffff; text-align: center; background-color: rgba(255,255,255,0.18); backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px);">
<a href="https://cloudemail.vn/" target="_blank" rel="noopener" style="color: #ffffff; text-decoration: none;">Email doanh nghiệp</a>
</td>
<td width="25%" style="border: 1px solid rgba(255,255,255,0.35); border-radius: 8px; padding: 6px 4px; font-size: 12px; line-height: 16px; color: #ffffff; text-align: center; background-color: rgba(255,255,255,0.18); backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px);">
<a href="https://tgs.com.vn/thiet-ke-website/" target="_blank" rel="noopener" style="color: #ffffff; text-decoration: none;">Thiết kế website</a>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td style="padding: 6px 30px 0 30px; text-align: center;">
<strong style="font-size: 14px; line-height: 22px; color: #ffffff;">CÔNG TY CỔ PHẦN GIẢI PHÁP CÔNG NGHỆ THẾ GIỚI SỐ</strong>
</td>
</tr>
<tr>
<td style="padding: 6px 30px 0 30px; text-align: center;">
<span style="font-size: 12px; line-height: 18px; color: #ffffff;">Địa chỉ: 128/38 Tân Hương, Phường Phú Thọ Hòa, Thành Phố Hồ Chí Minh</span>
</td>
</tr>
<tr>
<td style="padding: 6px 30px 0 30px; text-align: center;">
<span style="font-size: 12px; line-height: 18px; color: #ffffff;">Tel: (028) 7309. 7379 &nbsp;-&nbsp; MST: 0318443116</span>
</td>
</tr>
<tr>
<td style="padding: 6px 30px 0 30px; text-align: center;">
<span style="font-size: 12px; line-height: 18px; color: #ffffff;">Email: <a href="mailto:info@tgs.com.vn" style="color: #ffffff; text-decoration: none;">info@tgs.com.vn</a></span>
</td>
</tr>
<tr>
<td style="padding: 6px 30px 0 30px; text-align: center;">
<span style="font-size: 12px; line-height: 18px; color: #ffffff;">
<a href="https://www.tgs.com.vn" style="color: #ffffff; text-decoration: underline;">www.TGS.com.vn</a>
&nbsp;&amp;&nbsp;
<a href="https://www.thegioiso.cloud" style="color: #ffffff; text-decoration: underline;">www.thegioiso.CLOUD</a>
&nbsp;&amp;&nbsp;
<a href="https://www.thegioiserver.com" style="color: #ffffff; text-decoration: underline;">www.thegioiSERVER.com</a>
&nbsp;&amp;&nbsp;
<a href="https://www.cloudemail.vn" style="color: #ffffff; text-decoration: underline;">www.CloudEmail.vn</a>
</span>
</td>
</tr>
<tr>
<td style="padding: 6px 30px 16px 30px; text-align: center;">
<span style="font-size: 12px; line-height: 20px; color: #ffffff; font-weight: bold;">Thế Giới Số- Premium HOSTING • CLOUD • SERVER &amp; WEBSITE | 15+ năm Phụng Sự</span>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</body>
</html>
+12
View File
@@ -36,6 +36,7 @@ use App\Http\Controllers\Api\Admin\EmailNotificationTemplateController;
use App\Http\Controllers\Api\Admin\ActivityLog\ActivityLogController;
use App\Http\Controllers\Api\Admin\Rebuild\AdminReinstallLogController;
use App\Http\Controllers\Api\Admin\EmailLog\EmailLogController;
use App\Http\Controllers\Api\Admin\MailCampaign\MailCampaignController;
use App\Http\Controllers\Api\Admin\Transaction\AdminTransactionController;
use App\Http\Controllers\Api\Admin\Ticket\TicketController as AdminTicketController;
use App\Http\Controllers\Api\Admin\Docs\PostCategoryController as AdminPostCategoryController;
@@ -699,6 +700,17 @@ Route::prefix('v1')
Route::get('{id}', 'show')->whereNumber('id');
});
// Mail Campaigns (module: mail-campaign)
Route::prefix('mail-campaigns')
->controller(MailCampaignController::class)
->group(function () {
Route::get('/', 'index')->middleware('perm:mail-campaign.view');
Route::post('preview', 'preview')->middleware('perm:mail-campaign.create');
Route::get('{uuid}/preview', 'previewCampaign')->middleware('perm:mail-campaign.view');
Route::get('{uuid}', 'show')->middleware('perm:mail-campaign.view');
Route::post('/', 'store')->middleware('perm:mail-campaign.create');
});
// VM Rebuild Logs — who rebuilt, which OS, post-rebuild password
Route::prefix('rebuild-logs')
->controller(AdminReinstallLogController::class)