405 lines
17 KiB
PHP
405 lines
17 KiB
PHP
<?php
|
|
|
|
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;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Facades\Mail;
|
|
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
|
|
{
|
|
$query = Template::with('invoiceTemplate:id,name,scenario')
|
|
->orderBy('scenario')
|
|
->orderBy('id');
|
|
|
|
if ($request->filled('scenario')) {
|
|
$query->where('scenario', $request->scenario);
|
|
}
|
|
|
|
$templates = $query->get()->map(fn($t) => $this->format($t));
|
|
|
|
return response()->json(['error' => false, 'data' => $templates]);
|
|
}
|
|
|
|
public function show(int $id): JsonResponse
|
|
{
|
|
$template = Template::with('invoiceTemplate:id,name,scenario')->findOrFail($id);
|
|
return response()->json(['error' => false, 'data' => $this->format($template)]);
|
|
}
|
|
|
|
public function scenarios(): JsonResponse
|
|
{
|
|
$templates = Template::query()->get(['key', 'scenario', 'status']);
|
|
$labels = $this->scenarioLabelOverrides();
|
|
|
|
$registered = collect(EmailScenarioRegistry::SCENARIOS)->map(function ($definition, $key) use ($templates, $labels) {
|
|
$matches = $templates->filter(fn ($t) => $t->key === $key || $t->scenario === $key);
|
|
|
|
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),
|
|
];
|
|
});
|
|
|
|
$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 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.
|
|
*/
|
|
public function updateScenarioLabel(Request $request, string $key): JsonResponse
|
|
{
|
|
$data = $request->validate([
|
|
'label' => 'required|string|max:255',
|
|
]);
|
|
|
|
$setting = Setting::firstOrNew(['key' => 'scenario_labels']);
|
|
$labels = $setting->value ? json_decode($setting->value, true) : [];
|
|
$labels[$key] = trim($data['label']);
|
|
$setting->value = json_encode($labels, JSON_UNESCAPED_UNICODE);
|
|
$setting->save();
|
|
|
|
return response()->json(['error' => false, 'message' => 'Đã đổi tên tình huống.', 'data' => ['key' => $key, 'label' => $labels[$key]]]);
|
|
}
|
|
|
|
private function scenarioLabelOverrides(): array
|
|
{
|
|
if ($this->scenarioLabelOverridesCache !== null) {
|
|
return $this->scenarioLabelOverridesCache;
|
|
}
|
|
|
|
$setting = Setting::where('key', 'scenario_labels')->first();
|
|
return $this->scenarioLabelOverridesCache = $setting && $setting->value
|
|
? (json_decode($setting->value, true) ?: [])
|
|
: [];
|
|
}
|
|
|
|
public function store(Request $request, TemplateGuard $guard): JsonResponse
|
|
{
|
|
$data = $request->validate([
|
|
'name' => 'nullable|string|max:255',
|
|
'scenario' => ['nullable', 'string', 'max:100', 'regex:/^[a-z][a-z0-9_]*$/'],
|
|
'key' => ['nullable', 'string', 'max:100', 'regex:/^[a-z][a-z0-9_]*$/', 'unique:template,key'],
|
|
'format' => 'nullable|in:html,json',
|
|
'invoice_template_id' => 'nullable|integer|exists:template,id',
|
|
'subject' => 'nullable|string|max:255',
|
|
'message' => 'nullable|string',
|
|
'builder_data' => 'nullable|array',
|
|
'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',
|
|
...self::VARIABLE_RULES,
|
|
]);
|
|
|
|
$template = new Template([
|
|
'type_id' => 0,
|
|
'name' => $data['name'] ?? null,
|
|
'scenario' => $data['scenario'] ?? null,
|
|
'key' => $data['key'] ?? null,
|
|
'format' => $data['format'] ?? 'html',
|
|
'invoice_template_id' => $data['invoice_template_id'] ?? null,
|
|
'subject' => $data['subject'] ?? null,
|
|
'message' => $data['message'] ?? null,
|
|
'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.',
|
|
'data' => $this->format($template),
|
|
], 201);
|
|
}
|
|
|
|
public function update(Request $request, int $id, TemplateGuard $guard): JsonResponse
|
|
{
|
|
$template = Template::findOrFail($id);
|
|
|
|
$data = $request->validate([
|
|
'name' => 'sometimes|nullable|string|max:255',
|
|
'scenario' => ['sometimes', 'nullable', 'string', 'max:100', 'regex:/^[a-z][a-z0-9_]*$/'],
|
|
'key' => ['sometimes', 'nullable', 'string', 'max:100', 'regex:/^[a-z][a-z0-9_]*$/', Rule::unique('template', 'key')->ignore($template->id)],
|
|
'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',
|
|
'builder_data' => 'sometimes|nullable|array',
|
|
'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',
|
|
...self::VARIABLE_RULES,
|
|
]);
|
|
|
|
if (array_key_exists('mail_config', $data)) {
|
|
$metadata = $template->metadata ?? [];
|
|
$metadata['mail'] = $data['mail_config'] ?? [];
|
|
$data['metadata'] = $metadata;
|
|
}
|
|
$variables = $data['variables'] ?? [];
|
|
unset($data['mail_config'], $data['variables']);
|
|
|
|
$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.',
|
|
'data' => $this->format($template->fresh(['invoiceTemplate'])),
|
|
]);
|
|
}
|
|
|
|
public function destroy(int $id, TemplateGuard $guard): JsonResponse
|
|
{
|
|
$template = Template::findOrFail($id);
|
|
$guard->assertCanDelete($template);
|
|
DB::transaction(fn () => $template->delete());
|
|
return response()->json(['error' => false, 'message' => 'Đã xoá template.']);
|
|
}
|
|
|
|
// ── Email settings (scenario assignments) ─────────────────────────────────
|
|
|
|
public function getEmailSettings(): JsonResponse
|
|
{
|
|
$setting = Setting::where('key', 'email_settings')->first();
|
|
$value = $setting ? json_decode($setting->value, true) : [];
|
|
|
|
// Ensure mail_enabled defaults to true when not set
|
|
if (!isset($value['mail_enabled'])) {
|
|
$value['mail_enabled'] = true;
|
|
}
|
|
|
|
return response()->json(['error' => false, 'data' => $value]);
|
|
}
|
|
|
|
public function updateEmailSettings(Request $request): JsonResponse
|
|
{
|
|
$data = $request->validate([
|
|
'vm_template_id' => 'nullable|integer|exists:template,id',
|
|
'renewal_template_id' => 'nullable|integer|exists:template,id',
|
|
'news_template_id' => 'nullable|integer|exists:template,id',
|
|
'invoice_template_id' => 'nullable|integer|exists:template,id',
|
|
'mail_enabled' => 'sometimes|boolean',
|
|
]);
|
|
|
|
$setting = Setting::firstOrNew(['key' => 'email_settings']);
|
|
$current = $setting->value ? json_decode($setting->value, true) : [];
|
|
$setting->value = json_encode(array_merge($current, $data));
|
|
$setting->save();
|
|
|
|
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',
|
|
...self::VARIABLE_RULES,
|
|
]);
|
|
|
|
$draft = clone $template;
|
|
if (array_key_exists('subject', $overrides)) {
|
|
$draft->subject = $overrides['subject'];
|
|
}
|
|
if (array_key_exists('message', $overrides)) {
|
|
$draft->message = $overrides['message'];
|
|
}
|
|
$draft->syncVariables($overrides['variables'] ?? []);
|
|
|
|
$exampleData = collect($draft->variables())
|
|
->mapWithKeys(fn ($def, $key) => [$key => $def['example'] ?? "[{$key}]"])
|
|
->merge(MailGlobals::values())
|
|
->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 = 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 = EmailRecipients::parse($data['cc'] ?? null)) {
|
|
$mailer->cc($cc);
|
|
}
|
|
if ($bcc = EmailRecipients::parse($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) {
|
|
Log::error('Gửi email test thất bại', [
|
|
'template_id' => $id,
|
|
'to' => $data['to'],
|
|
'exception' => $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.']);
|
|
}
|
|
|
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
|
|
private function syncVariables(Template $template, array $overrides): void
|
|
{
|
|
if ($template->format !== 'json') {
|
|
$template->syncVariables($overrides);
|
|
}
|
|
}
|
|
|
|
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
|
|
{
|
|
return [
|
|
'id' => $t->id,
|
|
'type_id' => $t->type_id,
|
|
'name' => $t->name,
|
|
'scenario' => $t->scenario,
|
|
'key' => $t->key,
|
|
'scenario_label' => $this->scenarioLabel($t),
|
|
'format' => $t->format ?? 'html',
|
|
'invoice_template_id' => $t->invoice_template_id,
|
|
'invoice_template_name' => $t->invoiceTemplate?->name,
|
|
'subject' => $t->subject,
|
|
'message' => $t->message,
|
|
'builder_data' => $t->builder_data,
|
|
'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,
|
|
];
|
|
}
|
|
}
|