# Notifications

## Table of Contents

- [Introduction](#introduction)
- [List Notifications](#list-notifications)
- [Unread Count](#unread-count)
- [Mark as Read](#mark-as-read)
- [Mark All as Read](#mark-all-as-read)
- [Delete a Notification](#delete-a-notification)
- [Send a Push Test](#send-a-push-test)
- [Notification Preferences](#notification-preferences)
  - [Get Preference Matrix](#get-preference-matrix)
  - [Update Preferences](#update-preferences)
- [HasNotifications Trait](#hasnotifications-trait)
  - [prefers()](#prefers)
  - [routeNotificationForOneSignal()](#routenotificationforonesignal)
- [OneSignal Push Channel (v5 SDK)](#onesignal-push-channel)
- [NotificationSetting Model](#notificationsetting-model)
- [Channel Gating via GateNotificationChannels](#channel-gating-via-gatenotificationchannels)
- [NotificationPreferenceRegistry](#notificationpreferenceregistry)
- [Mail Branding](#mail-branding)

---

## <a name="introduction"></a>Introduction

The notifications module is feature-gated behind `Features::notifications()`. All routes described below are only registered when that feature is enabled.

```php
// config/magic-starter.php
'features' => [
    Features::notifications(),
],
```

The module provides two distinct concerns:

1. **Database notification management** - read, mark, and delete Laravel database notifications via `NotificationController`.
2. **Notification preference management** - per-type, per-channel opt-in/opt-out matrix via `NotificationPreferenceController`.

All routes require an authenticated user (Sanctum `auth:sanctum` middleware is applied at the route group level by `MagicStarterServiceProvider`).

---

## <a name="list-notifications"></a>List Notifications

**`GET /notifications`**

Returns a paginated list of all database notifications for the authenticated user, ordered by `created_at` descending (Laravel default).

### Query Parameters

| Parameter  | Type    | Default | Description                        |
|------------|---------|---------|------------------------------------|
| `per_page` | integer | `15`    | Number of notifications per page.  |

### Response

```json
{
    "data": [
        {
            "id": "uuid",
            "type": "App\\Notifications\\OrderShipped",
            "notifiable_type": "App\\Models\\User",
            "notifiable_id": "uuid",
            "data": { },
            "read_at": null,
            "created_at": "2025-01-01T00:00:00.000000Z",
            "updated_at": "2025-01-01T00:00:00.000000Z"
        }
    ],
    "links": { },
    "meta": { }
}
```

The response shape follows Laravel's `AnonymousResourceCollection` with standard pagination links and meta. The `data` field inside each notification item is application-defined.

> [!NOTE]
> The controller delegates to `$request->user()->notifications()->paginate($perPage)`. The `notifications()` relation is provided by Laravel's `Notifiable` trait - ensure your User model uses it.

**Controller**: `NotificationController@index`

---

## <a name="unread-count"></a>Unread Count

**`GET /notifications/unread-count`**

Returns the number of unread notifications for the authenticated user.

### Response

```json
{
    "data": {
        "count": 3
    }
}
```

**Controller**: `NotificationController@unreadCount`

---

## <a name="mark-as-read"></a>Mark as Read

**`POST /notifications/{id}/read`**

Marks a single notification as read by setting `read_at` to the current timestamp.

### Path Parameters

| Parameter | Type   | Description                             |
|-----------|--------|-----------------------------------------|
| `id`      | string | The UUID of the notification to mark.   |

The notification is scoped to the authenticated user - attempting to mark another user's notification returns `404`.

### Response

```json
{
    "data": null,
    "message": "Notification marked as read."
}
```

**Controller**: `NotificationController@markAsRead`

---

## <a name="mark-all-as-read"></a>Mark All as Read

**`POST /notifications/read-all`**

Bulk-updates all unread notifications for the authenticated user by setting `read_at = now()` in a single query.

### Response

```json
{
    "data": null,
    "message": "All notifications marked as read."
}
```

**Controller**: `NotificationController@markAllAsRead`

---

## <a name="delete-a-notification"></a>Delete a Notification

**`DELETE /notifications/{id}`**

Permanently deletes a single notification. The notification is scoped to the authenticated user - attempting to delete another user's notification returns `404`.

### Path Parameters

| Parameter | Type   | Description                          |
|-----------|--------|--------------------------------------|
| `id`      | string | The UUID of the notification to delete. |

### Response

```json
{
    "data": null,
    "message": "Notification deleted."
}
```

**Controller**: `NotificationController@destroy`

---

## <a name="send-a-push-test"></a>Send a Push Test

**`POST /notifications/push-test`**

Sends the authenticated caller a push notification, to their own devices, so a
person can find out whether push actually reaches the phone in their hand. On an
on-call product that is a question worth answering before an incident rather
than during one.

**This endpoint ships switched off.** Set
`magic-starter.onesignal.self_test_enabled` (env
`MAGIC_STARTER_PUSH_SELF_TEST_ENABLED`) to enable it. An absent key reads as off,
because `mergeConfigFrom` is shallow and an upgrade that adds a key to the
package default does not add it to a config a consumer already published.

### Request

```json
{
    "title": "Uptizm",
    "body": "Push is working on this device.",
    "data": { "type": "push_test" }
}
```

| Field | Rules |
|---|---|
| `title` | required, string, max 120 |
| `body` | required, string, max 500 |
| `data` | sometimes, array |

**The body carries no recipient, and adding one is a breaking change to the
endpoint's safety property rather than a feature.** The target is derived from
the Sanctum session, so the worst a caller can do is page themselves. The server
also stamps `data.subject` with `user_<id>` over whatever the client sent, so a
caller cannot make a push aimed at their own device claim to be somebody else's.

### Response

```json
{
    "accepted": true
}
```

`accepted`, not `delivered`: a zero-recipient send is an HTTP 200 from OneSignal
with an empty notification id, which the channel reports without throwing. A
caller with no registered device is exactly who this endpoint is for, and
telling them it was delivered would send them looking in the wrong place.

| Status | Meaning |
|---|---|
| `202` | Accepted and dispatched |
| `501` | `self_test_enabled` is off on this server |
| `403` | The caller is a guest user |
| `409` | OneSignal is not provisioned (no `app_id`, or the feature is off) |
| `422` | Validation failed on `title`, `body` or `data` |
| `502` | The push provider could not be reached |
| `429` | Rate limited (5 per minute, per user) |

The 403 is worth reading twice if guest authentication is on: that feature hands
a Sanctum token to anybody who asks, so without this guard the endpoint would be
an anonymously reachable way to spend an operator's OneSignal quota.

The 501 check runs before every other guard: 403 would say the caller may not,
which is untrue of an operator who has simply not switched this on; 409 names a
different and independently fixable state; and 404 would hide that the route
exists at all from a client that can read the package's own config.

**Controller**: `PushTestController@store`

---

## <a name="notification-preferences"></a>Notification Preferences

Notification preferences allow users to opt in or out of specific notification types on specific channels. The available types and channels are declared at boot time via `NotificationPreferenceRegistry::register()`.

### <a name="get-preference-matrix"></a>Get Preference Matrix

**`GET /notification-preferences`**

Returns the full type × channel matrix for the authenticated user. Each entry reflects the effective preference - either the stored DB override or the registry default.

### Response

```json
{
    "data": {
        "order_shipped": {
            "label": "Order Shipped",
            "channels": {
                "push": { "enabled": true, "locked": false },
                "email": { "enabled": false, "locked": true }
            }
        }
    }
}
```

- `enabled` - whether the user currently has this channel on for this type.
- `locked` - whether the channel cannot be changed (the registry defined it as locked). Locked channels should be rendered as non-interactive in the UI.

**Controller**: `NotificationPreferenceController@show`

---

### <a name="update-preferences"></a>Update Preferences

**`PUT /notification-preferences`**

Supports two payload shapes: single and bulk.

#### Single update

```json
{
    "type": "order_shipped",
    "channel": "push",
    "is_enabled": false
}
```

#### Bulk update

```json
{
    "preferences": [
        { "type": "order_shipped", "channel": "push", "is_enabled": false },
        { "type": "order_shipped", "channel": "sms",  "is_enabled": true  }
    ]
}
```

The presence of the `preferences` key determines which path is taken. Each item is validated and then upserted into `notification_settings` via `NotificationSetting::updateOrCreate()`.

#### Validation rules

| Field         | Rule                                                         |
|---------------|--------------------------------------------------------------|
| `type`        | Must be registered in `NotificationPreferenceRegistry`.     |
| `channel`     | Must be a channel declared for the given type.              |
| `channel`     | Must not be a locked channel for the given type.            |
| `is_enabled`  | Required boolean.                                           |

Attempting to update a locked channel returns a `422` with an error message such as:

```
The channel 'email' is locked for type 'order_shipped' and cannot be changed.
```

### Response

Returns the updated preference matrix in the same shape as `GET /notification-preferences`.

**Controller**: `NotificationPreferenceController@update`

> [!NOTE]
> The `type` value in the request payload must match either the notification class FQCN or its resolved slug (e.g., `order_shipped` for `App\Notifications\OrderShippedNotification`). The DB always stores slugs.

---

## <a name="hasnotifications-trait"></a>HasNotifications Trait

`FlutterSdk\MagicStarter\Traits\HasNotifications`

Add to your User model to unlock notification preference management and push routing:

```php
use FlutterSdk\MagicStarter\Traits\HasNotifications;

class User extends Authenticatable
{
    use HasNotifications;
}
```

The trait provides two public methods and one relation.

### Relation: `notificationSettings()`

```php
public function notificationSettings(): MorphMany<NotificationSetting, $this>
```

Polymorphic relation returning all stored preference overrides for the user. Loaded eagerly by `NotificationPreferenceController` before building the matrix.

---

### <a name="prefers"></a>`prefers(string $type, string $channel): bool`

Determines whether the user wants to receive a given notification type on a given channel. Resolution order:

1. If `$type` is not registered in `NotificationPreferenceRegistry` → **return `true`** (allow by default).
2. Check `notificationSettings` collection for a stored override matching `$type` + `$channel` → return `$override->is_enabled`.
3. If no override exists → check whether `$channel` is in the type's `default` channels list and return accordingly.

This method is called by `GateNotificationChannels` during the `NotificationSending` event.

> [!NOTE]
> `prefers()` returns `true` for any type not in the registry. This means unregistered notification classes are always delivered, regardless of any stored settings.

---

### <a name="routenotificationforonesignal"></a>`routeNotificationForOneSignal(): array`

```php
public function routeNotificationForOneSignal(): array
{
    return [
        'external_id' => [MagicStarter::onesignalExternalIdPrefix() . $this->getKey()],
    ];
}
```

Returns the routing payload for the OneSignal v5 notification channel using alias-based targeting. The `external_id` key maps to an array of alias identifiers that will be passed to the OneSignal SDK's `setIncludeAliases()` method by the package's `FlutterSdk\MagicStarter\Notifications\Channels\OneSignalChannel` driver.

A prefix is **required** because OneSignal rejects bare numeric strings like `'0'`, `'1'`, or `'-1'` as external IDs, and because the id has to match the one the Flutter client registered. The client composes its own from `magic_starter.notifications.external_id_prefix`, which defaults to the same `user_`, so the two agree out of the box.

Change it in one place, on both sides:

```php
// config/magic-starter.php
'onesignal' => [
    'external_id_prefix' => env('MAGIC_STARTER_EXTERNAL_ID_PREFIX', 'user_'),
],
```

```dart
// lib/config/magic_starter.dart
'notifications': {'external_id_prefix': 'user_'},
```

> [!WARNING]
> A mismatch between the two is silent. OneSignal accepts a send to an alias no device carries, reports success, and delivers it to nobody; the only trace is a zero-recipient response on the server. The same config value also backs the channel's fallback for a notifiable that does NOT use this trait, which is worth knowing because `MagicStarter::userModel()` auto-detects a published `App\Models\User` and one that forgot the trait still gets a correctly prefixed id.

To use a different shape entirely, rather than a different prefix, override the method:

```php
public function routeNotificationForOneSignal(): array
{
    return [
        'external_id' => ['app_user_' . $this->uuid],
    ];
}
```

---

## <a name="onesignal-push-channel"></a>OneSignal Push Channel (v5 SDK)

The package ships `FlutterSdk\MagicStarter\Notifications\Channels\OneSignalChannel`, a Laravel notification channel driver backed by the official `onesignal/onesignal-php-api: ^5.3` SDK.

### Configuration

Enable the feature by adding to your application:

```php
// config/magic-starter.php
'features' => [
    Features::onesignal(),
],
```

When enabled, the service provider automatically registers the `onesignal` driver on Laravel's `ChannelManager` and registers the logical alias `push => onesignal` in `NotificationPreferenceRegistry`.

Required configuration keys under `magic-starter.onesignal`:

| Key | Type | Description |
|-----|------|-------------|
| `app_id` | string | OneSignal Application ID |
| `rest_api_key` | string | OneSignal REST API key. Falls back to `services.onesignal.rest_api_key` if not set. |
| `target_channel` | string | Default notification channel. Defaults to `'push'`. |
| `web_origin` | string\|null | Where the Flutter web client is served, e.g. `https://app.example.com` (`MAGIC_STARTER_WEB_ORIGIN`). Optional; see below. |

#### `web_origin`, and why a web push needs it

Set it and a push carrying a deep link opens the right SCREEN in a browser. Leave it absent and web recipients land on the home page, which is the behaviour before this key existed.

A browser reads `web_url` and nothing else. The mobile clients navigate from the notification's custom `data` and the web one cannot: a click is handled by the service worker rather than by the page, so it opens the launch url as an ordinary page load and no Dart is running yet to read `additionalData`. OneSignal supplies the dashboard's Site URL when the payload names no url, which is why the symptom is the home page in a new tab rather than an error, even with the app already open in another.

`OneSignalChannel` therefore joins this origin to the deep link the notification already carries, reading `url`, `deep_link`, `link`, `uri` in that order to match the Flutter client's own lookup. So a notification class keeps returning a relative path and nothing composes an absolute url per notification.

It leaves the payload alone in three cases: when the builder set `web_url` or the top-level `url` itself (the SDK documents `url` as "Omit if including web_url or app_url"), when no origin is configured, and when the deep link is not a rooted path. No origin is guessed, because `APP_URL` on an API-only deployment is the API host and would send every web recipient where the client is not served.

### Notification Contract

Any notification class that sends via OneSignal must implement the `toOneSignal()` method:

```php
use \onesignal\client\model\Notification;

public function toOneSignal(mixed $notifiable): Notification
{
    return new Notification(
        app_id: config('magic-starter.onesignal.app_id'),
    )
        ->setHeadings(
            new \onesignal\client\model\LanguageStringMap(
                'en' => 'Order Update'
            )
        )
        ->setContents(
            new \onesignal\client\model\LanguageStringMap(
                'en' => 'Your order #12345 has shipped.'
            )
        );
}
```

The driver handles the remaining setup:

- **`app_id`** is always overridden from `config('magic-starter.onesignal.app_id')`.
- **Aliases** and **`target_channel`** from the notifiable's `routeNotificationForOneSignal()` are applied only when the notification payload has none set. This allows per-notification customization while preserving sensible defaults.

The channel passes the `Notification` instance directly to the OneSignal SDK for delivery.

### SMS subscriptions

OneSignal delivers an SMS only to a user that carries a registered SMS subscription, and it fans the send out to every SMS subscription the user has. The package registers that subscription lazily, at send time, so the notification's SMS builder calls `ensureSmsSubscription()` before it builds the payload:

```php
public function toSms(mixed $notifiable): OneSignalNotification
{
    app(OneSignalSubscriptions::class)->ensureSmsSubscription($notifiable);

    // ... build the sms-targeted payload
}
```

The reconcile runs in this order:

1. `getUser` reads what OneSignal holds. A 404 means OneSignal has never seen the user, and counts as no subscriptions.
2. Every enabled SMS subscription whose token is not the current phone is deleted. A disabled one is left alone.
3. `createUser` (an upsert) registers the current phone with the user's two-letter language, only when no SMS subscription carries it yet.

`users.sms_registered_at` is set only after all three steps succeed. A failure is reported, `ensureSmsSubscription()` returns `false`, and the next send retries. The phone number never appears in an exception message or a log line.

When the phone changes, the `HasNotifications` trait clears `sms_registered_at` on save, so the next SMS send reconciles again and the old number is removed in step 2. The reset also runs for a model loaded without that column, and is skipped when the `users` table has no `sms_registered_at` column, so an app that has not published it is unaffected. Phones are compared and sent with spaces, dashes, dots and brackets stripped, so `+1 (555) 123-4567` and `+15551234567` are the same number.

Two queued jobs keep OneSignal in step with the account. Both need a queue worker, and both do nothing unless OneSignal is provisioned (an app id and a REST key):

- `PruneSmsSubscriptions` runs after a phone change commits and deletes every enabled SMS subscription whose token is not the current phone. Clearing the phone removes them all. The job reads the current phone when it runs, carries the model rather than the number, and is dropped when the user is gone. It has 3 tries with a 2, 5, 10 second backoff.
- `DeleteOneSignalUser` runs after `DeleteUser` commits the purge and deletes the OneSignal user by external id, which erases its push and SMS subscriptions with it.

A subscription that is disabled is a carrier opt-out (STOP). Neither the reconcile nor the prune re-enables, re-creates or deletes it: deleting it would wipe OneSignal's record, and a user returning to that number would be registered as enabled again, which breaches carrier rules. It delivers nothing, so keeping it costs nothing.

---

## <a name="notificationsetting-model"></a>NotificationSetting Model

`FlutterSdk\MagicStarter\Models\NotificationSetting`

Stores one row per (notifiable, type, channel) combination. Only explicit overrides are stored - the absence of a row means the registry default applies.

### Columns

| Column            | Type      | Description                                       |
|-------------------|-----------|---------------------------------------------------|
| `id`              | string    | Primary key (UUID or integer per app config).     |
| `notifiable_id`   | string    | Polymorphic owner ID.                             |
| `notifiable_type` | string    | Polymorphic owner class.                          |
| `type`            | string    | Notification type slug (e.g., `order_shipped`).   |
| `channel`         | string    | Channel slug (e.g., `push`, `email`, `sms`).      |
| `is_enabled`      | boolean   | Whether the user has this channel enabled.        |
| `created_at`      | timestamp |                                                   |
| `updated_at`      | timestamp |                                                   |

### Relation

```php
public function notifiable(): MorphTo<Model, $this>
```

`ConditionallyUsesUuids` is applied, so the primary key type follows the application's UUID configuration.

---

## <a name="channel-gating-via-gatenotificationchannels"></a>Channel Gating via GateNotificationChannels

`FlutterSdk\MagicStarter\Listeners\GateNotificationChannels`

This event listener is registered automatically by `MagicStarterServiceProvider` and listens to Laravel's `Illuminate\Notifications\Events\NotificationSending` event. Laravel fires this event once per channel per notifiable - if the listener returns `false`, delivery for that channel is cancelled.

### Gate logic (in order)

1. Resolve the notification FQCN from the event.
2. If the class is not in the registry → **allow**.
3. If the notifiable does not have a `prefers()` method → **allow**.
4. Resolve the slug for the notification class.
5. Resolve the logical channel name from the driver channel name via `NotificationPreferenceRegistry::resolveLogicalChannel()`.
6. If the logical channel is not in the registry's channels list for this type → **allow** (unknown channel passes through).
7. If the channel is marked as **locked** for this type → **allow** (locked channels are always delivered).
8. If the notification implements `BypassesNotificationPreferences` and `bypassesPreference($notifiable, $logicalChannel)` returns `true` → **allow**.
9. Call `$notifiable->prefers($slug, $logicalChannel)` and return the result.

### Bypassing a preference

`FlutterSdk\MagicStarter\Contracts\BypassesNotificationPreferences`

A notification can ask the gate to deliver a channel to a notifiable even though the person disabled it. The app owns the decision, for example a fallback when a paid channel is unavailable and the person must still hear by another one.

```php
use FlutterSdk\MagicStarter\Contracts\BypassesNotificationPreferences;

class IncidentOpenedNotification extends Notification implements BypassesNotificationPreferences
{
    public function bypassesPreference(object $notifiable, string $logicalChannel): bool
    {
        return in_array($logicalChannel, ['mail', 'push'], true)
            && $this->smsRefusedFor($notifiable);
    }
}
```

The gate asks once per channel per notifiable at `NotificationSending` time. The notification instance is shared across recipients, so key the answer by `$notifiable` inside the notification. `$logicalChannel` is the registry name (`push`), not the driver class. Only the preference check is bypassed: an unregistered type or an unknown channel already passes, and a locked channel is delivered without asking.

> [!NOTE]
> Channel aliases allow you to map driver channel class names (e.g., `NotificationChannels\OneSignal\OneSignalChannel`) to logical names (e.g., `push`). Register aliases at boot time with `NotificationPreferenceRegistry::channelAliases(['push' => OneSignalChannel::class])`.

---

## <a name="notificationpreferenceregistry"></a>NotificationPreferenceRegistry

`FlutterSdk\MagicStarter\NotificationPreferenceRegistry`

A static registry that declares which notification types are preference-managed and what channels they support. Register types in a service provider:

```php
use FlutterSdk\MagicStarter\NotificationPreferenceRegistry;
use App\Notifications\OrderShippedNotification;

NotificationPreferenceRegistry::register([
    OrderShippedNotification::class => [
        'label'    => 'Order Shipped',
        'channels' => ['push', 'email'],
        'default'  => ['push'],         // channels enabled by default
        'locked'   => ['email'],        // channels the user cannot change
    ],
]);
```

#### Translating the label

`label` is passed through the translator when the matrix is built, so an app
that ships more than one language registers a KEY instead of a sentence:

```php
NotificationPreferenceRegistry::register([
    OrderShippedNotification::class => [
        'label'    => 'notifications.type_order_shipped',
        'channels' => ['push', 'email'],
        'default'  => ['push'],
        'locked'   => [],
    ],
]);
```

A finished sentence still works exactly as before: `__()` hands back an
argument it has no line for, so `'Order Shipped'` stays `'Order Shipped'`.

Two things about this are worth knowing before you rely on it:

- **Register the key, never `__('...')`.** `register()` runs in a service
  provider's `boot()`, which is before any locale middleware has looked at the
  request, and under Octane it runs once for the worker's whole life. A `__()`
  call there resolves in the default locale and then freezes that answer in for
  every later request. Resolving happens inside
  `notificationPreferenceMatrix()` precisely so it lands in the request.
- **The locale comes from the notifiable when it declares one.** If your user
  model implements `Illuminate\Contracts\Translation\HasLocalePreference`
  (the same contract Laravel's own notification sender honours), the label
  resolves in `preferredLocale()`. Without the contract it follows whatever
  locale your app has set, which for most apps means whatever your locale
  middleware resolved for the request.

  **The shipped `User` stub deliberately does NOT implement it, and whether
  you should is one question rather than a default.** This package writes
  `users.locale` at registration and on a profile update, and its migration
  creates that column `NOT NULL` with an `'en'` default. So the column cannot
  tell "this person chose English" apart from "this row was created by a
  seeder and nobody has chosen anything", and `HasLocalePreference` asserts a
  STATED preference. Implement it when your `users.locale` really does reflect
  a choice somebody made:

  ```php
  class User extends Authenticatable implements HasLocalePreference
  {
      public function preferredLocale(): ?string
      {
          return $this->locale;
      }
  }
  ```

  Do not implement it if some of your rows carry the default: on those, a
  stated `'en'` would outrank a request that asked for something else, and a
  person browsing in Turkish would get English labels. Resolve the locale in
  middleware for that shape instead, which is what the label does when no
  contract is declared.

  There is a third shape, and an escape hatch for it. An app whose middleware
  prefers `Accept-Language` while its model implements the contract anyway
  (which is reasonable, since Laravel's notification sender honours it for
  queued mail) gets a preference screen whose type labels follow the stored
  locale while every other string in the same response follows the header. If
  that is you, override the resolver rather than dropping the contract:
  `HasNotifications::translateTypeLabel(string $label): string` is `protected`,
  so one method on your User model decides this for the preference matrix
  alone.

  ```php
  protected function translateTypeLabel(string $label): string
  {
      // Keep the guard the method you are replacing has: `__()` returns the
      // line UNCHANGED when it is an array, so a key naming a group of lines
      // would otherwise put "Array" in a label, with a PHP conversion warning
      // beside it. Handing the key back is what the package does.
      $translated = __($label);

      return is_string($translated) ? $translated : $label;
  }
  ```

### Slug resolution

The registry key can be a FQCN or a plain string. The slug stored in `notification_settings.type` is derived automatically:

- Strip the `Notification` suffix from the class basename.
- Convert the remainder from `PascalCase` to `snake_case`.
- Example: `OrderShippedNotification` → `order_shipped`.

Provide an explicit `slug` key to override this:

```php
NotificationPreferenceRegistry::register([
    OrderShippedNotification::class => [
        'slug'     => 'order_shipped_v2',
        'label'    => 'Order Shipped',
        'channels' => ['push'],
        'default'  => ['push'],
        'locked'   => [],
    ],
]);
```

### Channel aliases

Map logical channel names used in the registry to the actual Laravel notification channel driver strings:

```php
NotificationPreferenceRegistry::channelAliases([
    'push' => \NotificationChannels\OneSignal\OneSignalChannel::class,
]);
```

This mapping is used by `GateNotificationChannels` to translate the driver channel name received in `NotificationSending` back to the logical name stored in the registry and in `notification_settings`.

---

## <a name="mail-branding"></a>Mail Branding

The package can brand every markdown mail your app sends from one config block. It is off by default; with it off nothing changes.

```dotenv
MAGIC_STARTER_MAIL_BRAND_ENABLED=true
```

It covers every mail built on Laravel's markdown layout: this package's own notifications (invitation, verification, support), your own `MailMessage` notifications and Laravel's password reset. It does not touch a Mailable that renders its own Blade view instead of `x-mail::message`.

```php
// config/magic-starter.php
'mail' => [
    'brand' => [
        'enabled' => env('MAGIC_STARTER_MAIL_BRAND_ENABLED', false),
        'name' => 'Acme',
        'logo_url' => 'https://cdn.example.com/mail/logo.png',
        'logo_width' => 48,
        'footer' => 'Acme, all rights reserved :year. [Help centre](https://example.com/help)',
        'font_stack' => "'Helvetica Neue', Helvetica, Arial, sans-serif",
        'button_radius' => 8,
        'card_radius' => 8,
        'colors' => [
            'light' => [
                'primary' => '#2563eb',
                'on_primary' => '#ffffff',
                'heading' => '#0f172a',
                'text' => '#475569',
                'muted' => '#94a3b8',
                'background' => '#f8fafc',
                'card' => '#ffffff',
                'border' => '#e2e8f0',
            ],
            'dark' => [
                'primary' => '#60a5fa',
                'on_primary' => '#0f172a',
                'heading' => '#f8fafc',
                'text' => '#cbd5e1',
                'muted' => '#64748b',
                'background' => '#0f172a',
                'card' => '#1e293b',
                'border' => '#334155',
            ],
        ],
    ],
],
```

| Key | Default | Meaning |
|-----|---------|---------|
| `enabled` | `false` | Turns the branded layout and theme on |
| `name` | `APP_NAME` | Shown beside the logo, as the logo's alt text and in the default footer |
| `logo_url` | `null` | Absolute URL of the header logo; `null` shows the name only |
| `logo_width` | `48` | Logo width in pixels |
| `footer` | `null` | Footer line. `:year` becomes the current year and the text is Markdown. `null` prints `© <year> <name>. All rights reserved.`, translated |
| `font_stack` | Laravel's system stack | CSS `font-family` value |
| `button_radius`, `card_radius` | `4` | Corner radius in pixels |
| `colors.light.*` | Laravel's default theme | `primary`, `on_primary`, `heading`, `text`, `muted`, `background`, `card`, `border` |
| `colors.dark.*` | all `null` | The same eight keys, for dark mode |

A value that breaks a rule throws an `InvalidArgumentException` naming the key and the value when a mail renders, never a half-styled mail:

- Colours are six digit hex (`#2563eb`).
- `colors.dark.*` is all eight keys or none.
- `logo_url` is `null` or an absolute `http` or `https` URL.
- `font_stack` holds letters, digits, spaces, commas, quotes and hyphens only.
- `logo_width` is an integer from 1 to 600, and the radii an integer from 0 to 64. A value read from `env()` is a string, so cast it with `(int)`.
- `name` is a non-empty string.

A key you leave out is an error, except `logo_url`, `footer` and the dark colours, which count as `null`.

### Logo and font

Use an absolute `https` PNG for the logo, at twice `logo_width` so it stays sharp on a high density screen. SVG and web fonts are unreliable across mail clients. Name the brand typeface first in `font_stack` and finish with system fonts: a client that lacks the first falls through to the next.

### Dark mode

Dark colours are optional. When all eight are set, Apple Mail, Outlook.com and Outlook mobile switch to them. Gmail and Outlook for Windows ignore them and apply their own colour inversion, so check a mail in both schemes before you ship.

### Overriding one component

The package appends its `resources/views/mail` directory to `mail.markdown.paths` and sets `mail.markdown.theme` to `magic-starter::mail.theme`, replacing any theme the app configured there; a theme set on a single message with `->theme()` still wins. It replaces `layout`, `header` and `message` (html) and `message` (text); button, panel, table, subcopy and footer stay Laravel's. Because the package path is appended, a directory your app already lists wins per component. Laravel's default `resources/views/vendor/mail` is one, so a file there overrides the package:

```
resources/views/vendor/mail/html/header.blade.php
```

The paths are added once, so `php artisan config:cache` is safe.
