update email template

This commit is contained in:
baodev0
2026-09-09 16:56:22 +07:00
parent d3d9f76ba0
commit 2365ef72e9
210 changed files with 6335 additions and 4688 deletions
@@ -2,12 +2,17 @@
namespace App\Http\Controllers\Api\Admin\EmailTemplate;
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 Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Validation\Rule;
class EmailTemplateController extends Controller
{
@@ -32,16 +37,39 @@ class EmailTemplateController extends Controller
return response()->json(['error' => false, 'data' => $this->format($template)]);
}
/** Danh sách scenario hợp lệ (key + label) để render dropdown động ở frontend. */
public function scenarios(): JsonResponse
{
$used = Template::whereNotNull('scenario')->pluck('scenario')->all();
$data = collect(Template::SCENARIOS)->map(fn ($label, $key) => [
'key' => $key,
'label' => $label,
'has_template' => in_array($key, $used, true),
])->values();
return response()->json(['error' => false, 'data' => $data]);
}
public function store(Request $request): JsonResponse
{
$data = $request->validate([
'name' => 'nullable|string|max:255',
'scenario' => 'nullable|string|in:vm_credentials,renewal_reminder,news_notification,invoice_pdf',
'scenario' => ['nullable', 'string', Rule::in(array_keys(Template::SCENARIOS))],
'format' => 'nullable|in:html,json',
'invoice_template_id' => 'nullable|integer|exists:template,id',
'subject' => 'nullable|string|max:255',
'message' => 'nullable|string',
'status' => 'boolean',
'mail_config' => 'nullable|array',
'mail_config.from_email' => 'nullable|email',
'mail_config.from_name' => 'nullable|string|max:255',
'mail_config.reply_to' => 'nullable|email',
'mail_config.reply_to_name' => 'nullable|string|max:255',
'mail_config.cc' => 'nullable|array',
'mail_config.cc.*' => 'email',
'mail_config.bcc' => 'nullable|array',
'mail_config.bcc.*' => 'email',
]);
$template = DB::transaction(fn() => Template::create([
@@ -53,6 +81,7 @@ class EmailTemplateController extends Controller
'subject' => $data['subject'] ?? null,
'message' => $data['message'] ?? null,
'status' => $data['status'] ?? 1,
'metadata' => isset($data['mail_config']) ? ['mail' => $data['mail_config']] : null,
]));
return response()->json([
@@ -67,14 +96,31 @@ class EmailTemplateController extends Controller
$data = $request->validate([
'name' => 'sometimes|nullable|string|max:255',
'scenario' => 'sometimes|nullable|string|in:vm_credentials,renewal_reminder,news_notification,invoice_pdf',
'scenario' => ['sometimes', 'nullable', 'string', Rule::in(array_keys(Template::SCENARIOS))],
'format' => 'sometimes|nullable|in:html,json',
'invoice_template_id' => 'sometimes|nullable|integer|exists:template,id',
'subject' => 'sometimes|nullable|string|max:255',
'message' => 'sometimes|nullable|string',
'status' => 'sometimes|boolean',
'mail_config' => 'sometimes|nullable|array',
'mail_config.from_email' => 'nullable|email',
'mail_config.from_name' => 'nullable|string|max:255',
'mail_config.reply_to' => 'nullable|email',
'mail_config.reply_to_name' => 'nullable|string|max:255',
'mail_config.cc' => 'nullable|array',
'mail_config.cc.*' => 'email',
'mail_config.bcc' => 'nullable|array',
'mail_config.bcc.*' => 'email',
]);
// 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']);
DB::transaction(fn() => $template->update($data));
return response()->json([
@@ -122,6 +168,106 @@ class EmailTemplateController extends Controller
return response()->json(['error' => false, 'message' => 'Đã lưu cài đặt email.', 'data' => json_decode($setting->value, true)]);
}
// ── Preview (render thật qua EmailTemplateRenderer, dùng example value) ────
public function preview(Request $request, int $id, EmailTemplateRenderer $renderer): JsonResponse
{
$template = Template::findOrFail($id);
if ($template->format === 'json') {
return response()->json(['error' => true, 'message' => 'Template hoá đơn JSON dùng preview riêng (previewInvoiceJson).'], 422);
}
$overrides = $request->validate([
'subject' => 'nullable|string|max:255',
'message' => 'nullable|string',
]);
// 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'];
}
if (array_key_exists('message', $overrides)) {
$draft->message = $overrides['message'];
}
$exampleData = collect($template->variables())
->mapWithKeys(fn ($def, $key) => [$key => $def['example'] ?? "[{$key}]"])
->all();
try {
$rendered = $renderer->render($draft, $exampleData);
} catch (InvalidTemplateVariableException $e) {
return response()->json(['error' => true, 'message' => $e->getMessage()], 422);
}
return response()->json(['error' => false, 'data' => $rendered]);
}
// ── Send test email ───────────────────────────────────────────────────────
public function sendTest(Request $request, int $id, EmailTemplateRenderer $renderer): JsonResponse
{
$template = Template::findOrFail($id);
if ($template->format === 'json') {
return response()->json(['error' => true, 'message' => 'Không thể gửi mẫu cho template JSON (hoá đơn).'], 422);
}
$data = $request->validate([
'to' => 'required|string',
'cc' => 'nullable|string',
'bcc' => 'nullable|string',
]);
$to = $this->parseRecipients($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}]"])
->all();
try {
$rendered = $renderer->render($template, $exampleData);
$mailer = Mail::to($to);
if ($cc = $this->parseRecipients($data['cc'] ?? null)) {
$mailer->cc($cc);
}
if ($bcc = $this->parseRecipients($data['bcc'] ?? null)) {
$mailer->bcc($bcc);
}
$mailer->send(new GenericTemplateMail(
'[TEST] ' . $rendered['subject'],
$rendered['html'],
$template->mailConfig(),
));
} catch (InvalidTemplateVariableException $e) {
return response()->json(['error' => true, 'message' => $e->getMessage()], 422);
} catch (\Throwable $e) {
return response()->json(['error' => true, 'message' => 'Không thể gửi email: ' . $e->getMessage()], 500);
}
return response()->json(['error' => false, 'message' => 'Đã gửi email mẫu.']);
}
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();
}
// ── Invoice PDF preview ───────────────────────────────────────────────────
public function previewInvoiceJson(int $id): JsonResponse
@@ -154,6 +300,8 @@ class EmailTemplateController extends Controller
'subject' => $t->subject,
'message' => $t->message,
'status' => $t->status,
'variables' => array_values($t->variables()),
'mail_config' => $t->mailConfig(),
'created_at' => $t->created_at,
'updated_at' => $t->updated_at,
];