upsert($item); } } /** * @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]; } 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(); } }