Spaces:
Sleeping

axeronis commited on
Commit
455a5d9
·
1 Parent(s): 124b9d2

refactor: Rename TELEGRAM_BOT_TOKEN to TELEGRAM_NOTIFICATION_TOKEN and update config

Browse files
backend/app/api/telegram_webhook.py CHANGED
@@ -80,7 +80,7 @@ async def process_telegram_message(
80
  if not bot_token:
81
  # Fallback to global config if single tenant mode or dev
82
  from app.core.config import settings
83
- bot_token = settings.TELEGRAM_BOT_TOKEN
84
 
85
  if not bot_token:
86
  logger.error(f"No Telegram token found for tenant {tenant_id}")
 
80
  if not bot_token:
81
  # Fallback to global config if single tenant mode or dev
82
  from app.core.config import settings
83
+ bot_token = settings.TELEGRAM_NOTIFICATION_TOKEN
84
 
85
  if not bot_token:
86
  logger.error(f"No Telegram token found for tenant {tenant_id}")
backend/app/core/config.py CHANGED
@@ -53,7 +53,7 @@ class Settings(BaseSettings):
53
  GOOGLE_CLIENT_SECRET: Optional[str] = None
54
 
55
  # Telegram
56
- TELEGRAM_BOT_TOKEN: Optional[str] = None
57
  TELEGRAM_WEBHOOK_URL: Optional[str] = None
58
 
59
  # Evolution API / Baileys (WhatsApp)
 
53
  GOOGLE_CLIENT_SECRET: Optional[str] = None
54
 
55
  # Telegram
56
+ TELEGRAM_NOTIFICATION_TOKEN: Optional[str] = "8467664774:AAGs7LVLkbShw2UGZLL8pDaeWRmbzAcDGmw"
57
  TELEGRAM_WEBHOOK_URL: Optional[str] = None
58
 
59
  # Evolution API / Baileys (WhatsApp)
backend/app/services/notification.py CHANGED
@@ -57,8 +57,14 @@ class NotificationService:
57
 
58
  async def _send_telegram(self, bot_token: str, chat_id: str, text: str):
59
  """Helper to send TG message."""
60
- if not bot_token or not chat_id:
61
- logger.warning("⚠️ Cannot send notification: Missing bot_token or chat_id")
 
 
 
 
 
 
62
  return
63
 
64
  try:
@@ -67,7 +73,7 @@ class NotificationService:
67
  # Using the one imported from deps/webhook context usually
68
  from app.api.webhook import send_telegram_message as send_tg
69
 
70
- await send_tg(bot_token, chat_id, text)
71
  logger.info(f"📧 Notification sent to Admin {chat_id}")
72
  except Exception as e:
73
  logger.error(f"❌ Failed to send admin notification: {e}")
 
57
 
58
  async def _send_telegram(self, bot_token: str, chat_id: str, text: str):
59
  """Helper to send TG message."""
60
+ # Use Global Platform Bot Token if not explicitly provided (which is null now)
61
+ from app.core.config import settings as global_settings
62
+
63
+ # Priority: explicit argument -> global setting -> fail
64
+ token_to_use = bot_token or global_settings.TELEGRAM_NOTIFICATION_TOKEN
65
+
66
+ if not token_to_use or not chat_id:
67
+ logger.warning("⚠️ Cannot send notification: Missing PLATFORM TELEGRAM_NOTIFICATION_TOKEN or chat_id")
68
  return
69
 
70
  try:
 
73
  # Using the one imported from deps/webhook context usually
74
  from app.api.webhook import send_telegram_message as send_tg
75
 
76
+ await send_tg(token_to_use, chat_id, text)
77
  logger.info(f"📧 Notification sent to Admin {chat_id}")
78
  except Exception as e:
79
  logger.error(f"❌ Failed to send admin notification: {e}")
backend/app/services/telegram_service.py CHANGED
@@ -12,7 +12,7 @@ class TelegramService:
12
 
13
  def __init__(self):
14
  self.base_url = "https://api.telegram.org/bot"
15
- self.token = settings.TELEGRAM_BOT_TOKEN
16
 
17
  def _get_url(self, token: str, method: str) -> str:
18
  return f"{self.base_url}{token}/{method}"
 
12
 
13
  def __init__(self):
14
  self.base_url = "https://api.telegram.org/bot"
15
+ self.token = settings.TELEGRAM_NOTIFICATION_TOKEN
16
 
17
  def _get_url(self, token: str, method: str) -> str:
18
  return f"{self.base_url}{token}/{method}"
frontend/app/settings/notifications/page.tsx CHANGED
@@ -1,20 +1,29 @@
1
  'use client'
2
 
3
  import { useState, useEffect } from 'react'
4
- import { Save, Bell, MessageCircle, AlertCircle } from 'lucide-react'
5
- import { motion } from 'framer-motion'
6
-
7
- export default function NotificationSettings() {
8
- const [settings, setSettings] = useState({
9
- telegram_enabled: true,
10
- telegram_chat_id: '',
11
- dashboard_enabled: true,
12
- notify_hot_leads: true
13
- })
 
 
14
  const [loading, setLoading] = useState(true)
15
  const [saving, setSaving] = useState(false)
16
- const [saveSuccess, setSaveSuccess] = useState(false)
17
 
 
 
 
 
 
 
 
 
18
  useEffect(() => {
19
  fetchSettings()
20
  }, [])
@@ -22,184 +31,174 @@ export default function NotificationSettings() {
22
  const fetchSettings = async () => {
23
  try {
24
  const token = localStorage.getItem('auth_token')
25
- const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/notifications/settings`, {
26
  headers: { 'Authorization': `Bearer ${token}` }
27
  })
28
- const data = await response.json()
29
- setSettings(data)
30
- } catch (error) {
31
- console.error('Failed to fetch settings:', error)
 
 
 
 
 
 
 
 
 
32
  } finally {
33
  setLoading(false)
34
  }
35
  }
36
 
37
  const handleSave = async () => {
 
38
  try {
39
- setSaving(true)
40
  const token = localStorage.getItem('auth_token')
41
- await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/notifications/settings`, {
42
- method: 'PUT',
 
 
 
 
 
 
 
 
 
 
 
 
43
  headers: {
44
  'Authorization': `Bearer ${token}`,
45
  'Content-Type': 'application/json'
46
  },
47
- body: JSON.stringify(settings)
48
  })
49
- setSaveSuccess(true)
50
- setTimeout(() => setSaveSuccess(false), 3000)
51
- } catch (error) {
52
- console.error('Failed to save settings:', error)
 
 
 
53
  alert('Ошибка сохранения')
54
  } finally {
55
  setSaving(false)
56
  }
57
  }
58
 
59
- if (loading) {
60
- return (
61
- <div className="flex items-center justify-center min-h-screen">
62
- <div className="text-slate-500">Загрузка...</div>
63
- </div>
64
- )
65
- }
66
 
67
  return (
68
- <div className="max-w-3xl mx-auto p-8">
69
- <div className="mb-8">
70
- <h1 className="text-3xl font-bold text-slate-900">Уведомления</h1>
71
- <p className="text-slate-600 mt-2">
72
- Настройте уведомления о горячих лидах, чтобы не пропустить важных клиентов
73
- </p>
74
  </div>
75
 
76
- {/* Info Alert */}
77
- <div className="mb-6 bg-indigo-50 border border-indigo-200 rounded-xl p-4 flex gap-3">
78
- <AlertCircle className="w-5 h-5 text-indigo-600 flex-shrink-0 mt-0.5" />
79
- <div className="text-sm text-indigo-900">
80
- <p className="font-semibold mb-1">🎯 Цель: Экономить время</p>
81
- <p className="text-indigo-700">
82
- Вы получаете уведомления только о HOT лидах (готовых к покупке). Никакого спама от муслоных клиентов.
83
- </p>
 
 
84
  </div>
85
- </div>
86
 
87
- <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-8 space-y-8">
88
- {/* Telegram Section */}
89
- <div>
90
- <div className="flex items-center gap-3 mb-6">
91
- <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
92
- <MessageCircle className="w-5 h-5 text-blue-600" />
93
- </div>
94
- <div>
95
- <h3 className="font-semibold text-lg">Telegram</h3>
96
- <p className="text-sm text-slate-500">Мгновенные уведомления на телефон</p>
97
- </div>
 
 
 
 
 
 
 
 
98
  </div>
 
 
99
 
100
- <label className="flex items-center gap-3 mb-6 cursor-pointer group">
101
- <input
102
- type="checkbox"
103
- checked={settings.telegram_enabled}
104
- onChange={(e) => setSettings({ ...settings, telegram_enabled: e.target.checked })}
105
- className="w-5 h-5 text-indigo-600 rounded border-slate-300 focus:ring-2 focus:ring-indigo-500"
106
- />
107
- <span className="text-sm font-medium text-slate-700 group-hover:text-slate-900">
108
- Включить Telegram уведомления
109
- </span>
110
- </label>
111
-
112
- <div className="space-y-4">
113
- <div>
114
- <label className="block text-sm font-medium text-slate-700 mb-2">
115
- Chat ID <span className="text-red-500">*</span>
116
- </label>
117
- <input
118
- type="text"
119
- value={settings.telegram_chat_id || ''}
120
- onChange={(e) => setSettings({ ...settings, telegram_chat_id: e.target.value })}
121
- placeholder="Ваш Telegram Chat ID"
122
- className="w-full px-4 py-3 border border-slate-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all"
123
- />
124
- <div className="mt-3 p-4 bg-slate-50 rounded-lg">
125
- <p className="text-xs font-semibold text-slate-700 mb-2">📱 Как получить Chat ID:</p>
126
- <ol className="text-xs text-slate-600 space-y-1 list-decimal list-inside">
127
- <li>Откройте Telegram</li>
128
- <li>Найдите бота <code className="bg-slate-200 px-1 py-0.5 rounded">@userinfobot</code></li>
129
- <li>Отправьте команду <code className="bg-slate-200 px-1 py-0.5 rounded">/start</code></li>
130
- <li>Скопируйте ваш ID (число)</li>
131
- </ol>
132
- </div>
133
- </div>
134
  </div>
135
  </div>
136
 
137
- {/* Dashboard Section */}
138
- <div className="pt-8 border-t border-slate-200">
139
- <div className="flex items-center gap-3 mb-6">
140
- <div className="w-10 h-10 rounded-full bg-indigo-100 flex items-center justify-center">
141
- <Bell className="w-5 h-5 text-indigo-600" />
142
- </div>
143
- <div>
144
- <h3 className="font-semibold text-lg">Dashboard</h3>
145
- <p className="text-sm text-slate-500">Уведомления в интерфейсе</p>
146
  </div>
 
147
  </div>
148
 
149
- <label className="flex items-center gap-3 cursor-pointer group">
150
- <input
151
- type="checkbox"
152
- checked={settings.dashboard_enabled}
153
- onChange={(e) => setSettings({ ...settings, dashboard_enabled: e.target.checked })}
154
- className="w-5 h-5 text-indigo-600 rounded border-slate-300 focus:ring-2 focus:ring-indigo-500"
155
- />
156
- <span className="text-sm font-medium text-slate-700 group-hover:text-slate-900">
157
- Показывать уведомления на дашборде
158
- </span>
159
- </label>
160
- </div>
161
-
162
- {/* Types Section */}
163
- <div className="pt-8 border-t border-slate-200">
164
- <h3 className="font-semibold text-lg mb-4">Типы уведомлений</h3>
165
 
166
- <label className="flex items-center gap-3 cursor-pointer group">
167
- <input
168
- type="checkbox"
169
- checked={settings.notify_hot_leads}
170
- onChange={(e) => setSettings({ ...settings, notify_hot_leads: e.target.checked })}
171
- className="w-5 h-5 text-indigo-600 rounded border-slate-300 focus:ring-2 focus:ring-indigo-500"
172
- />
173
- <span className="text-sm font-medium text-slate-700 group-hover:text-slate-900 flex items-center gap-2">
174
- 🔥 Горячие лиды
175
- <span className="text-xs bg-emerald-100 text-emerald-700 px-2 py-0.5 rounded-full font-bold">
176
- Рекомендуется
177
- </span>
178
- </span>
179
- </label>
180
- <p className="text-xs text-slate-500 ml-8 mt-1">
181
- Уведомление когда лид готов к покупке (Heat Score ≥ 70)
182
- </p>
183
  </div>
184
-
185
- {/* Save Button */}
186
- <div className="pt-8">
187
- <motion.button
188
- onClick={handleSave}
189
- disabled={saving || !settings.telegram_chat_id}
190
- whileTap={{ scale: 0.98 }}
191
- className="w-full px-6 py-4 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-semibold transition-all flex items-center justify-center gap-3 disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-indigo-600/20 hover:shadow-xl hover:shadow-indigo-600/30"
192
- >
193
- <Save className="w-5 h-5" />
194
- {saving ? 'Сохранение...' : saveSuccess ? '✓ Сохранено!' : 'Сохранить настройки'}
195
- </motion.button>
196
-
197
- {!settings.telegram_chat_id && (
198
- <p className="text-xs text-amber-600 mt-3 text-center">
199
- ⚠️ Введите Chat ID для активации Telegram уведомлений
200
- </p>
 
201
  )}
202
- </div>
203
  </div>
204
  </div>
205
  )
 
1
  'use client'
2
 
3
  import { useState, useEffect } from 'react'
4
+ import { Card } from '@/components/ui/card'
5
+ import { Button } from '@/components/ui/button'
6
+ import { Input } from '@/components/ui/input'
7
+ import { Switch } from '@/components/ui/switch'
8
+ import { Label } from '@/components/ui/label'
9
+ import { Bell, Send, AlertCircle, CheckCircle2, Bot } from 'lucide-react'
10
+ import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
11
+ import { useAuth } from '@/contexts/AuthContext'
12
+ import { toast } from 'sonner' // Assuming sonner is used, or alert
13
+
14
+ export default function NotificationSettingsPage() {
15
+ const { user } = useAuth()
16
  const [loading, setLoading] = useState(true)
17
  const [saving, setSaving] = useState(false)
 
18
 
19
+ // Form State
20
+ // const [botToken, setBotToken] = useState('') // Removed - using global bot
21
+ const [chatId, setChatId] = useState('')
22
+ const [notifyOrder, setNotifyOrder] = useState(true)
23
+ const [notifyBooking, setNotifyBooking] = useState(true)
24
+ const [notifyLeads, setNotifyLeads] = useState(true)
25
+
26
+ // Load Settings
27
  useEffect(() => {
28
  fetchSettings()
29
  }, [])
 
31
  const fetchSettings = async () => {
32
  try {
33
  const token = localStorage.getItem('auth_token')
34
+ const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/tenants/me`, {
35
  headers: { 'Authorization': `Bearer ${token}` }
36
  })
37
+ const data = await res.json()
38
+
39
+ // Populate state
40
+ // setBotToken(data.telegram_bot_token || '')
41
+
42
+ const notif = data.notification_settings || {}
43
+ setChatId(notif.telegram_chat_id || '')
44
+ setNotifyOrder(notif.notify_on_order !== false)
45
+ setNotifyBooking(notif.notify_on_booking !== false)
46
+ setNotifyLeads(notif.notify_on_lead_heat !== false)
47
+ } catch (err) {
48
+ console.error(err)
49
+ // toast.error('Failed to load settings')
50
  } finally {
51
  setLoading(false)
52
  }
53
  }
54
 
55
  const handleSave = async () => {
56
+ setSaving(true)
57
  try {
 
58
  const token = localStorage.getItem('auth_token')
59
+
60
+ // Construct payload
61
+ const payload = {
62
+ // telegram_bot_token: botToken, // Removed - users don't manage bot token
63
+ notification_settings: {
64
+ telegram_chat_id: chatId,
65
+ notify_on_order: notifyOrder,
66
+ notify_on_booking: notifyBooking,
67
+ notify_on_lead_heat: notifyLeads
68
+ }
69
+ }
70
+
71
+ const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/tenants/me`, {
72
+ method: 'PATCH',
73
  headers: {
74
  'Authorization': `Bearer ${token}`,
75
  'Content-Type': 'application/json'
76
  },
77
+ body: JSON.stringify(payload)
78
  })
79
+
80
+ if (!res.ok) throw new Error('Failed to update')
81
+
82
+ // toast.success('Settings saved!')
83
+ alert('Настройки сохранены!')
84
+ } catch (err) {
85
+ console.error(err)
86
  alert('Ошибка сохранения')
87
  } finally {
88
  setSaving(false)
89
  }
90
  }
91
 
92
+ if (loading) return <div className="p-8">Загрузка...</div>
 
 
 
 
 
 
93
 
94
  return (
95
+ <div className="max-w-4xl mx-auto p-6 space-y-8">
96
+ <div>
97
+ <h1 className="text-2xl font-bold text-slate-900">Уведомления</h1>
98
+ <p className="text-slate-500">Настройте, куда присылать важные оповещения (Заказы, Записи, Лиды).</p>
 
 
99
  </div>
100
 
101
+ {/* Telegram Integration Card */}
102
+ <Card className="p-6 space-y-6">
103
+ <div className="flex items-center gap-3 border-b border-slate-100 pb-4">
104
+ <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center text-blue-600">
105
+ <Send className="w-6 h-6" />
106
+ </div>
107
+ <div>
108
+ <h2 className="text-lg font-semibold text-slate-900">Telegram Уведомления</h2>
109
+ <p className="text-sm text-slate-500">Получайте важные события прямо в Telegram</p>
110
+ </div>
111
  </div>
 
112
 
113
+ <Alert className="bg-blue-50 border-blue-200">
114
+ <Bot className="h-4 w-4 text-blue-600" />
115
+ <AlertTitle className="text-blue-800">Как подключить?</AlertTitle>
116
+ <AlertDescription className="text-blue-700 text-sm mt-2 space-y-1">
117
+ <p>1. Откройте нашего бота: <a href="https://t.me/stryeccjgjbot" target="_blank" className="underline font-medium">@stryeccjgjbot</a></p>
118
+ <p>2. Нажмите <b>Start</b>.</p>
119
+ <p>3. Скопируйте ваш ID (бот пришлет его) и вставьте ниже.</p>
120
+ </AlertDescription>
121
+ </Alert>
122
+
123
+ <div className="grid gap-6 md:grid-cols-2">
124
+ <div className="space-y-2">
125
+ <Label>Chat ID (Ваш Telegram ID)</Label>
126
+ <Input
127
+ placeholder="Например: 12345678"
128
+ value={chatId}
129
+ onChange={(e) => setChatId(e.target.value)}
130
+ />
131
+ <p className="text-[10px] text-slate-400">Сюда будут приходить уведомления</p>
132
  </div>
133
+ </div>
134
+ </Card>
135
 
136
+ {/* Notification Preferences */}
137
+ <Card className="p-6 space-y-6">
138
+ <div className="flex items-center gap-3 border-b border-slate-100 pb-4">
139
+ <div className="w-10 h-10 bg-indigo-100 rounded-lg flex items-center justify-center text-indigo-600">
140
+ <Bell className="w-6 h-6" />
141
+ </div>
142
+ <div>
143
+ <h2 className="text-lg font-semibold text-slate-900">Настройки Оповещений</h2>
144
+ <p className="text-sm text-slate-500">Выберите, о каких событиях уведомлять</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  </div>
146
  </div>
147
 
148
+ <div className="space-y-4">
149
+ <div className="flex items-center justify-between p-4 bg-slate-50 rounded-xl">
150
+ <div className="flex items-center gap-3">
151
+ <div className="p-2 bg-white rounded-lg shadow-sm">🛍️</div>
152
+ <div>
153
+ <p className="font-medium text-slate-900">Новые Заказы</p>
154
+ <p className="text-xs text-slate-500">Уведомлять о создании нового заказа</p>
155
+ </div>
 
156
  </div>
157
+ <Switch checked={notifyOrder} onCheckedChange={setNotifyOrder} />
158
  </div>
159
 
160
+ <div className="flex items-center justify-between p-4 bg-slate-50 rounded-xl">
161
+ <div className="flex items-center gap-3">
162
+ <div className="p-2 bg-white rounded-lg shadow-sm">📅</div>
163
+ <div>
164
+ <p className="font-medium text-slate-900">Новые Записи</p>
165
+ <p className="text-xs text-slate-500">Уведомлять о подтвержденных бронированиях</p>
166
+ </div>
167
+ </div>
168
+ <Switch checked={notifyBooking} onCheckedChange={setNotifyBooking} />
169
+ </div>
 
 
 
 
 
 
170
 
171
+ <div className="flex items-center justify-between p-4 bg-slate-50 rounded-xl">
172
+ <div className="flex items-center gap-3">
173
+ <div className="p-2 bg-white rounded-lg shadow-sm">🔥</div>
174
+ <div>
175
+ <p className="font-medium text-slate-900">Горячие Лиды</p>
176
+ <p className="text-xs text-slate-500">Уведомлять при высоком Heat Score</p>
177
+ </div>
178
+ </div>
179
+ <Switch checked={notifyLeads} onCheckedChange={setNotifyLeads} />
180
+ </div>
 
 
 
 
 
 
 
181
  </div>
182
+ </Card>
183
+
184
+ <div className="flex justify-end">
185
+ <Button
186
+ onClick={handleSave}
187
+ disabled={saving}
188
+ className="bg-indigo-600 hover:bg-indigo-700 text-white min-w-[150px]"
189
+ >
190
+ {saving ? (
191
+ <>
192
+ <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin mr-2" />
193
+ Сохранение...
194
+ </>
195
+ ) : (
196
+ <>
197
+ <CheckCircle2 className="w-4 h-4 mr-2" />
198
+ Сохранить Настройки
199
+ </>
200
  )}
201
+ </Button>
202
  </div>
203
  </div>
204
  )
frontend/components/Sidebar.tsx CHANGED
@@ -253,6 +253,16 @@ export function Sidebar() {
253
  <span>Команда</span>
254
  </Link>
255
 
 
 
 
 
 
 
 
 
 
 
256
 
257
 
258
  <Link href="/settings/billing" className={cn(
 
253
  <span>Команда</span>
254
  </Link>
255
 
256
+ <Link href="/settings/notifications" className={cn(
257
+ "flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
258
+ isActive('/settings/notifications')
259
+ ? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
260
+ : "text-white/80 hover:text-white hover:bg-white/5"
261
+ )}>
262
+ <Bell className={cn("w-5 h-5 transition-colors", isActive('/settings/notifications') ? "text-white" : "text-white/70 group-hover:text-indigo-400")} />
263
+ <span>Уведомления</span>
264
+ </Link>
265
+
266
 
267
 
268
  <Link href="/settings/billing" className={cn(