laravel_template_engine/
notification.rs1use std::fmt;
4
5use crate::TemplateError;
6use crate::assets::{Assets, assets};
7use crate::config::TemplateEngineConfig;
8use crate::events::TemplateRendered;
9use crate::render::{current_config, pick_locale, render_text, sandbox};
10use crate::sandbox::Escape;
11use crate::schema::TemplateType;
12use crate::template::{Kind, Settings, Template};
13
14#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct RenderedText {
17 pub locale: String,
19 pub subject: String,
21 pub body: String,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct Channel {
28 pub name: String,
30 pub description: String,
32}
33
34pub(crate) fn builtin_channels() -> Vec<Channel> {
36 vec![
37 Channel {
38 name: "sms".to_owned(),
39 description: "Text message".to_owned(),
40 },
41 Channel {
42 name: "slack".to_owned(),
43 description: "Slack".to_owned(),
44 },
45 ]
46}
47
48#[derive(Clone)]
66pub struct NotificationTexts {
67 type_key: &'static str,
68 data: serde_json::Value,
69 templates: Vec<Template>,
70 assets: Assets,
71 config: TemplateEngineConfig,
72}
73
74impl fmt::Debug for NotificationTexts {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 f.debug_struct("NotificationTexts")
77 .field("type_key", &self.type_key)
78 .field("channels", &self.channels())
79 .finish_non_exhaustive()
80 }
81}
82
83pub async fn notification<T: TemplateType>(data: &T) -> laravel::Result<NotificationTexts> {
89 let data = serde_json::to_value(data)
90 .map_err(|e| laravel::Error::msg(format!("the data of `{}` doesn't serialize: {e}", T::KEY)))?;
91 let templates = Template::query()
92 .filter(Template::type_key.eq(T::KEY) & Template::kind.eq(Kind::Notification) & Template::is_active.eq(true))
93 .order_by(Template::id.asc())
94 .get()
95 .await?;
96 Ok(NotificationTexts {
97 type_key: T::KEY,
98 data,
99 templates,
100 assets: assets().await?,
101 config: current_config(),
102 })
103}
104
105impl NotificationTexts {
106 #[must_use]
108 pub fn channels(&self) -> Vec<String> {
109 self.templates
110 .iter()
111 .filter_map(|t| channel_of(t).map(ToOwned::to_owned))
112 .collect()
113 }
114
115 pub fn render(&self, channel: &str, locale: Option<&str>) -> laravel::Result<Option<RenderedText>> {
122 let Some(template) = self.templates.iter().find(|t| channel_of(t) == Some(channel)) else {
123 return Ok(None);
124 };
125 let (chosen, content) = pick_locale(&template.content.0, locale, &self.config.locale)
126 .ok_or_else(|| TemplateError::Render("the template has no text".to_owned()))?;
127 let sandbox = sandbox(chosen, &self.assets, &self.config);
128 let subject = render_text(&sandbox, "subject", &content.subject, &self.data, Escape::None)?;
129 let body = render_text(&sandbox, "body", &content.body, &self.data, Escape::None)?;
130 laravel::event::dispatch_background(TemplateRendered {
131 template_id: template.id,
132 type_key: template.type_key.clone(),
133 kind: Kind::Notification,
134 locale: chosen.to_owned(),
135 })?;
136 Ok(Some(RenderedText {
137 locale: chosen.to_owned(),
138 subject: subject.trim().to_owned(),
139 body: body.trim().to_owned(),
140 }))
141 }
142
143 pub fn text(&self, channel: &str, locale: Option<&str>) -> laravel::Result<String> {
150 self.render(channel, locale)?.map(|text| text.body).ok_or_else(|| {
151 TemplateError::NoNotification {
152 type_key: self.type_key.to_owned(),
153 channel: channel.to_owned(),
154 }
155 .into()
156 })
157 }
158}
159
160fn channel_of(template: &Template) -> Option<&str> {
161 template.settings.get("channel").and_then(serde_json::Value::as_str)
162}
163
164pub(crate) fn settings_channel(settings: &Settings) -> Option<&str> {
165 match settings {
166 Settings::Notification(notification) => Some(notification.channel.as_str()),
167 _ => None,
168 }
169}