use cot::db::{Database, query}; use crate::models::{Setting, User}; /// Send a Telegram notification to all admins with notifications enabled. /// Silently ignores errors (missing config, network issues) — notifications are best-effort. pub async fn notify_new_lead( db: &Database, name: &str, phone: Option<&str>, comment: Option<&str>, ) { 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}")); } 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(); let url = format!("https://api.telegram.org/bot{token}/sendMessage"); 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; } } async fn get_setting(db: &Database, key_name: &str) -> Option { let k = key_name.to_string(); query!(Setting, $key == k) .get(db) .await .ok() .flatten() .map(|s| s.value) }