Files
portal-api/app/Http/Controllers/Api/Admin/MailCampaign/MailCampaignController.php
T

219 lines
7.7 KiB
PHP

<?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,
];
}
}