Spaces:
Sleeping
Sleeping
axeronis commited on
Commit ·
6770e41
1
Parent(s): d3c6de4
feat: add group chat id support and global bot webhook
Browse files
backend/app/api/notifications.py
CHANGED
|
@@ -40,6 +40,7 @@ class UnreadCountResponse(BaseModel):
|
|
| 40 |
class NotificationSettingsResponse(BaseModel):
|
| 41 |
telegram_enabled: bool
|
| 42 |
telegram_chat_id: Optional[str]
|
|
|
|
| 43 |
dashboard_enabled: bool
|
| 44 |
notify_hot_leads: bool
|
| 45 |
notify_qualification_complete: bool
|
|
@@ -48,6 +49,7 @@ class NotificationSettingsResponse(BaseModel):
|
|
| 48 |
class UpdateNotificationSettingsRequest(BaseModel):
|
| 49 |
telegram_enabled: Optional[bool] = None
|
| 50 |
telegram_chat_id: Optional[str] = None
|
|
|
|
| 51 |
dashboard_enabled: Optional[bool] = None
|
| 52 |
notify_hot_leads: Optional[bool] = None
|
| 53 |
notify_qualification_complete: Optional[bool] = None
|
|
@@ -141,6 +143,160 @@ async def mark_all_notifications_read(
|
|
| 141 |
return {"success": True}
|
| 142 |
|
| 143 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
@router.get("/settings", response_model=NotificationSettingsResponse)
|
| 145 |
async def get_notification_settings(
|
| 146 |
session: AsyncSession = Depends(get_async_session),
|
|
|
|
| 40 |
class NotificationSettingsResponse(BaseModel):
|
| 41 |
telegram_enabled: bool
|
| 42 |
telegram_chat_id: Optional[str]
|
| 43 |
+
telegram_channel_id: Optional[str] # Added support for group ID
|
| 44 |
dashboard_enabled: bool
|
| 45 |
notify_hot_leads: bool
|
| 46 |
notify_qualification_complete: bool
|
|
|
|
| 49 |
class UpdateNotificationSettingsRequest(BaseModel):
|
| 50 |
telegram_enabled: Optional[bool] = None
|
| 51 |
telegram_chat_id: Optional[str] = None
|
| 52 |
+
telegram_channel_id: Optional[str] = None # Added support for group ID
|
| 53 |
dashboard_enabled: Optional[bool] = None
|
| 54 |
notify_hot_leads: Optional[bool] = None
|
| 55 |
notify_qualification_complete: Optional[bool] = None
|
|
|
|
| 143 |
return {"success": True}
|
| 144 |
|
| 145 |
|
| 146 |
+
@router.get("/settings", response_model=NotificationSettingsResponse)
|
| 147 |
+
async def get_notification_settings(
|
| 148 |
+
session: AsyncSession = Depends(get_async_session),
|
| 149 |
+
current_user: User = Depends(get_current_user)
|
| 150 |
+
):
|
| 151 |
+
"""Get notification settings."""
|
| 152 |
+
stmt = select(NotificationSettings).where(
|
| 153 |
+
NotificationSettings.tenant_id == current_user.tenant_id
|
| 154 |
+
)
|
| 155 |
+
result = await session.execute(stmt)
|
| 156 |
+
settings = result.scalar_one_or_none()
|
| 157 |
+
|
| 158 |
+
if not settings:
|
| 159 |
+
# Create default settings
|
| 160 |
+
settings = NotificationSettings(tenant_id=current_user.tenant_id)
|
| 161 |
+
session.add(settings)
|
| 162 |
+
await session.commit()
|
| 163 |
+
await session.refresh(settings)
|
| 164 |
+
|
| 165 |
+
return NotificationSettingsResponse(
|
| 166 |
+
telegram_enabled=settings.telegram_enabled,
|
| 167 |
+
telegram_chat_id=settings.telegram_chat_id,
|
| 168 |
+
telegram_channel_id=settings.telegram_channel_id, # Include group ID
|
| 169 |
+
dashboard_enabled=settings.dashboard_enabled,
|
| 170 |
+
notify_hot_leads=settings.notify_hot_leads,
|
| 171 |
+
notify_qualification_complete=settings.notify_qualification_complete
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
@router.put("/settings")
|
| 176 |
+
async def update_notification_settings(
|
| 177 |
+
request: UpdateNotificationSettingsRequest,
|
| 178 |
+
session: AsyncSession = Depends(get_async_session),
|
| 179 |
+
current_user: User = Depends(get_current_user)
|
| 180 |
+
):
|
| 181 |
+
"""Update notification settings."""
|
| 182 |
+
stmt = select(NotificationSettings).where(
|
| 183 |
+
NotificationSettings.tenant_id == current_user.tenant_id
|
| 184 |
+
)
|
| 185 |
+
result = await session.execute(stmt)
|
| 186 |
+
settings = result.scalar_one_or_none()
|
| 187 |
+
|
| 188 |
+
if not settings:
|
| 189 |
+
settings = NotificationSettings(tenant_id=current_user.tenant_id)
|
| 190 |
+
session.add(settings)
|
| 191 |
+
|
| 192 |
+
# Update fields
|
| 193 |
+
if request.telegram_enabled is not None:
|
| 194 |
+
settings.telegram_enabled = request.telegram_enabled
|
| 195 |
+
if request.telegram_chat_id is not None:
|
| 196 |
+
settings.telegram_chat_id = request.telegram_chat_id
|
| 197 |
+
if request.telegram_channel_id is not None:
|
| 198 |
+
settings.telegram_channel_id = request.telegram_channel_id
|
| 199 |
+
if request.dashboard_enabled is not None:
|
| 200 |
+
settings.dashboard_enabled = request.dashboard_enabled
|
| 201 |
+
if request.notify_hot_leads is not None:
|
| 202 |
+
settings.notify_hot_leads = request.notify_hot_leads
|
| 203 |
+
if request.notify_qualification_complete is not None:
|
| 204 |
+
settings.notify_qualification_complete = request.notify_qualification_complete
|
| 205 |
+
|
| 206 |
+
settings.updated_at = datetime.utcnow()
|
| 207 |
+
await session.commit()
|
| 208 |
+
|
| 209 |
+
return {"success": True}
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
# ============================================================================
|
| 213 |
+
# Endpoints
|
| 214 |
+
# ============================================================================
|
| 215 |
+
|
| 216 |
+
@router.get("/unread-count", response_model=UnreadCountResponse)
|
| 217 |
+
async def get_unread_count(
|
| 218 |
+
session: AsyncSession = Depends(get_async_session),
|
| 219 |
+
current_user: User = Depends(get_current_user)
|
| 220 |
+
):
|
| 221 |
+
"""Get count of unread notifications."""
|
| 222 |
+
stmt = select(func.count(Notification.id)).where(
|
| 223 |
+
Notification.tenant_id == current_user.tenant_id,
|
| 224 |
+
Notification.is_read == False
|
| 225 |
+
)
|
| 226 |
+
count = await session.scalar(stmt)
|
| 227 |
+
|
| 228 |
+
return UnreadCountResponse(unread_count=count or 0)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
@router.get("/", response_model=List[NotificationResponse])
|
| 232 |
+
async def get_notifications(
|
| 233 |
+
limit: int = 20,
|
| 234 |
+
session: AsyncSession = Depends(get_async_session),
|
| 235 |
+
current_user: User = Depends(get_current_user)
|
| 236 |
+
):
|
| 237 |
+
"""Get list of notifications (last 20)."""
|
| 238 |
+
stmt = select(Notification).where(
|
| 239 |
+
Notification.tenant_id == current_user.tenant_id
|
| 240 |
+
).order_by(Notification.created_at.desc()).limit(limit)
|
| 241 |
+
|
| 242 |
+
result = await session.execute(stmt)
|
| 243 |
+
notifications = result.scalars().all()
|
| 244 |
+
|
| 245 |
+
return [
|
| 246 |
+
NotificationResponse(
|
| 247 |
+
id=n.id,
|
| 248 |
+
type=n.type,
|
| 249 |
+
title=n.title,
|
| 250 |
+
message=n.message,
|
| 251 |
+
is_read=n.is_read,
|
| 252 |
+
created_at=n.created_at.isoformat(),
|
| 253 |
+
lead_id=n.lead_id
|
| 254 |
+
)
|
| 255 |
+
for n in notifications
|
| 256 |
+
]
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
@router.post("/{notification_id}/mark-read")
|
| 260 |
+
async def mark_notification_read(
|
| 261 |
+
notification_id: UUID,
|
| 262 |
+
session: AsyncSession = Depends(get_async_session),
|
| 263 |
+
current_user: User = Depends(get_current_user)
|
| 264 |
+
):
|
| 265 |
+
"""Mark notification as read."""
|
| 266 |
+
stmt = select(Notification).where(
|
| 267 |
+
Notification.id == notification_id,
|
| 268 |
+
Notification.tenant_id == current_user.tenant_id
|
| 269 |
+
)
|
| 270 |
+
result = await session.execute(stmt)
|
| 271 |
+
notification = result.scalar_one_or_none()
|
| 272 |
+
|
| 273 |
+
if not notification:
|
| 274 |
+
raise HTTPException(status_code=404, detail="Notification not found")
|
| 275 |
+
|
| 276 |
+
notification.is_read = True
|
| 277 |
+
notification.read_at = datetime.utcnow()
|
| 278 |
+
await session.commit()
|
| 279 |
+
|
| 280 |
+
return {"success": True}
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
@router.post("/mark-all-read")
|
| 284 |
+
async def mark_all_notifications_read(
|
| 285 |
+
session: AsyncSession = Depends(get_async_session),
|
| 286 |
+
current_user: User = Depends(get_current_user)
|
| 287 |
+
):
|
| 288 |
+
"""Mark all notifications as read."""
|
| 289 |
+
stmt = update(Notification).where(
|
| 290 |
+
Notification.tenant_id == current_user.tenant_id,
|
| 291 |
+
Notification.is_read == False
|
| 292 |
+
).values(is_read=True, read_at=datetime.utcnow())
|
| 293 |
+
|
| 294 |
+
await session.execute(stmt)
|
| 295 |
+
await session.commit()
|
| 296 |
+
|
| 297 |
+
return {"success": True}
|
| 298 |
+
|
| 299 |
+
|
| 300 |
@router.get("/settings", response_model=NotificationSettingsResponse)
|
| 301 |
async def get_notification_settings(
|
| 302 |
session: AsyncSession = Depends(get_async_session),
|
backend/app/api/telegram_webhook.py
CHANGED
|
@@ -22,6 +22,54 @@ logger = get_logger(__name__)
|
|
| 22 |
router = APIRouter(prefix="/webhook/telegram", tags=["Telegram Webhooks"])
|
| 23 |
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
@router.post("/{tenant_id}")
|
| 26 |
@limiter.limit("5/minute")
|
| 27 |
async def handle_telegram_webhook(
|
|
|
|
| 22 |
router = APIRouter(prefix="/webhook/telegram", tags=["Telegram Webhooks"])
|
| 23 |
|
| 24 |
|
| 25 |
+
@router.post("/global")
|
| 26 |
+
@limiter.limit("20/minute")
|
| 27 |
+
async def handle_global_telegram_webhook(
|
| 28 |
+
request: Request,
|
| 29 |
+
background_tasks: BackgroundTasks,
|
| 30 |
+
session: AsyncSession = Depends(get_async_session)
|
| 31 |
+
):
|
| 32 |
+
"""Handle incoming updates for the Global Notification Bot."""
|
| 33 |
+
try:
|
| 34 |
+
raw_body = await request.body()
|
| 35 |
+
import json
|
| 36 |
+
data = json.loads(raw_body)
|
| 37 |
+
except Exception:
|
| 38 |
+
return {"status": "ignored"}
|
| 39 |
+
|
| 40 |
+
logger.info(f"🚨 GLOBAL BOT WEBHOOK: body_preview={raw_body[:200]}")
|
| 41 |
+
|
| 42 |
+
# 1. Handle Group Addition
|
| 43 |
+
if "my_chat_member" in data:
|
| 44 |
+
my_chat_member = data["my_chat_member"]
|
| 45 |
+
chat = my_chat_member.get("chat", {})
|
| 46 |
+
new_status = my_chat_member.get("new_chat_member", {}).get("status")
|
| 47 |
+
chat_id = str(chat.get("id"))
|
| 48 |
+
|
| 49 |
+
if new_status in ["member", "administrator"]:
|
| 50 |
+
token = settings.TELEGRAM_NOTIFICATION_TOKEN
|
| 51 |
+
if token:
|
| 52 |
+
from app.services.telegram_service import telegram_service
|
| 53 |
+
msg = f"✅ <b>Бота добавили в группу!</b>\n\n🆔 Group ID: <code>{chat_id}</code>\n\nВставьте этот ID в поле 'Групповой чат' в настройках уведомлений."
|
| 54 |
+
background_tasks.add_task(telegram_service.send_message, token=token, chat_id=chat_id, text=msg)
|
| 55 |
+
return {"status": "ok"}
|
| 56 |
+
|
| 57 |
+
# 2. Handle /start for Personal ID
|
| 58 |
+
if "message" in data:
|
| 59 |
+
msg_data = data["message"]
|
| 60 |
+
text = msg_data.get("text", "")
|
| 61 |
+
chat_id = str(msg_data.get("chat", {}).get("id"))
|
| 62 |
+
|
| 63 |
+
if text and text.strip().lower().startswith("/start"):
|
| 64 |
+
token = settings.TELEGRAM_NOTIFICATION_TOKEN
|
| 65 |
+
if token:
|
| 66 |
+
from app.services.telegram_service import telegram_service
|
| 67 |
+
reply = f"✅ <b>Бот готов к работе!</b>\n\n🆔 Ваш Personal ID: <code>{chat_id}</code>\n\nВставьте этот ID в поле 'Личный чат' в настройках уведомлений."
|
| 68 |
+
background_tasks.add_task(telegram_service.send_message, token=token, chat_id=chat_id, text=reply)
|
| 69 |
+
|
| 70 |
+
return {"status": "ok"}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
@router.post("/{tenant_id}")
|
| 74 |
@limiter.limit("5/minute")
|
| 75 |
async def handle_telegram_webhook(
|
frontend/app/settings/notifications/page.tsx
CHANGED
|
@@ -191,52 +191,59 @@ export default function NotificationSettingsPage() {
|
|
| 191 |
</div>
|
| 192 |
|
| 193 |
{/* Chat ID Input (Personal Only) */}
|
| 194 |
-
<div className="mb-
|
| 195 |
<div className="flex gap-4">
|
| 196 |
<div className="flex-1">
|
| 197 |
<label className="block text-sm font-medium text-slate-400 mb-2">Ваш Личный ID (Private chat)</label>
|
| 198 |
-
<
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
</div>
|
| 206 |
</div>
|
| 207 |
<p className="text-xs text-slate-500 mt-2">
|
| 208 |
-
|
| 209 |
</p>
|
| 210 |
</div>
|
| 211 |
|
| 212 |
-
{/* Channel/Group ID Input
|
| 213 |
-
|
| 214 |
-
<div className="
|
| 215 |
-
<div className="flex
|
| 216 |
-
<
|
| 217 |
-
|
| 218 |
<input
|
| 219 |
type="text"
|
| 220 |
value={channelId}
|
| 221 |
onChange={(e) => setChannelId(e.target.value)}
|
| 222 |
placeholder="Например: -100123456789"
|
| 223 |
-
className="
|
| 224 |
/>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
</div>
|
| 226 |
</div>
|
| 227 |
-
<p className="text-xs text-slate-500 mt-2">
|
| 228 |
-
Общий чат для команды. Бот должен быть адми��истратором группы/канала.
|
| 229 |
-
</p>
|
| 230 |
</div>
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
<button
|
| 235 |
-
onClick={handleSave}
|
| 236 |
-
className="px-5 py-3 bg-blue-600 hover:bg-blue-500 text-white font-semibold rounded-xl transition-all"
|
| 237 |
-
>
|
| 238 |
-
{t('notifications.saveId')}
|
| 239 |
-
</button>
|
| 240 |
</div>
|
| 241 |
</motion.div>
|
| 242 |
|
|
|
|
| 191 |
</div>
|
| 192 |
|
| 193 |
{/* Chat ID Input (Personal Only) */}
|
| 194 |
+
<div className="mb-6 pb-6 border-b border-white/5">
|
| 195 |
<div className="flex gap-4">
|
| 196 |
<div className="flex-1">
|
| 197 |
<label className="block text-sm font-medium text-slate-400 mb-2">Ваш Личный ID (Private chat)</label>
|
| 198 |
+
<div className="flex gap-2">
|
| 199 |
+
<input
|
| 200 |
+
type="text"
|
| 201 |
+
value={chatId}
|
| 202 |
+
onChange={(e) => setChatId(e.target.value)}
|
| 203 |
+
placeholder="Например: 123456789"
|
| 204 |
+
className="flex-1 px-4 py-3 bg-white/5 border border-white/10 rounded-xl focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 text-white transition-all outline-none"
|
| 205 |
+
/>
|
| 206 |
+
<button
|
| 207 |
+
onClick={handleSave}
|
| 208 |
+
disabled={saving}
|
| 209 |
+
className="px-4 py-3 bg-white/5 hover:bg-white/10 text-white font-medium rounded-xl transition-all border border-white/10 whitespace-nowrap"
|
| 210 |
+
>
|
| 211 |
+
Сохранить
|
| 212 |
+
</button>
|
| 213 |
+
</div>
|
| 214 |
</div>
|
| 215 |
</div>
|
| 216 |
<p className="text-xs text-slate-500 mt-2">
|
| 217 |
+
Сюда будут приходить уведомления, адресованные лично вам.
|
| 218 |
</p>
|
| 219 |
</div>
|
| 220 |
|
| 221 |
+
{/* Channel/Group ID Input */}
|
| 222 |
+
<div>
|
| 223 |
+
<div className="flex gap-4">
|
| 224 |
+
<div className="flex-1">
|
| 225 |
+
<label className="block text-sm font-medium text-slate-400 mb-2">ID Группы или Канала (Team Chat)</label>
|
| 226 |
+
<div className="flex gap-2">
|
| 227 |
<input
|
| 228 |
type="text"
|
| 229 |
value={channelId}
|
| 230 |
onChange={(e) => setChannelId(e.target.value)}
|
| 231 |
placeholder="Например: -100123456789"
|
| 232 |
+
className="flex-1 px-4 py-3 bg-white/5 border border-white/10 rounded-xl focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 text-white transition-all outline-none"
|
| 233 |
/>
|
| 234 |
+
<button
|
| 235 |
+
onClick={handleSave}
|
| 236 |
+
disabled={saving}
|
| 237 |
+
className="px-4 py-3 bg-white/5 hover:bg-white/10 text-white font-medium rounded-xl transition-all border border-white/10 whitespace-nowrap"
|
| 238 |
+
>
|
| 239 |
+
Сохранить
|
| 240 |
+
</button>
|
| 241 |
</div>
|
| 242 |
</div>
|
|
|
|
|
|
|
|
|
|
| 243 |
</div>
|
| 244 |
+
<p className="text-xs text-slate-500 mt-2">
|
| 245 |
+
Общий чат для команды. Добавьте бота в группу, и он пришлет ID сюда.
|
| 246 |
+
</p>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
</div>
|
| 248 |
</motion.div>
|
| 249 |
|