dev update

This commit is contained in:
baodev0
2026-09-10 16:32:48 +07:00
parent 2365ef72e9
commit cd38c5d6d0
15 changed files with 483 additions and 191 deletions
@@ -16,6 +16,8 @@ use Illuminate\Validation\Rule;
class EmailTemplateController extends Controller
{
private ?array $scenarioLabelOverridesCache = null;
public function index(Request $request): JsonResponse
{
$query = Template::with('invoiceTemplate:id,name,scenario')
@@ -37,25 +39,68 @@ 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. */
/**
* 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')->pluck('scenario')->all();
$used = Template::whereNotNull('scenario')->distinct()->pluck('scenario')->all();
$labels = $this->scenarioLabelOverrides();
$data = collect(Template::SCENARIOS)->map(fn ($label, $key) => [
'key' => $key,
'label' => $label,
$known = collect(Template::SCENARIOS)->map(fn ($label, $key) => [
'key' => $key,
'label' => $labels[$key] ?? $label,
'has_template' => in_array($key, $used, true),
])->values();
]);
return response()->json(['error' => false, 'data' => $data]);
$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 response()->json(['error' => false, 'data' => $known->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
* (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): JsonResponse
{
$data = $request->validate([
'name' => 'nullable|string|max:255',
'scenario' => ['nullable', 'string', Rule::in(array_keys(Template::SCENARIOS))],
'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',
@@ -76,6 +121,7 @@ class EmailTemplateController extends Controller
'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,
@@ -96,7 +142,8 @@ class EmailTemplateController extends Controller
$data = $request->validate([
'name' => 'sometimes|nullable|string|max:255',
'scenario' => ['sometimes', 'nullable', 'string', Rule::in(array_keys(Template::SCENARIOS))],
'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',
@@ -293,7 +340,10 @@ class EmailTemplateController extends Controller
'type_id' => $t->type_id,
'name' => $t->name,
'scenario' => $t->scenario,
'scenario_label' => Template::SCENARIOS[$t->scenario] ?? null,
'key' => $t->key,
'scenario_label' => $t->scenario
? ($this->scenarioLabelOverrides()[$t->scenario] ?? Template::SCENARIOS[$t->scenario] ?? $t->scenario)
: null,
'format' => $t->format ?? 'html',
'invoice_template_id' => $t->invoice_template_id,
'invoice_template_name' => $t->invoiceTemplate?->name,
@@ -106,10 +106,7 @@ final class MailCampaignController extends Controller
private function renderPreview(string $subject, string $message): string
{
return view('emails.customer.template-camp', [
'content' => $message,
'emailSubject' => $subject,
])->render();
return Template::renderWithLayout($subject, $message);
}
public function store(Request $request): JsonResponse
+2 -2
View File
@@ -2,6 +2,7 @@
namespace App\Mail\Customer;
use App\Models\Template;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
@@ -26,8 +27,7 @@ class ManualCustomerEmail extends Mailable implements ShouldQueue
public function content(): Content
{
return new Content(
view: 'emails.customer.template-camp',
with: ['content' => $this->htmlContent, 'emailSubject' => $this->emailSubject],
html: Template::renderWithLayout($this->emailSubject, $this->htmlContent),
);
}
+29
View File
@@ -17,6 +17,7 @@ class Template extends Model
protected $fillable = [
'type_id',
'scenario',
'key',
'format',
'invoice_template_id',
'name',
@@ -44,6 +45,9 @@ class Template extends Model
if ($this->scenario) {
Cache::forget(self::CACHE_PREFIX . $this->scenario);
}
if ($this->key) {
Cache::forget(self::CACHE_PREFIX . $this->key);
}
}
/** Danh sách variable hợp lệ khai báo trong metadata.variables, key theo variable key. */
@@ -59,6 +63,7 @@ class Template extends Model
}
public const SCENARIOS = [
'layout' => 'Bố cục Header/Footer (mặc định)',
'vm_credentials' => 'Khởi tạo dịch vụ',
'renewal_reminder' => 'Nhắc gia hạn',
'news_notification' => 'Thông báo tin tức',
@@ -102,6 +107,30 @@ class Template extends Model
return $this->belongsTo(self::class, 'invoice_template_id');
}
/**
* Wrap $contentHtml with the admin-editable "layout" template (scenario=layout),
* replacing its {{$content}} placeholder. Falls back to the static blade
* template-camp wrapper when no active layout template is configured.
*/
public static function renderWithLayout(?string $subject, string $contentHtml): string
{
$layout = self::where('scenario', 'layout')->where('status', 1)->first();
if (!$layout || !$layout->message) {
return view('emails.customer.template-camp', [
'content' => $contentHtml,
'emailSubject' => $subject,
])->render();
}
$body = str_replace('{{$content}}', $contentHtml, $layout->message);
return view('emails.customer.template-envelope', [
'body' => $body,
'emailSubject' => $subject,
])->render();
}
public function type()
{
return $this->belongsTo(\App\Models\Type::class);
+9 -3
View File
@@ -34,12 +34,18 @@ class EmailTemplateService
return $this->renderer->render($this->loadTemplate($scenario), $data);
}
public function loadTemplate(string $scenario): Template
/**
* Tìm template theo `key` (định danh riêng, ưu tiên) hoặc `scenario`
* (tương thích ngược với các lời gọi cũ truyền scenario làm định danh).
*/
public function loadTemplate(string $key): Template
{
return Cache::remember(
Template::CACHE_PREFIX . $scenario,
Template::CACHE_PREFIX . $key,
3600,
fn () => Template::where('scenario', $scenario)->where('status', 1)->firstOrFail(),
fn () => Template::where('status', 1)
->where(fn ($q) => $q->where('key', $key)->orWhere('scenario', $key))
->firstOrFail(),
);
}
}