update
This commit is contained in:
@@ -10,9 +10,12 @@ use App\Models\Customer;
|
||||
use App\Models\Mail;
|
||||
use App\Models\MailCampaign;
|
||||
use App\Models\Template;
|
||||
use App\Services\Email\MailCampaignRenderer;
|
||||
use App\Support\MailPlaceholders;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
final class MailCampaignController extends Controller
|
||||
{
|
||||
@@ -21,7 +24,7 @@ final class MailCampaignController extends Controller
|
||||
$limit = min((int) $request->get('per_page', 20), 200);
|
||||
|
||||
$paginator = MailCampaign::query()
|
||||
->with('template')
|
||||
->with(['template', 'creator'])
|
||||
->orderByDesc('created_at')
|
||||
->paginate($limit);
|
||||
|
||||
@@ -39,7 +42,7 @@ final class MailCampaignController extends Controller
|
||||
|
||||
public function show(string $uuid): JsonResponse
|
||||
{
|
||||
$campaign = MailCampaign::with('template')->where('uuid', $uuid)->first();
|
||||
$campaign = MailCampaign::with(['template', 'creator'])->where('uuid', $uuid)->first();
|
||||
|
||||
if (!$campaign) {
|
||||
return response()->json(['error' => true, 'message' => 'Không tìm thấy chiến dịch'], 404);
|
||||
@@ -48,12 +51,13 @@ final class MailCampaignController extends Controller
|
||||
$logs = Mail::with('customer')
|
||||
->where('campaign_id', $campaign->id)
|
||||
->orderByDesc('created_at')
|
||||
->get()
|
||||
->get(['id', 'to', 'customer_id', 'subject', 'status', 'created_at'])
|
||||
->map(fn (Mail $log) => [
|
||||
'id' => $log->id,
|
||||
'to_email' => $log->to,
|
||||
'to_name' => $log->customer->fullname ?? null,
|
||||
'customer_id' => $log->customer_id,
|
||||
'subject' => $log->subject,
|
||||
'status' => $log->status,
|
||||
'created_at' => $log->created_at,
|
||||
]);
|
||||
@@ -62,35 +66,25 @@ final class MailCampaignController extends Controller
|
||||
'error' => false,
|
||||
'data' => [
|
||||
...$this->mapCampaign($campaign),
|
||||
'logs' => $logs,
|
||||
'cc' => $campaign->cc,
|
||||
'bcc' => $campaign->bcc,
|
||||
'variables' => $campaign->variables ?? [],
|
||||
'logs' => $logs,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function preview(Request $request): JsonResponse
|
||||
public function preview(Request $request, MailCampaignRenderer $renderer): 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));
|
||||
}
|
||||
$campaign = $this->draftCampaign($request->validate($this->contentRules()));
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'data' => ['html' => $this->renderPreview($subject, $message)],
|
||||
'data' => ['html' => $renderer->render($campaign, $renderer->sampleValues($campaign))['html']],
|
||||
]);
|
||||
}
|
||||
|
||||
public function previewCampaign(string $uuid): JsonResponse
|
||||
public function previewCampaign(string $uuid, MailCampaignRenderer $renderer): JsonResponse
|
||||
{
|
||||
$campaign = MailCampaign::where('uuid', $uuid)->first();
|
||||
|
||||
@@ -100,101 +94,178 @@ final class MailCampaignController extends Controller
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'data' => ['html' => $this->renderPreview($campaign->subject, $campaign->message)],
|
||||
'data' => ['html' => $renderer->render($campaign, $renderer->sampleValues($campaign))['html']],
|
||||
]);
|
||||
}
|
||||
|
||||
private function renderPreview(string $subject, string $message): string
|
||||
public function showLog(string $uuid, int $id): JsonResponse
|
||||
{
|
||||
return Template::renderWithLayout($subject, $message);
|
||||
$log = Mail::query()
|
||||
->whereKey($id)
|
||||
->whereHas('campaign', fn ($q) => $q->where('uuid', $uuid))
|
||||
->first();
|
||||
|
||||
if (!$log) {
|
||||
return response()->json(['error' => true, 'message' => 'Không tìm thấy email'], 404);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'data' => [
|
||||
'id' => $log->id,
|
||||
'to_email' => $log->to,
|
||||
'cc' => $log->cc,
|
||||
'subject' => $log->subject,
|
||||
'html' => $log->message,
|
||||
'status' => $log->status,
|
||||
'created_at' => $log->created_at,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
...$this->contentRules(),
|
||||
'recipient_type' => 'required|in:all,selected',
|
||||
'uuids' => 'required_if:recipient_type,selected|array|min:1',
|
||||
'uuids' => 'nullable|array',
|
||||
'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',
|
||||
'emails' => 'nullable|array|max:1000',
|
||||
'emails.*' => 'email|max:255',
|
||||
'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'] ?? ''));
|
||||
$campaign = $this->draftCampaign($data);
|
||||
|
||||
if (!empty($data['template_id'])) {
|
||||
$template = Template::query()
|
||||
->whereKey($data['template_id'])
|
||||
->where('status', 1)
|
||||
->first();
|
||||
$recipients = $data['recipient_type'] === 'all'
|
||||
? $this->allCustomerRecipients()
|
||||
: $this->selectedRecipients($data['uuids'] ?? [], $data['emails'] ?? []);
|
||||
|
||||
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 === '') {
|
||||
if ($recipients === []) {
|
||||
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.',
|
||||
'message' => 'Không có người nhận hợp lệ để 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,
|
||||
$campaign->fill([
|
||||
'name' => trim((string) ($data['name'] ?? '')) ?: $campaign->subject,
|
||||
'cc' => $data['cc'] ?? null,
|
||||
'bcc' => $data['bcc'] ?? null,
|
||||
'recipient_type' => $data['recipient_type'],
|
||||
'total_recipients' => $customers->count(),
|
||||
'total_recipients' => count($recipients),
|
||||
'sent_count' => 0,
|
||||
'failed_count' => 0,
|
||||
'status' => 'queued',
|
||||
'created_by' => $admin->id ?? null,
|
||||
]);
|
||||
])->save();
|
||||
|
||||
foreach ($customers as $customer) {
|
||||
SendMailCampaignRecipient::dispatch(
|
||||
$campaign->id,
|
||||
$customer->id,
|
||||
$subject,
|
||||
$message,
|
||||
$data['cc'] ?? null,
|
||||
$data['bcc'] ?? null,
|
||||
);
|
||||
foreach ($recipients as $email => $customerId) {
|
||||
SendMailCampaignRecipient::dispatch($campaign->id, $customerId, $email);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'message' => 'Chiến dịch đã được tạo và đang gửi.',
|
||||
'message' => "Đã đưa {$campaign->total_recipients} email vào hàng đợi gửi.",
|
||||
'data' => $this->mapCampaign($campaign),
|
||||
]);
|
||||
}
|
||||
|
||||
private function contentRules(): array
|
||||
{
|
||||
return [
|
||||
'template_id' => 'nullable|integer|exists:template,id',
|
||||
'subject' => 'required_without:template_id|nullable|string|max:255',
|
||||
'message' => 'required_without:template_id|nullable|string',
|
||||
'variables' => 'nullable|array',
|
||||
'variables.*' => 'nullable|string|max:5000',
|
||||
];
|
||||
}
|
||||
|
||||
private function draftCampaign(array $data): MailCampaign
|
||||
{
|
||||
$subject = trim((string) ($data['subject'] ?? ''));
|
||||
$message = trim((string) ($data['message'] ?? ''));
|
||||
$template = null;
|
||||
|
||||
if (!empty($data['template_id'])) {
|
||||
$template = Template::query()->whereKey($data['template_id'])->where('status', 1)->first();
|
||||
if (!$template || $template->format === 'json') {
|
||||
throw ValidationException::withMessages(['template_id' => 'Template không tồn tại, đang bị tắt hoặc không phải email HTML.']);
|
||||
}
|
||||
|
||||
$subject = $subject !== '' ? $subject : trim((string) $template->subject);
|
||||
$message = trim((string) $template->message);
|
||||
}
|
||||
|
||||
if ($subject === '' || $message === '') {
|
||||
throw ValidationException::withMessages(['subject' => 'Subject và content không được để trống.']);
|
||||
}
|
||||
|
||||
$input = $data['variables'] ?? [];
|
||||
$declared = $template?->variables() ?? [];
|
||||
$variables = [];
|
||||
foreach (MailPlaceholders::extract($subject, $message) as $key) {
|
||||
$value = trim((string) ($input[$key] ?? ''));
|
||||
if ($value === '' && !array_key_exists($key, MailPlaceholders::RECIPIENT_FIELDS)) {
|
||||
$value = (string) ($declared[$key]['example'] ?? '');
|
||||
}
|
||||
if ($value !== '') {
|
||||
$variables[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return new MailCampaign([
|
||||
'template_id' => $template?->id,
|
||||
'subject' => $subject,
|
||||
'message' => $message,
|
||||
'variables' => $variables ?: null,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, int>
|
||||
*/
|
||||
private function allCustomerRecipients(): array
|
||||
{
|
||||
return Customer::query()
|
||||
->whereNotNull('email')
|
||||
->where('email', '!=', '')
|
||||
->pluck('id', 'email')
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $uuids
|
||||
* @param array<int, string> $emails
|
||||
* @return array<string, int|null>
|
||||
*/
|
||||
private function selectedRecipients(array $uuids, array $emails): array
|
||||
{
|
||||
$emails = array_values(array_unique(array_map(fn ($email) => mb_strtolower(trim($email)), $emails)));
|
||||
|
||||
$customers = Customer::query()
|
||||
->where(fn ($q) => $q->whereIn('uuid', $uuids)->orWhereIn('email', $emails))
|
||||
->whereNotNull('email')
|
||||
->get(['id', 'email', 'uuid']);
|
||||
|
||||
$recipients = [];
|
||||
foreach ($customers as $customer) {
|
||||
if (in_array($customer->uuid, $uuids, true) || in_array(mb_strtolower($customer->email), $emails, true)) {
|
||||
$recipients[mb_strtolower($customer->email)] = $customer->id;
|
||||
}
|
||||
}
|
||||
foreach ($emails as $email) {
|
||||
$recipients[$email] ??= null;
|
||||
}
|
||||
|
||||
return array_filter($recipients, fn ($id, $email) => filter_var($email, FILTER_VALIDATE_EMAIL), ARRAY_FILTER_USE_BOTH);
|
||||
}
|
||||
|
||||
private function mapCampaign(MailCampaign $campaign): array
|
||||
{
|
||||
return [
|
||||
@@ -208,6 +279,8 @@ final class MailCampaignController extends Controller
|
||||
'sent_count' => $campaign->sent_count,
|
||||
'failed_count' => $campaign->failed_count,
|
||||
'status' => $campaign->status,
|
||||
'recipient_type' => $campaign->recipient_type,
|
||||
'created_by_name' => $campaign->creator->fullname ?? $campaign->creator->username ?? null,
|
||||
'completed_at' => $campaign->completed_at,
|
||||
'created_at' => $campaign->created_at,
|
||||
];
|
||||
|
||||
Reference in New Issue
Block a user