upsert($item); } foreach (MarketingTemplates::all() as $item) { $this->createMarketingIfMissing($item); } } public function seedScenarioIfMissing(string $scenario): void { if (Template::query()->where('key', $scenario)->orWhere('scenario', $scenario)->exists()) { return; } foreach (self::templates() as $item) { if ($item['scenario'] === $scenario) { $this->upsert($item); } } } private function createMarketingIfMissing(array $item): void { $template = Template::firstOrNew(['name' => $item['name']]); if ($template->exists) { return; } $template->fill([ 'type_id' => 0, 'format' => 'html', 'subject' => $item['subject'], 'message' => EmailTemplateShell::page($item['body']), 'status' => 1, ]); $template->syncVariables($item['variables']); $template->save(); } /** * @return array}> */ public static function templates(): array { $layout = [ 'scenario' => 'layout', 'name' => 'Bố cục Header/Footer (mặc định)', 'subject' => '', 'message' => EmailTemplateShell::page('{{$content}}'), ]; $scenarios = array_map( fn (array $item) => [...$item, 'message' => EmailTemplateShell::page($item['body'])], [ ...AccountTemplates::all(), ...ServiceTemplates::all(), ...BillingTemplates::all(), ...AdminTemplates::all(), ], ); return [$layout, ...$scenarios]; } /** * @return array */ public static function legacyTemplates(): array { return array_map( fn (array $item) => [...$item, 'message' => EmailTemplateShell::page($item['body'])], LegacyTemplates::all(), ); } private function upsert(array $item): void { $scenario = $item['scenario']; $template = Template::query() ->where(fn ($q) => $q->where('key', $scenario)->orWhere('scenario', $scenario)) ->orderByRaw('`key` = ? desc', [$scenario]) ->orderBy('id') ->first() ?? new Template(['type_id' => 0, 'status' => 1]); $template->fill([ 'key' => $scenario, 'scenario' => $scenario, 'name' => $item['name'], 'subject' => $item['subject'], 'message' => $item['message'], 'format' => 'html', ]); $template->metadata = [ ...($template->metadata ?? []), 'variables' => $this->variables($template, $item['types'] ?? []), ]; $template->save(); } /** * @param array $typeOverrides * @return array */ private function variables(Template $template, array $typeOverrides): array { $existing = $template->variables(); return collect(MailPlaceholders::extract($template->subject, $template->message)) ->map(function (string $key) use ($existing, $typeOverrides) { [$label, $type, $example] = TemplateVariables::DEFINITIONS[$key] ?? [$key, 'string', '']; return [ 'key' => $key, 'label' => $existing[$key]['label'] ?? $label, 'type' => $typeOverrides[$key] ?? $type, 'example' => $existing[$key]['example'] ?? $example, ]; }) ->values() ->all(); } }