# Notifications

- [Introduction](#introduction)
- [Writing notifications](#writing-notifications)
    - [Mail messages](#mail-messages)
    - [SMS messages](#sms-messages)
    - [Slack messages](#slack-messages)
- [Notifiables](#notifiables)
- [Sending notifications](#sending-notifications)
    - [Queueing notifications](#queueing-notifications)
- [Choosing channels for each notifiable](#choosing-channels)
- [Package channels](#package-channels)
    - [Sending through a package channel](#sending-through-a-package-channel)
    - [Writing a channel](#writing-a-channel)
- [Testing](#testing)

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

## Introduction


고객이 청구서를 결제하면 이메일과 문자 메시지를 보내고 팀의 Slack 채널에 결제 내역을 게시할 수 있습니다. 알림은 이 이벤트를 한 번 정의하고 채널별 메시지를 구성하며, Laravel은 지정한 모든 사용자나 팀에 메시지를 전달합니다.


Laravel은 이메일, SMS, Slack 및 Discord 같은 [custom package channels](#package-channels)로 알림을 전달합니다. 이메일은 [mail](/rust/docs/mail), 문자 메시지는 [SMS](/rust/docs/sms)를 사용하며 해당 가이드의 설정과 큐를 공유하므로, 사용할 채널부터 설정하세요.


알림은 짧고 정보를 전달하는 내용으로 작성하세요. 주문 영수증처럼 자체 레이아웃과 첨부 파일이 있는 이메일 한 통을 보내려면 [mailable](/rust/docs/mail)을 직접 전송하세요.

<a name="writing-notifications"></a>

## Writing notifications


각 알림은 메시지에 필요한 데이터를 담는 구조체와 `#[notification]`이 붙은 `impl` 블록으로 구성됩니다. 보통 `src/notifications.rs` 같은 모듈에서 알림이 지원하는 채널별로 `mail`, `sms`, `slack` 메서드를 정의합니다.


예를 들어 애플리케이션에 `Invoice` [model](/rust/docs/models)과 `InvoicePaidEmail` [mailable](#mail-messages)이 있다고 가정하겠습니다. 다음 알림은 청구서가 결제되면 사용자에게 알립니다.

```rust
use laravel::mail::Mailable;
use laravel::notification;

use crate::mail::InvoicePaidEmail;

pub struct InvoicePaid {
    pub invoice: Invoice,
}

#[notification]
impl InvoicePaid {
    fn mail(&self, user: &User) -> impl Mailable {
        InvoicePaidEmail { name: user.name.clone(), invoice_id: self.invoice.id }
    }

    fn sms(&self, _user: &User) -> String {
        format!("Invoice #{} is paid. Thanks!", self.invoice.id)
    }
}
```


각 메서드의 두 번째 인수는 메시지를 받는 알림 수신 대상으로, 여기서는 `&User`입니다. 하나의 `impl` 안에 있는 모든 메서드는 같은 수신 대상 타입을 받습니다. 팀에도 알림을 보내려면 [Slack example](#slack-messages)처럼 메서드가 `&Team`을 받는 두 번째 `#[notification]` 구현을 작성하세요.


채널 메서드는 동기식이므로 필요한 관련 모델이나 데이터를 알림 전송 전에 불러오세요. Laravel은 알림을 발송하는 핸들러나 잡에서 이 메서드를 호출하므로 라우트 URL, 설정, [context values](/rust/docs/context)에 직접 접근할 수 있습니다. 라우트 URL 생성 등 채널 메서드에서 실패할 수 있는 작업을 수행한다면 `laravel::Result`를 반환하세요. 오류가 있으면 메시지가 하나라도 전달되기 전에 전송을 중단합니다.


알림은 [mailable](/rust/docs/mail#writing-mailables)처럼 데이터를 소유하므로 [fake](#testing)가 테스트용으로 보관할 수 있습니다. 전송 후에도 값이 필요하면 `InvoicePaid { invoice: invoice.clone() }`처럼 복제하여 알림에 넣으세요.

<a name="mail-messages"></a>

### Mail messages


`mail`은 수신 대상 한 명이 받을 이메일을 반환합니다. 파생 Mailable, [builds its message itself](/rust/docs/mail#building-the-message-yourself) 방식으로 직접 메시지를 구성하는 Mailable, 또는 `Message`를 반환할 수 있습니다. `InvoicePaidEmail`은 `name`과 `invoice_id`로 `resources/views/mail/invoice-paid-email.html`을 렌더링하는 파생 Mailable입니다.

```rust
use laravel::mail::Mailable;

#[derive(Mailable)]
#[mail(subject = "Invoice #{invoice_id} is paid")]
pub struct InvoicePaidEmail {
    pub name: String,
    pub invoice_id: i64,
}
```


Laravel은 수신 대상의 이메일 주소를 수신자로 자동 지정하므로 Mailable에서 `to`를 지정할 필요가 없습니다. 뷰, 제목, 첨부 파일에 관한 자세한 내용은 [Mail](/rust/docs/mail#writing-mailables) 가이드를 참고하세요.

<a name="sms-messages"></a>

### SMS messages


`sms`는 `SMS_FROM` 번호로 발송할 텍스트를 `String` 또는 `&str`로 반환합니다. 다른 번호로 보내려면 `sms::Message`를 반환하세요.

```rust
use laravel::sms;

fn sms(&self, _user: &User) -> sms::Message {
    sms::Message::new(format!("Invoice #{} is paid.", self.invoice.id)).from("+15555550199")
}
```

<a name="slack-messages"></a>

### Slack messages


`slack`은 섹션이나 버튼 같은 블록을 담은 [`slack::Message`](/rust/docs/slack#writing-messages)를 반환합니다. Slack 메시지는 보통 사용자 한 명보다 팀 채널로 보냅니다. 예를 들어 애플리케이션에 `slack_channel_id` 컬럼을 가진 `Team` 모델이 있다고 가정하겠습니다.

```rust
use laravel::notification;
use laravel::prelude::*;
use laravel::slack::{Button, Message, Section};

#[notification]
impl InvoicePaid {
    fn slack(&self, _team: &Team) -> laravel::Result<Message> {
        let url = route!(invoices::show, &self.invoice)?;
        let amount = format!("${:.2}", self.invoice.total as f64 / 100.0);

        Ok(Message::new(format!("Invoice #{} is paid", self.invoice.id))
            .section(Section::new("Invoice paid.").field("Amount", amount))
            .actions([Button::link("View invoice", url)]))
    }
}
```


메시지는 팀의 [Slack route](#notifiables)로 전송됩니다. Slack 앱 설정과 버튼 클릭 처리는 [Slack guide](/rust/docs/slack)를 참고하세요.

<a name="notifiables"></a>

## Notifiables


알림 수신 대상은 `User`나 `Team`처럼 알림을 받는 타입입니다. 지원하는 채널별로 `ReceivesMail`, `ReceivesSms`, `ReceivesSlack`을 구현하여 이메일 주소, 전화번호, [Slack route](/rust/docs/slack#routing-notifications)를 제공합니다. 사용자 테이블에 null을 허용하는 `phone` 컬럼이 있다고 가정하겠습니다.

```rust
use laravel::mail::Address;
use laravel::notification::{ReceivesMail, ReceivesSlack, ReceivesSms};
use laravel::slack::Route;
use laravel::sms::PhoneNumber;

impl ReceivesMail for User {
    fn mail_address(&self) -> Option<Address> {
        Some(Address::new(&self.email).with_name(&self.name))
    }
}

impl ReceivesSms for User {
    fn sms_number(&self) -> Option<PhoneNumber> {
        self.phone.as_deref().map(PhoneNumber::new)
    }
}

impl ReceivesSlack for Team {
    fn slack_route(&self) -> Option<Route> {
        self.slack_channel_id.as_deref().map(Route::channel)
    }
}
```


이 메서드 중 하나가 `None`을 반환하면 오류 없이 해당 수신 대상의 채널 전송을 건너뜁니다. 전화번호 없이 가입한 사용자도 이메일은 받습니다.


알림 수신 대상은 알림이 구성하는 모든 채널을 구현해야 합니다. `ReceivesSms`가 없는 타입에 `InvoicePaid`를 보내면 컴파일되지 않습니다.

<a name="sending-notifications"></a>

## Sending notifications


알림을 보내려면 `notification::to`로 수신자를 지정한 다음 `queue`나 `send`를 호출하세요. 대부분의 핸들러에서는 HTTP 응답이 외부 프로바이더를 기다리지 않도록 알림을 [queue](#queueing-notifications)에 넣는 것이 좋습니다. 다음 핸들러는 청구서를 결제하고 고객에게 알립니다.

```rust
use laravel::notification;
use laravel::prelude::*;

use crate::models::Invoice;
use crate::notifications::InvoicePaid;

pub async fn pay(Params(id): Params<i64>) -> laravel::Result<Redirect> {
    let invoice = Invoice::query()
        .with(Invoice::user)
        .find_or_fail(id)
        .await?;

    // Charge the invoice...

    notification::to(&invoice.user)
        .queue(InvoicePaid { invoice: invoice.clone() })
        .await?;

    Ok(Redirect::back())
}
```


`send`는 메시지를 즉시 전달하고 각 프로바이더가 수락할 때까지 기다립니다. `to`는 단일 수신 대상의 참조, 수신 대상의 슬라이스나 `Vec`, 참조의 `Vec`, [`Authenticated<User>`](/rust/docs/authentication#retrieving-the-logged-in-user), 또는 `&invoice.user`, `&team.members`처럼 불러온 [relationship](/rust/docs/model-relationships#eager-loading)을 받습니다. 여러 팀에 한 번에 알리려면 다음과 같이 작성합니다.

```rust
let teams = Team::all().await?;

notification::to(&teams).send(WeeklySummary { report }).await?;
```


하나의 알림이 여러 수신 대상 타입에 `#[notification]`을 구현하면 Rust는 `&Vec<T>`, `&Authenticated<T>` 또는 불러온 연관관계 래퍼에서 대상 타입을 추론하지 못합니다. 이 경우 슬라이스를 전달하거나 래퍼를 역참조하세요.

```rust
let teams = Team::all().await?;

notification::to(teams.as_slice()).send(InvoicePaid { invoice }).await?;
```

<a name="queueing-notifications"></a>

### Queueing notifications


`queue`는 [queue worker](/rust/docs/queues#running-the-worker)에서 메시지를 전송하며 프로바이더가 실패하면 각 메시지를 재시도합니다. 따라서 알림을 큐에 넣기 전에 워커를 시작하세요. `queue`를 await하기 전에 메시지를 지연시키고 잡을 보낼 큐를 선택할 수 있습니다.

```rust
use laravel::time::ToSpan;

notification::to(&user)
    .queue(InvoicePaid { invoice })
    .delay(5.minutes())
    .on_queue("notifications")
    .await?;
```


`queue`는 [queued mail](/rust/docs/mail#queueing-mail)과 [queued SMS](/rust/docs/sms#queueing-messages)처럼 수신 대상과 채널 조합마다 잡 하나를 발송합니다. 사용자 세 명과 채널 두 개면 잡 여섯 개가 생성되며, 문자 메시지가 실패하면 해당 문자만 재시도하고 이메일은 재시도하지 않습니다.


`on_connection`과 `on_queue`를 지정하지 않으면 이메일 잡은 `MAIL_QUEUE_CONNECTION`과 `MAIL_QUEUE`를, 문자 메시지 잡은 `SMS_QUEUE_CONNECTION`과 `SMS_QUEUE`를 사용하며, Slack과 패키지 채널 잡은 기본 연결과 큐를 사용합니다.


[database transaction](/rust/docs/database#transactions) 안에서 알림을 큐에 넣으면 Laravel은 트랜잭션이 커밋될 때까지 잡 발송을 기다립니다. 트랜잭션이 롤백되면 큐에 넣은 알림을 버리므로 저장되지 않은 변경 사항을 사용자에게 알리지 않습니다.

<a name="choosing-channels"></a>

## Choosing channels for each notifiable


기본적으로 알림은 `#[notification]` 블록에 정의된 모든 채널로 전달됩니다. 그러나 사용자가 특정 채널을 선택하거나 거부하게 하거나 알림 데이터에 따라 채널을 결정할 수도 있습니다. 수신자별 전달을 제어하려면 알림에 `channels` 메서드를 추가하세요. 예를 들어 설정 페이지에서 관리하는 `sms_alerts` 컬럼이 사용자 테이블에 있다고 가정하겠습니다.

```rust
use laravel::notification;
use laravel::notification::{Mail, Selected, Sms};

#[notification]
impl InvoicePaid {
    // `mail` and `sms` as before...

    fn channels(&self, user: &User, channels: &mut Selected<Self, User>) {
        channels.add(Mail);

        if user.sms_alerts && self.invoice.total >= 10_000 {
            channels.add(Sms);
        }
    }
}
```


`channels`는 Laravel이 메시지를 구성하기 전에 수신 대상마다 한 번 실행됩니다. 대기하거나 실패할 수 없으므로 데이터베이스를 조회할 수 없습니다. 필요한 데이터는 전송 전에 수신 대상이나 알림에 불러오세요.

<a name="package-channels"></a>

## Package channels


사용자는 Discord처럼 Laravel에 기본 채널이 없는 곳에서 알림을 받고 싶을 수 있습니다. 패키지로 채널을 추가하면 이메일과 문자 메시지 옆에 해당 채널의 메시지도 구성할 수 있습니다.

<a name="sending-through-a-package-channel"></a>

### Sending through a package channel


패키지 채널로 보내려면 `#[notification]` 구현의 메서드에 `#[via(..)]`와 채널 타입을 지정하세요. 예를 들어 `discord_notifications` 패키지가 웹훅 URL에 `DiscordMessage`를 보내는 `Discord` 채널을 제공한다고 가정하겠습니다.

```rust
use discord_notifications::{Discord, DiscordMessage};
use laravel::notification;
use laravel::notification::Receives;

#[notification]
impl InvoicePaid {
    // `mail` and `sms` as before...

    #[via(Discord)]
    fn discord(&self, _user: &User) -> DiscordMessage {
        DiscordMessage::new(format!("Invoice #{} is paid.", self.invoice.id))
    }
}
```


수신 대상은 `Receives<Discord>`를 구현하며, 이 트레이트의 `route` 메서드는 패키지가 정의한 목적지 값을 반환합니다. 사용자 테이블에 null을 허용하는 `discord_webhook_url` 컬럼이 있다고 가정하겠습니다.

```rust
impl Receives<Discord> for User {
    fn route(&self) -> Option<String> {
        self.discord_webhook_url.clone()
    }
}
```


내장 채널과 마찬가지로 `Receives<Discord>::route`가 `Some`을 반환하면 패키지 채널도 기본적으로 포함됩니다. 알림에 수신자별 채널을 선택하는 [`channels`](#choosing-channels) 메서드가 있다면 `channels.add`에 채널 타입을 전달하여 패키지 채널을 포함하세요.

```rust
use discord_notifications::Discord;
use laravel::notification;
use laravel::notification::{Mail, Selected};

#[notification]
impl InvoicePaid {
    // `mail`, `sms`, and `discord` as before...

    fn channels(&self, user: &User, channels: &mut Selected<Self, User>) {
        channels.add(Mail);

        if user.discord_alerts {
            channels.add(Discord);
        }
    }
}
```


`channels.add`에 전달하는 채널 타입은 타입 검사를 받습니다. 알림에 `#[via(Discord)]` 메서드가 있고 수신 대상이 `Receives<Discord>`를 구현해야 코드가 컴파일됩니다.

<a name="writing-a-channel"></a>

### Writing a channel


채널은 `impl`에 `#[notification::channel]`을 지정한 유닛 구조체입니다. `impl`은 라우트와 메시지를 받아 프로바이더가 메시지를 수락하면 반환하는 비동기 `send` 함수를 포함합니다. 패키지가 제공할 Discord 채널은 다음과 같습니다.

```rust
use laravel::http::client;
use laravel::notification;
use serde::{Deserialize, Serialize};

#[derive(Clone, Copy)]
pub struct Discord;

#[derive(Serialize, Deserialize)]
pub struct DiscordMessage {
    pub content: String,
}

impl DiscordMessage {
    pub fn new(content: impl Into<String>) -> Self {
        Self { content: content.into() }
    }
}

#[notification::channel(name = "discord")]
impl Discord {
    async fn send(webhook_url: String, message: DiscordMessage) -> laravel::Result<()> {
        client::post(webhook_url).json(&message).ensure_successful().await?;

        Ok(())
    }

    fn check(message: &DiscordMessage) -> laravel::Result<()> {
        if message.content.chars().count() > 2000 {
            return Err(laravel::abort_with(
                500,
                "a Discord message holds at most 2,000 characters",
            ));
        }

        Ok(())
    }
}
```


`send`의 인수 타입이 채널의 라우트와 메시지 타입이 됩니다. 큐 잡이 이를 저장하므로 두 타입 모두 `Serialize`와 `Deserialize`를 구현해야 합니다. `send`는 애플리케이션 컨텍스트에서 실행되므로 API 토큰을 담은 [config section](/rust/docs/configuration#your-own-config-sections)처럼 설정을 읽고 서비스를 조회할 수 있습니다.


선택적인 `check` 함수는 알림이 각 메시지를 구성할 때 실행됩니다. 프로바이더가 거부할 메시지는 큐 워커에 도달하기 전에 전송 코드와 테스트에서 실패합니다. Discord의 2,000자 제한처럼 프로바이더가 문서로 명시한 제한에 사용하세요.


사용자 지정 채널의 알림을 큐에 넣으면 Laravel은 워커가 호출할 `send` 함수를 알 수 있도록 잡 페이로드에 채널의 `name`을 기록합니다. `name`을 생략하면 구조체의 전체 Rust 모듈 경로(예를 들어 `discord_notifications::channels::Discord`)를 사용합니다.


채널에 명시적인 `name`을 지정하면 큐 잡이 모듈 구조에 종속되지 않습니다. 나중에 구조체를 다른 모듈로 옮기거나 이름을 바꾸어도 이미 큐에 있는 잡이 실패 없이 계속 실행됩니다.

```rust
#[notification::channel(name = "discord")]
impl DiscordWebhook {
    async fn send(webhook_url: String, message: DiscordMessage) -> laravel::Result<()> {
        // ...
    }
}
```

<a name="testing"></a>

## Testing


대부분의 테스트에서는 프로바이더의 전달 여부보다 코드가 알림을 보냈는지 확인하는 것이 좋습니다. `notification::fake()`는 실제 전송 대신 알림을 기록합니다. 실제 전송과 동일하게 각 메시지를 구성하고 렌더링하므로 템플릿 오류나 잘못된 전화번호가 있으면 테스트가 실패합니다.

```rust
use laravel::model::create;
use laravel::notification;
use laravel::testing::prelude::*;

#[laravel::test]
async fn paying_an_invoice_notifies_the_customer(app: Application) -> laravel::Result<()> {
    let user = create!(User {
        name: "Taylor",
        email: "taylor@laravel.com",
        password: "password",
    })
    .await?;

    let invoice = create!(Invoice { user_id: user.id, total: 120_000 }).await?;

    let notifications = notification::fake();

    app.post(format!("/invoices/{}/pay", invoice.id)).await.assert_redirect();

    notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| {
        sent.notification().invoice.id == invoice.id && sent.sms().is_none()
    });

    Ok(())
}
```


조건 함수에 전달되는 각 `SentNotification`은 `notification()`으로 원래 알림을 제공하고, `queued()`로 동기 전송 대신 큐에 넣었는지 확인할 수 있게 합니다. `mail()`로 렌더링된 이메일을, `mailable::<M>()`으로 이를 구성한 Mailable 구조체를 확인할 수도 있습니다.

```rust
notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| {
    sent.queued()
        && sent
            .mail()
            .is_some_and(|email| email.subject() == format!("Invoice #{} is paid", invoice.id))
        && sent.mailable::<InvoicePaidEmail>().is_some_and(|mail| mail.name == user.name)
});
```


해당 수신 대상에서 채널을 건너뛰었다면 각 채널 접근자는 `None`을 반환합니다. 예를 들어 위의 Taylor는 전화번호가 없으므로 `sent.sms()`가 `None`입니다. SMS가 전송됐다면 `sms()`로 메시지를 확인하세요.

```rust
notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| {
    sent.sms().is_some_and(|sms| sms.text().contains("Thanks!"))
});
```


Slack과 사용자 지정 패키지 채널은 `message::<C>()`에 채널 타입을 지정하여 구성된 메시지를 확인하세요.

```rust
use discord_notifications::Discord;
use laravel::notification::Slack;

notifications.assert_sent_to_where::<InvoicePaid>(&team, |sent| {
    sent.message::<Slack>()
        .is_some_and(|message| message.text().contains(&format!("Invoice #{}", invoice.id)))
});

notifications.assert_sent_to_where::<InvoicePaid>(&user, |sent| {
    sent.message::<Discord>()
        .is_some_and(|message| message.content.contains(&format!("Invoice #{}", invoice.id)))
});
```


fake는 다음 검증 메서드를 제공합니다.

| 메서드 | 검증 내용 또는 반환값 |
| --- | --- |
| `assert_sent::<T>()` | 타입 `T`의 알림을 한 번 이상 전송하거나 큐에 넣었음 |
| `assert_sent_to::<T>(&notifiable)` | 이 수신 대상에 타입 `T`의 알림을 전송하거나 큐에 넣었음 |
| `assert_sent_to_where::<T>(&notifiable, predicate)` | 이 수신 대상의 타입 `T` 알림이 조건 함수에 부합함 |
| `assert_not_sent_to::<T>(&notifiable)` | 이 수신 대상에 타입 `T`의 알림을 전송하거나 큐에 넣지 않았음 |
| `assert_sent_where::<T>(predicate)` | 한 수신 대상의 타입 `T` 알림이 조건 함수에 부합함 |
| `assert_sent_times::<T>(count)` | 타입 `T`의 알림이 정확히 `count`개의 수신 대상에 도달함 |
| `assert_not_sent::<T>()` | 타입 `T`의 알림을 전송하거나 큐에 넣지 않았음 |
| `assert_nothing_sent()` | 어떤 알림도 전송하거나 큐에 넣지 않았음 |
| `sent::<T>()` | 알림과 함께 타입 `T`의 각 `SentNotification`을 순서대로 반환 |


fake는 전송한 알림과 큐에 넣은 알림을 모두 기록합니다. `SentNotification::queued()`로 구분하세요.


알림 fake가 활성화된 동안 알림은 [mail fake](/rust/docs/mail#testing)나 [SMS fake](/rust/docs/sms#testing)에 전달되지 않습니다. 알림 fake가 없으면 이 fake들이 일반 이메일과 문자 메시지뿐 아니라 알림 메시지도 기록합니다.