2026-04-29 17:49:07 +03:00
|
|
|
use cot::db::{Database, query};
|
|
|
|
|
|
2026-05-15 15:28:19 +03:00
|
|
|
use crate::models::{Setting, User};
|
2026-04-29 17:49:07 +03:00
|
|
|
|
2026-05-15 15:28:19 +03:00
|
|
|
/// Send a Telegram notification to all admins with notifications enabled.
|
2026-04-29 17:49:07 +03:00
|
|
|
/// Silently ignores errors (missing config, network issues) — notifications are best-effort.
|
2026-05-11 11:34:11 +01:00
|
|
|
pub async fn notify_new_lead(
|
|
|
|
|
db: &Database,
|
|
|
|
|
name: &str,
|
|
|
|
|
phone: Option<&str>,
|
|
|
|
|
comment: Option<&str>,
|
|
|
|
|
) {
|
2026-04-29 17:49:07 +03:00
|
|
|
let token = match get_setting(db, "telegram_bot_token").await {
|
|
|
|
|
Some(t) if !t.is_empty() => t,
|
|
|
|
|
_ => return,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let mut text = format!("📋 Новая заявка!\n\nИмя: {name}");
|
|
|
|
|
if let Some(phone) = phone.filter(|s| !s.is_empty()) {
|
|
|
|
|
text.push_str(&format!("\nТелефон: {phone}"));
|
|
|
|
|
}
|
|
|
|
|
if let Some(comment) = comment.filter(|s| !s.is_empty()) {
|
|
|
|
|
text.push_str(&format!("\nКомментарий: {comment}"));
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-15 15:28:19 +03:00
|
|
|
let active = "active".to_string();
|
|
|
|
|
let users = match query!(User, $status == active).all(db).await {
|
|
|
|
|
Ok(u) => u,
|
|
|
|
|
Err(_) => return,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let client = reqwest::Client::new();
|
2026-04-29 17:49:07 +03:00
|
|
|
let url = format!("https://api.telegram.org/bot{token}/sendMessage");
|
2026-05-15 15:28:19 +03:00
|
|
|
|
|
|
|
|
for user in &users {
|
|
|
|
|
if user.telegram_notifications != Some(true) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
let chat_id = match &user.telegram_chat_id {
|
|
|
|
|
Some(id) if !id.is_empty() => id,
|
|
|
|
|
_ => continue,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let _ = client
|
|
|
|
|
.post(&url)
|
|
|
|
|
.json(&serde_json::json!({
|
|
|
|
|
"chat_id": chat_id,
|
|
|
|
|
"text": text,
|
|
|
|
|
}))
|
|
|
|
|
.send()
|
|
|
|
|
.await;
|
|
|
|
|
}
|
2026-04-29 17:49:07 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn get_setting(db: &Database, key_name: &str) -> Option<String> {
|
|
|
|
|
let k = key_name.to_string();
|
|
|
|
|
query!(Setting, $key == k)
|
|
|
|
|
.get(db)
|
|
|
|
|
.await
|
|
|
|
|
.ok()
|
|
|
|
|
.flatten()
|
|
|
|
|
.map(|s| s.value)
|
|
|
|
|
}
|