update
This commit is contained in:
@@ -2,12 +2,17 @@
|
||||
|
||||
namespace App\Http\Controllers\Api\Admin\EmailTemplate;
|
||||
|
||||
use App\Support\EmailRecipients;
|
||||
use App\Support\MailGlobals;
|
||||
use App\Support\MailPlaceholders;
|
||||
use App\Exceptions\InvalidTemplateVariableException;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Mail\GenericTemplateMail;
|
||||
use App\Models\Setting;
|
||||
use App\Models\Template;
|
||||
use App\Services\Email\EmailTemplateRenderer;
|
||||
use App\Services\Email\TemplateGuard;
|
||||
use App\Support\EmailScenarioRegistry;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -17,6 +22,13 @@ use Illuminate\Validation\Rule;
|
||||
|
||||
class EmailTemplateController extends Controller
|
||||
{
|
||||
private const VARIABLE_RULES = [
|
||||
'variables' => 'sometimes|array',
|
||||
'variables.*.key' => ['required', 'string', 'max:100', 'regex:/^[a-zA-Z_][a-zA-Z0-9_]*$/'],
|
||||
'variables.*.label' => 'nullable|string|max:255',
|
||||
'variables.*.example' => 'nullable|string|max:5000',
|
||||
];
|
||||
|
||||
private ?array $scenarioLabelOverridesCache = null;
|
||||
|
||||
public function index(Request $request): JsonResponse
|
||||
@@ -40,32 +52,39 @@ class EmailTemplateController extends Controller
|
||||
return response()->json(['error' => false, 'data' => $this->format($template)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Danh sách scenario để render dropdown động ở frontend — gồm cả scenario
|
||||
* đã khai báo sẵn (Template::SCENARIOS) lẫn scenario tự tạo (đã dùng
|
||||
* trong bảng template nhưng chưa có label cứng trong code).
|
||||
*/
|
||||
public function scenarios(): JsonResponse
|
||||
{
|
||||
$used = Template::whereNotNull('scenario')->distinct()->pluck('scenario')->all();
|
||||
$labels = $this->scenarioLabelOverrides();
|
||||
$templates = Template::query()->get(['key', 'scenario', 'status']);
|
||||
$labels = $this->scenarioLabelOverrides();
|
||||
|
||||
$known = collect(Template::SCENARIOS)->map(fn ($label, $key) => [
|
||||
'key' => $key,
|
||||
'label' => $labels[$key] ?? $label,
|
||||
'has_template' => in_array($key, $used, true),
|
||||
]);
|
||||
$registered = collect(EmailScenarioRegistry::SCENARIOS)->map(function ($definition, $key) use ($templates, $labels) {
|
||||
$matches = $templates->filter(fn ($t) => $t->key === $key || $t->scenario === $key);
|
||||
|
||||
$custom = collect($used)
|
||||
->reject(fn ($key) => array_key_exists($key, Template::SCENARIOS))
|
||||
->map(fn ($key) => ['key' => $key, 'label' => $labels[$key] ?? $key, 'has_template' => true]);
|
||||
return [
|
||||
...EmailScenarioRegistry::describe($key),
|
||||
'key' => $key,
|
||||
'label' => $labels[$key] ?? $definition['label'],
|
||||
'has_template' => $matches->isNotEmpty(),
|
||||
'is_active' => $matches->contains(fn ($t) => (int) $t->status === 1),
|
||||
];
|
||||
});
|
||||
|
||||
return response()->json(['error' => false, 'data' => $known->concat($custom)->values()]);
|
||||
$custom = $templates->pluck('scenario')->filter()->unique()
|
||||
->reject(fn ($key) => EmailScenarioRegistry::find($key) !== null)
|
||||
->map(fn ($key) => [
|
||||
...EmailScenarioRegistry::describe($key),
|
||||
'key' => $key,
|
||||
'label' => $labels[$key] ?? $key,
|
||||
'has_template' => true,
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
return response()->json(['error' => false, 'data' => $registered->values()->concat($custom->values())]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Đặt/đổi tên hiển thị (label) cho một scenario — cho cả scenario tự tạo
|
||||
* lẫn scenario khai báo sẵn trong Template::SCENARIOS. Lưu trong Setting
|
||||
* lẫn scenario khai báo sẵn trong EmailScenarioRegistry. Lưu trong Setting
|
||||
* (key=scenario_labels) vì scenario là khái niệm chung, không thuộc riêng
|
||||
* một Template row nào.
|
||||
*/
|
||||
@@ -96,7 +115,7 @@ class EmailTemplateController extends Controller
|
||||
: [];
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
public function store(Request $request, TemplateGuard $guard): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'name' => 'nullable|string|max:255',
|
||||
@@ -117,9 +136,10 @@ class EmailTemplateController extends Controller
|
||||
'mail_config.cc.*' => 'email',
|
||||
'mail_config.bcc' => 'nullable|array',
|
||||
'mail_config.bcc.*' => 'email',
|
||||
...self::VARIABLE_RULES,
|
||||
]);
|
||||
|
||||
$template = DB::transaction(fn() => Template::create([
|
||||
$template = new Template([
|
||||
'type_id' => 0,
|
||||
'name' => $data['name'] ?? null,
|
||||
'scenario' => $data['scenario'] ?? null,
|
||||
@@ -131,7 +151,10 @@ class EmailTemplateController extends Controller
|
||||
'builder_data' => $data['builder_data'] ?? null,
|
||||
'status' => $data['status'] ?? 1,
|
||||
'metadata' => isset($data['mail_config']) ? ['mail' => $data['mail_config']] : null,
|
||||
]));
|
||||
]);
|
||||
$this->syncVariables($template, $data['variables'] ?? []);
|
||||
$guard->assertCanSave($template);
|
||||
DB::transaction(fn () => $template->save());
|
||||
|
||||
return response()->json([
|
||||
'error' => false, 'message' => 'Tạo template thành công.',
|
||||
@@ -139,7 +162,7 @@ class EmailTemplateController extends Controller
|
||||
], 201);
|
||||
}
|
||||
|
||||
public function update(Request $request, int $id): JsonResponse
|
||||
public function update(Request $request, int $id, TemplateGuard $guard): JsonResponse
|
||||
{
|
||||
$template = Template::findOrFail($id);
|
||||
|
||||
@@ -162,17 +185,21 @@ class EmailTemplateController extends Controller
|
||||
'mail_config.cc.*' => 'email',
|
||||
'mail_config.bcc' => 'nullable|array',
|
||||
'mail_config.bcc.*' => 'email',
|
||||
...self::VARIABLE_RULES,
|
||||
]);
|
||||
|
||||
// metadata.variables do developer khai báo theo code — admin chỉ được sửa metadata.mail.
|
||||
if (array_key_exists('mail_config', $data)) {
|
||||
$metadata = $template->metadata ?? [];
|
||||
$metadata['mail'] = $data['mail_config'] ?? [];
|
||||
$data['metadata'] = $metadata;
|
||||
}
|
||||
unset($data['mail_config']);
|
||||
$variables = $data['variables'] ?? [];
|
||||
unset($data['mail_config'], $data['variables']);
|
||||
|
||||
DB::transaction(fn() => $template->update($data));
|
||||
$template->fill($data);
|
||||
$this->syncVariables($template, $variables);
|
||||
$guard->assertCanSave($template);
|
||||
DB::transaction(fn () => $template->save());
|
||||
|
||||
return response()->json([
|
||||
'error' => false, 'message' => 'Cập nhật template thành công.',
|
||||
@@ -180,9 +207,11 @@ class EmailTemplateController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
public function destroy(int $id): JsonResponse
|
||||
public function destroy(int $id, TemplateGuard $guard): JsonResponse
|
||||
{
|
||||
DB::transaction(fn() => Template::findOrFail($id)->delete());
|
||||
$template = Template::findOrFail($id);
|
||||
$guard->assertCanDelete($template);
|
||||
DB::transaction(fn () => $template->delete());
|
||||
return response()->json(['error' => false, 'message' => 'Đã xoá template.']);
|
||||
}
|
||||
|
||||
@@ -232,9 +261,9 @@ class EmailTemplateController extends Controller
|
||||
$overrides = $request->validate([
|
||||
'subject' => 'nullable|string|max:255',
|
||||
'message' => 'nullable|string',
|
||||
...self::VARIABLE_RULES,
|
||||
]);
|
||||
|
||||
// Cho phép preview nội dung đang sửa dở (chưa lưu) bằng cách override tạm, không đụng DB.
|
||||
$draft = clone $template;
|
||||
if (array_key_exists('subject', $overrides)) {
|
||||
$draft->subject = $overrides['subject'];
|
||||
@@ -242,9 +271,11 @@ class EmailTemplateController extends Controller
|
||||
if (array_key_exists('message', $overrides)) {
|
||||
$draft->message = $overrides['message'];
|
||||
}
|
||||
$draft->syncVariables($overrides['variables'] ?? []);
|
||||
|
||||
$exampleData = collect($template->variables())
|
||||
$exampleData = collect($draft->variables())
|
||||
->mapWithKeys(fn ($def, $key) => [$key => $def['example'] ?? "[{$key}]"])
|
||||
->merge(MailGlobals::values())
|
||||
->all();
|
||||
|
||||
try {
|
||||
@@ -272,23 +303,24 @@ class EmailTemplateController extends Controller
|
||||
'bcc' => 'nullable|string',
|
||||
]);
|
||||
|
||||
$to = $this->parseRecipients($data['to']);
|
||||
$to = EmailRecipients::parse($data['to']);
|
||||
if (empty($to)) {
|
||||
return response()->json(['error' => true, 'message' => 'Vui lòng nhập email người nhận hợp lệ.'], 422);
|
||||
}
|
||||
|
||||
$exampleData = collect($template->variables())
|
||||
->mapWithKeys(fn ($def, $key) => [$key => $def['example'] ?? "[{$key}]"])
|
||||
->merge(MailGlobals::values())
|
||||
->all();
|
||||
|
||||
try {
|
||||
$rendered = $renderer->render($template, $exampleData);
|
||||
|
||||
$mailer = Mail::to($to);
|
||||
if ($cc = $this->parseRecipients($data['cc'] ?? null)) {
|
||||
if ($cc = EmailRecipients::parse($data['cc'] ?? null)) {
|
||||
$mailer->cc($cc);
|
||||
}
|
||||
if ($bcc = $this->parseRecipients($data['bcc'] ?? null)) {
|
||||
if ($bcc = EmailRecipients::parse($data['bcc'] ?? null)) {
|
||||
$mailer->bcc($bcc);
|
||||
}
|
||||
$mailer->send(new GenericTemplateMail(
|
||||
@@ -311,21 +343,38 @@ class EmailTemplateController extends Controller
|
||||
return response()->json(['error' => false, 'message' => 'Đã gửi email mẫu.']);
|
||||
}
|
||||
|
||||
private function parseRecipients(?string $value): array
|
||||
{
|
||||
if (!$value) {
|
||||
return [];
|
||||
}
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
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 syncVariables(Template $template, array $overrides): void
|
||||
{
|
||||
if ($template->format !== 'json') {
|
||||
$template->syncVariables($overrides);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
private function placeholders(Template $t): array
|
||||
{
|
||||
$declared = $t->variables();
|
||||
|
||||
return array_map(fn (string $key) => [
|
||||
'key' => $key,
|
||||
'label' => $declared[$key]['label'] ?? $key,
|
||||
'example' => $declared[$key]['example'] ?? null,
|
||||
'recipient' => array_key_exists($key, MailPlaceholders::RECIPIENT_FIELDS) || array_key_exists($key, MailGlobals::LABELS),
|
||||
], MailPlaceholders::extract($t->subject, $t->message));
|
||||
}
|
||||
|
||||
private function scenarioLabel(Template $t): ?string
|
||||
{
|
||||
$scenario = EmailScenarioRegistry::find($t->key, $t->scenario) ?? $t->scenario;
|
||||
if (!$scenario) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->scenarioLabelOverrides()[$scenario]
|
||||
?? EmailScenarioRegistry::SCENARIOS[$scenario]['label']
|
||||
?? $scenario;
|
||||
}
|
||||
|
||||
private function format(Template $t): array
|
||||
{
|
||||
@@ -335,9 +384,7 @@ class EmailTemplateController extends Controller
|
||||
'name' => $t->name,
|
||||
'scenario' => $t->scenario,
|
||||
'key' => $t->key,
|
||||
'scenario_label' => $t->scenario
|
||||
? ($this->scenarioLabelOverrides()[$t->scenario] ?? Template::SCENARIOS[$t->scenario] ?? $t->scenario)
|
||||
: null,
|
||||
'scenario_label' => $this->scenarioLabel($t),
|
||||
'format' => $t->format ?? 'html',
|
||||
'invoice_template_id' => $t->invoice_template_id,
|
||||
'invoice_template_name' => $t->invoiceTemplate?->name,
|
||||
@@ -347,6 +394,9 @@ class EmailTemplateController extends Controller
|
||||
'status' => $t->status,
|
||||
'variables' => array_values($t->variables()),
|
||||
'mail_config' => $t->mailConfig(),
|
||||
'placeholders' => $this->placeholders($t),
|
||||
...collect(EmailScenarioRegistry::describe($t->key, $t->scenario))->only(['registered', 'category', 'group', 'permissions', 'required_variables'])->all(),
|
||||
'global_variables' => collect(MailGlobals::LABELS)->map(fn ($label, $key) => ['key' => $key, 'label' => $label])->values(),
|
||||
'created_at' => $t->created_at,
|
||||
'updated_at' => $t->updated_at,
|
||||
];
|
||||
|
||||
@@ -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