# `PhoenixKit.Modules.Emails.Template`
[🔗](https://github.com/BeamLabEU/phoenix_kit_emails/blob/0.4.2/lib/phoenix_kit/modules/emails/template.ex#L1)

Email template schema for managing reusable email templates.

This module defines the structure and validations for email templates that can be
used throughout the application. Templates support variable substitution and
categorization for better organization.

## Template Variables

Templates support variable substitution using the `{{variable_name}}` syntax.
Common variables include:

- `{{email}}` - User's email address
- `{{url}}` - Action URL (magic link, confirmation, etc.)
- `{{timestamp}}` - Current timestamp
- `{{user_name}}` - User's display name

## Categories

- **system** - Core authentication and system emails (protected)
- **marketing** - Promotional and marketing communications
- **transactional** - Order confirmations, notifications, etc.
- **notification** - Event-driven notifications (new posts, comments, etc.)

## Source Modules

Templates can be tagged with a source module in the `metadata` field to track
which part of the application sends the email:

- **users** - User management (magic_link, password_reset, email_confirmation)
- **billing** - Billing module (invoices, receipts, payment notifications)
- **publishing** - Publishing module (new posts, comments)
- **entities** - Entities module (entity notifications)
- **admin** - Admin functions (test emails, manual sends)
- **custom** - Custom/user-defined emails

## Metadata Structure

The `metadata` field can contain:

    %{
      "source_module" => "users",    # Source module identifier
      "priority" => "high",           # Email priority (optional)
      "requires_user" => true         # Whether user_uuid is required (optional)
    }

## Status

- **active** - Template is live and can be used
- **draft** - Template is being edited
- **archived** - Template is no longer active but preserved

## Examples

    # Create a new template
    %EmailTemplate{}
    |> EmailTemplate.changeset(%{
      name: "welcome_email",
      slug: "welcome-email",
      display_name: "Welcome Email",
      subject: "Welcome to {{app_name}}!",
      html_body: "<h1>Welcome {{user_name}}!</h1>",
      text_body: "Welcome {{user_name}}!",
      category: "transactional",
      status: "active"
    })

# `t`

```elixir
@type t() :: %PhoenixKit.Modules.Emails.Template{
  __meta__: term(),
  category: String.t(),
  created_by_user_uuid: term(),
  description: String.t() | nil,
  display_name: String.t(),
  html_body: String.t(),
  inserted_at: DateTime.t() | nil,
  is_system: boolean(),
  last_used_at: DateTime.t() | nil,
  metadata: map(),
  name: String.t(),
  slug: String.t(),
  status: String.t(),
  subject: String.t(),
  text_body: String.t(),
  updated_at: DateTime.t() | nil,
  updated_by_user_uuid: term(),
  usage_count: integer(),
  uuid: term(),
  variables: map(),
  version: integer()
}
```

# `changeset`

Creates a changeset for email template creation and updates.

## Parameters

- `template` - The email template struct (new or existing)
- `attrs` - Map of attributes to change

## Required Fields

- `:name` - Unique template identifier
- `:slug` - URL-friendly identifier
- `:display_name` - Human-readable name
- `:subject` - Email subject line
- `:html_body` - HTML version of email
- `:text_body` - Plain text version of email

## Validations

- Name must be unique and follow snake_case format
- Slug must be unique and URL-friendly
- Category must be one of the valid categories
- Status must be one of the valid statuses
- Subject and body fields cannot be empty
- Variables must be a valid map

# `common_variables`

Returns the list of common template variables.

# `extract_variables`

Extracts variables from template content (subject, html_body, text_body).

Returns a list of unique variable names found in the template.

## Examples

    iex> template = %EmailTemplate{
    ...>   subject: "Welcome {{user_name}}!",
    ...>   html_body: "<p>Hi {{user_name}}, click {{url}}</p>",
    ...>   text_body: "Hi {{user_name}}, visit {{url}}"
    ...> }
    iex> EmailTemplate.extract_variables(template)
    ["user_name", "url"]

# `get_source_module`

Gets the source module from a template's metadata.

Returns the source_module value if present, otherwise "custom".

## Examples

    iex> template = %EmailTemplate{metadata: %{"source_module" => "auth"}}
    iex> EmailTemplate.get_source_module(template)
    "auth"

    iex> template = %EmailTemplate{metadata: %{}}
    iex> EmailTemplate.get_source_module(template)
    "custom"

# `get_translation`

Extracts a translated string from a JSON language map field.

## Parameters
- `field_map` — a map like `%{"en" => "...", "uk" => "..."}`
- `locale` — the desired locale code, e.g. `"uk"` or `"en-US"`
- `default_locale` — fallback locale, defaults to `"en"`

## Behaviour
1. Try exact match: `field_map[locale]`
2. Try base language: e.g. `"en"` from `"en-US"`
3. Try default_locale
4. Try any available value (last resort)
5. Return `""` if map is empty or nil

## Examples

    iex> get_translation(%{"en" => "Hello", "uk" => "Привіт"}, "uk")
    "Привіт"

    iex> get_translation(%{"en" => "Hello"}, "uk")
    "Hello"

    iex> get_translation(nil, "uk")
    ""

# `set_source_module`

Sets the source module in a template's metadata.

Returns updated metadata map with source_module set.

## Examples

    iex> EmailTemplate.set_source_module(%{}, "auth")
    %{"source_module" => "auth"}

# `substitute_variables`

Substitutes variables in template content with provided values.

## Parameters

- `template` - The email template
- `variables` - Map of variable names to values
- `locale` - The target locale code (default: `"en"`)

Returns a map `%{subject: string, html_body: string, text_body: string}` with
the locale-specific content and all variables substituted.

## Examples

    iex> template = %EmailTemplate{
    ...>   subject: %{"en" => "Welcome {{user_name}}!"},
    ...>   html_body: %{"en" => "<p>Hi {{user_name}}</p>"},
    ...>   text_body: %{"en" => "Hi {{user_name}}"}
    ...> }
    iex> result = EmailTemplate.substitute_variables(template, %{"user_name" => "John"}, "en")
    iex> result.subject
    "Welcome John!"

# `usage_changeset`

Creates a changeset for updating template usage statistics.

# `valid_categories`

Returns the list of valid categories for email templates.

# `valid_source_modules`

Returns the list of valid source modules for email templates.

# `valid_statuses`

Returns the list of valid statuses for email templates.

# `version_changeset`

Creates a changeset for updating template version.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
