use std::fmt;
use crate::TemplateError;
use crate::assets::{Assets, assets};
use crate::config::TemplateEngineConfig;
use crate::events::TemplateRendered;
use crate::render::{current_config, pick_locale, render_text, sandbox};
use crate::sandbox::Escape;
use crate::schema::TemplateType;
use crate::template::{Kind, Settings, Template};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderedText {
pub locale: String,
pub subject: String,
pub body: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Channel {
pub name: String,
pub description: String,
}
pub(crate) fn builtin_channels() -> Vec<Channel> {
vec![
Channel {
name: "sms".to_owned(),
description: "Text message".to_owned(),
},
Channel {
name: "slack".to_owned(),
description: "Slack".to_owned(),
},
]
}
#[derive(Clone)]
pub struct NotificationTexts {
type_key: &'static str,
data: serde_json::Value,
templates: Vec<Template>,
assets: Assets,
config: TemplateEngineConfig,
}
impl fmt::Debug for NotificationTexts {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NotificationTexts")
.field("type_key", &self.type_key)
.field("channels", &self.channels())
.finish_non_exhaustive()
}
}
pub async fn notification<T: TemplateType>(data: &T) -> laravel::Result<NotificationTexts> {
let data = serde_json::to_value(data)
.map_err(|e| laravel::Error::msg(format!("the data of `{}` doesn't serialize: {e}", T::KEY)))?;
let templates = Template::query()
.filter(Template::type_key.eq(T::KEY) & Template::kind.eq(Kind::Notification) & Template::is_active.eq(true))
.order_by(Template::id.asc())
.get()
.await?;
Ok(NotificationTexts {
type_key: T::KEY,
data,
templates,
assets: assets().await?,
config: current_config(),
})
}
impl NotificationTexts {
#[must_use]
pub fn channels(&self) -> Vec<String> {
self.templates
.iter()
.filter_map(|t| channel_of(t).map(ToOwned::to_owned))
.collect()
}
pub fn render(&self, channel: &str, locale: Option<&str>) -> laravel::Result<Option<RenderedText>> {
let Some(template) = self.templates.iter().find(|t| channel_of(t) == Some(channel)) else {
return Ok(None);
};
let (chosen, content) = pick_locale(&template.content.0, locale, &self.config.locale)
.ok_or_else(|| TemplateError::Render("the template has no text".to_owned()))?;
let sandbox = sandbox(chosen, &self.assets, &self.config);
let subject = render_text(&sandbox, "subject", &content.subject, &self.data, Escape::None)?;
let body = render_text(&sandbox, "body", &content.body, &self.data, Escape::None)?;
laravel::event::dispatch_background(TemplateRendered {
template_id: template.id,
type_key: template.type_key.clone(),
kind: Kind::Notification,
locale: chosen.to_owned(),
})?;
Ok(Some(RenderedText {
locale: chosen.to_owned(),
subject: subject.trim().to_owned(),
body: body.trim().to_owned(),
}))
}
pub fn text(&self, channel: &str, locale: Option<&str>) -> laravel::Result<String> {
self.render(channel, locale)?.map(|text| text.body).ok_or_else(|| {
TemplateError::NoNotification {
type_key: self.type_key.to_owned(),
channel: channel.to_owned(),
}
.into()
})
}
}
fn channel_of(template: &Template) -> Option<&str> {
template.settings.get("channel").and_then(serde_json::Value::as_str)
}
pub(crate) fn settings_channel(settings: &Settings) -> Option<&str> {
match settings {
Settings::Notification(notification) => Some(notification.channel.as_str()),
_ => None,
}
}