This commit is contained in:
baodev0
2026-10-05 09:30:24 +07:00
parent a1aeb88061
commit 1544629a1f
53 changed files with 1292 additions and 963 deletions
@@ -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,
];