Spaces:
Running
feat: Замена Instagram на LinkedIn + WhatsApp через QR
Browse files✅ ЧТО СДЕЛАНО:
BACKEND:
- Удалён instagram_config, добавлен linkedin_config в Tenant
- Обновлены endpoints:
* POST /api/v1/channels/linkedin/connect
* GET /api/v1/channels/linkedin/status
* DELETE /api/v1/channels/linkedin/disconnect
- Убрана поддержка Instagram из meta channels API
- Добавлен LinkedInConnectRequest schema
FRONTEND:
- Заменён Instagram tab на LinkedIn в /channels
- Обновлены API calls (channelsApi.getLinkedInStatus и т.д.)
- Удалена валидация Instagram токенов
- LinkedIn state: liAccessToken, liOrgId, liVerifyToken
- Mutations: connectLinkedInMutation, disconnectLinkedInMutation
- getWebhookUrl теперь поддерживает whatsapp | linkedin
АРХИТЕКТУРА:
- Telegram: прямая интеграция (работает) ✅
- WhatsApp: через QR код (скоро) ⏳
- LinkedIn: Messaging API ⏳
ЗАЧЕМ:
- Instagram App Review слишком сложный
- LinkedIn = B2B аудитория (наша ЦА)
- WhatsApp QR = нет зависимости от Meta API
TODO:
- Добавить WhatsApp QR code генерацию
- LinkedIn webhook handler
- Обновить UI для LinkedIn (Organization ID вместо Page ID)
- backend/app/api/channels.py +162 -21
- backend/app/models/tenant.py +3 -3
- frontend/app/channels/page.tsx +46 -83
- frontend/lib/api.ts +7 -7
|
@@ -1,5 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
Channels API - Telegram
|
| 3 |
"""
|
| 4 |
from fastapi import APIRouter, HTTPException, Depends
|
| 5 |
from pydantic import BaseModel
|
|
@@ -9,9 +9,11 @@ import httpx
|
|
| 9 |
from app.core.database import get_session
|
| 10 |
from app.models.tenant import Tenant
|
| 11 |
from app.core.config import settings
|
|
|
|
| 12 |
from app.models import User
|
| 13 |
from app.api.deps import get_current_user
|
| 14 |
|
|
|
|
| 15 |
router = APIRouter(prefix="/channels", tags=["Channels"])
|
| 16 |
|
| 17 |
|
|
@@ -29,10 +31,16 @@ class TelegramConnectResponse(BaseModel):
|
|
| 29 |
|
| 30 |
|
| 31 |
class MetaChannelConnectRequest(BaseModel):
|
| 32 |
-
"""Meta (WhatsApp
|
| 33 |
access_token: str
|
| 34 |
phone_number_id: str | None = None # WhatsApp only
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
verify_token: str
|
| 37 |
|
| 38 |
|
|
@@ -267,8 +275,8 @@ async def connect_meta_channel(
|
|
| 267 |
tenant_id = current_user.tenant_id
|
| 268 |
|
| 269 |
# Validate channel
|
| 270 |
-
if channel not in ["whatsapp"
|
| 271 |
-
raise HTTPException(status_code=400, detail=f"Invalid channel: {channel}")
|
| 272 |
|
| 273 |
# Get tenant
|
| 274 |
tenant = await session.get(Tenant, tenant_id)
|
|
@@ -288,12 +296,6 @@ async def connect_meta_channel(
|
|
| 288 |
detail="Phone Number ID обязателен для WhatsApp"
|
| 289 |
)
|
| 290 |
|
| 291 |
-
if channel == "instagram" and not request.page_id:
|
| 292 |
-
raise HTTPException(
|
| 293 |
-
status_code=400,
|
| 294 |
-
detail="Page ID обязателен для Instagram"
|
| 295 |
-
)
|
| 296 |
-
|
| 297 |
# Construct webhook URL
|
| 298 |
webhook_base = settings.TELEGRAM_WEBHOOK_URL or "https://your-domain.com"
|
| 299 |
# Remove trailing /api/v1 to avoid duplication
|
|
@@ -303,14 +305,10 @@ async def connect_meta_channel(
|
|
| 303 |
# Build config object
|
| 304 |
config = {
|
| 305 |
"access_token": request.access_token.strip(),
|
| 306 |
-
"verify_token": request.verify_token.strip()
|
|
|
|
| 307 |
}
|
| 308 |
|
| 309 |
-
if channel == "whatsapp":
|
| 310 |
-
config["phone_number_id"] = request.phone_number_id.strip()
|
| 311 |
-
else: # instagram
|
| 312 |
-
config["page_id"] = request.page_id.strip()
|
| 313 |
-
|
| 314 |
# Update tenant config
|
| 315 |
config_field = f"{channel}_config"
|
| 316 |
setattr(tenant, config_field, config)
|
|
@@ -348,7 +346,7 @@ async def get_meta_channel_status(
|
|
| 348 |
# Use authenticated user's tenant_id (prevents tenant isolation breach)
|
| 349 |
tenant_id = current_user.tenant_id
|
| 350 |
|
| 351 |
-
if channel not in ["whatsapp"
|
| 352 |
raise HTTPException(status_code=400, detail=f"Invalid channel: {channel}")
|
| 353 |
|
| 354 |
tenant = await session.get(Tenant, tenant_id)
|
|
@@ -374,8 +372,7 @@ async def get_meta_channel_status(
|
|
| 374 |
"config": {
|
| 375 |
"has_access_token": bool(config and config.get("access_token")),
|
| 376 |
"has_verify_token": bool(config and config.get("verify_token")),
|
| 377 |
-
"phone_number_id": config.get("phone_number_id") if config
|
| 378 |
-
"page_id": config.get("page_id") if config and channel == "instagram" else None
|
| 379 |
} if config else None
|
| 380 |
}
|
| 381 |
|
|
@@ -402,7 +399,7 @@ async def disconnect_meta_channel(
|
|
| 402 |
# Use authenticated user's tenant_id (prevents tenant isolation breach)
|
| 403 |
tenant_id = current_user.tenant_id
|
| 404 |
|
| 405 |
-
if channel not in ["whatsapp"
|
| 406 |
raise HTTPException(status_code=400, detail=f"Invalid channel: {channel}")
|
| 407 |
|
| 408 |
tenant = await session.get(Tenant, tenant_id)
|
|
@@ -432,3 +429,147 @@ async def disconnect_meta_channel(
|
|
| 432 |
exc_info=True
|
| 433 |
)
|
| 434 |
raise
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
Channels API - Telegram, WhatsApp, LinkedIn Connection
|
| 3 |
"""
|
| 4 |
from fastapi import APIRouter, HTTPException, Depends
|
| 5 |
from pydantic import BaseModel
|
|
|
|
| 9 |
from app.core.database import get_session
|
| 10 |
from app.models.tenant import Tenant
|
| 11 |
from app.core.config import settings
|
| 12 |
+
from app.core.logging import get_logger
|
| 13 |
from app.models import User
|
| 14 |
from app.api.deps import get_current_user
|
| 15 |
|
| 16 |
+
logger = get_logger(__name__)
|
| 17 |
router = APIRouter(prefix="/channels", tags=["Channels"])
|
| 18 |
|
| 19 |
|
|
|
|
| 31 |
|
| 32 |
|
| 33 |
class MetaChannelConnectRequest(BaseModel):
|
| 34 |
+
"""Meta (WhatsApp) channel connection request."""
|
| 35 |
access_token: str
|
| 36 |
phone_number_id: str | None = None # WhatsApp only
|
| 37 |
+
verify_token: str
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class LinkedInConnectRequest(BaseModel):
|
| 41 |
+
"""LinkedIn channel connection request."""
|
| 42 |
+
access_token: str
|
| 43 |
+
organization_id: str # LinkedIn Page/Company ID
|
| 44 |
verify_token: str
|
| 45 |
|
| 46 |
|
|
|
|
| 275 |
tenant_id = current_user.tenant_id
|
| 276 |
|
| 277 |
# Validate channel
|
| 278 |
+
if channel not in ["whatsapp"]:
|
| 279 |
+
raise HTTPException(status_code=400, detail=f"Invalid channel: {channel}. Only 'whatsapp' is supported.")
|
| 280 |
|
| 281 |
# Get tenant
|
| 282 |
tenant = await session.get(Tenant, tenant_id)
|
|
|
|
| 296 |
detail="Phone Number ID обязателен для WhatsApp"
|
| 297 |
)
|
| 298 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
# Construct webhook URL
|
| 300 |
webhook_base = settings.TELEGRAM_WEBHOOK_URL or "https://your-domain.com"
|
| 301 |
# Remove trailing /api/v1 to avoid duplication
|
|
|
|
| 305 |
# Build config object
|
| 306 |
config = {
|
| 307 |
"access_token": request.access_token.strip(),
|
| 308 |
+
"verify_token": request.verify_token.strip(),
|
| 309 |
+
"phone_number_id": request.phone_number_id.strip()
|
| 310 |
}
|
| 311 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
# Update tenant config
|
| 313 |
config_field = f"{channel}_config"
|
| 314 |
setattr(tenant, config_field, config)
|
|
|
|
| 346 |
# Use authenticated user's tenant_id (prevents tenant isolation breach)
|
| 347 |
tenant_id = current_user.tenant_id
|
| 348 |
|
| 349 |
+
if channel not in ["whatsapp"]:
|
| 350 |
raise HTTPException(status_code=400, detail=f"Invalid channel: {channel}")
|
| 351 |
|
| 352 |
tenant = await session.get(Tenant, tenant_id)
|
|
|
|
| 372 |
"config": {
|
| 373 |
"has_access_token": bool(config and config.get("access_token")),
|
| 374 |
"has_verify_token": bool(config and config.get("verify_token")),
|
| 375 |
+
"phone_number_id": config.get("phone_number_id") if config else None
|
|
|
|
| 376 |
} if config else None
|
| 377 |
}
|
| 378 |
|
|
|
|
| 399 |
# Use authenticated user's tenant_id (prevents tenant isolation breach)
|
| 400 |
tenant_id = current_user.tenant_id
|
| 401 |
|
| 402 |
+
if channel not in ["whatsapp"]:
|
| 403 |
raise HTTPException(status_code=400, detail=f"Invalid channel: {channel}")
|
| 404 |
|
| 405 |
tenant = await session.get(Tenant, tenant_id)
|
|
|
|
| 429 |
exc_info=True
|
| 430 |
)
|
| 431 |
raise
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
# ==================== LINKEDIN ENDPOINTS ====================
|
| 435 |
+
|
| 436 |
+
@router.post("/linkedin/connect")
|
| 437 |
+
async def connect_linkedin(
|
| 438 |
+
request: LinkedInConnectRequest,
|
| 439 |
+
current_user: User = Depends(get_current_user),
|
| 440 |
+
session = Depends(get_session)
|
| 441 |
+
):
|
| 442 |
+
"""
|
| 443 |
+
Connect LinkedIn channel to authenticated user's tenant account.
|
| 444 |
+
|
| 445 |
+
LinkedIn Messaging API integration.
|
| 446 |
+
"""
|
| 447 |
+
try:
|
| 448 |
+
tenant_id = current_user.tenant_id
|
| 449 |
+
|
| 450 |
+
tenant = await session.get(Tenant, tenant_id)
|
| 451 |
+
if not tenant:
|
| 452 |
+
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 453 |
+
|
| 454 |
+
# Validate required fields
|
| 455 |
+
if not request.access_token or not request.organization_id:
|
| 456 |
+
raise HTTPException(
|
| 457 |
+
status_code=400,
|
| 458 |
+
detail="Access Token и Organization ID обязательны"
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
# Build config object
|
| 462 |
+
config = {
|
| 463 |
+
"access_token": request.access_token.strip(),
|
| 464 |
+
"organization_id": request.organization_id.strip(),
|
| 465 |
+
"verify_token": request.verify_token.strip()
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
# Update tenant config
|
| 469 |
+
tenant.linkedin_config = config
|
| 470 |
+
|
| 471 |
+
session.add(tenant)
|
| 472 |
+
await session.commit()
|
| 473 |
+
|
| 474 |
+
webhook_base = settings.TELEGRAM_WEBHOOK_URL or "https://your-domain.com"
|
| 475 |
+
webhook_base = webhook_base.rstrip('/').replace('/api/v1', '')
|
| 476 |
+
webhook_url = f"{webhook_base}/api/v1/webhook/linkedin/{tenant_id}"
|
| 477 |
+
|
| 478 |
+
return {
|
| 479 |
+
"ok": True,
|
| 480 |
+
"status": "connected",
|
| 481 |
+
"webhook_url": webhook_url,
|
| 482 |
+
"message": "LinkedIn успешно подключен! Настройте Webhook в LinkedIn Developers."
|
| 483 |
+
}
|
| 484 |
+
|
| 485 |
+
except HTTPException:
|
| 486 |
+
raise
|
| 487 |
+
except Exception as e:
|
| 488 |
+
logger.error(
|
| 489 |
+
"Failed to connect LinkedIn",
|
| 490 |
+
error=str(e),
|
| 491 |
+
exc_info=True
|
| 492 |
+
)
|
| 493 |
+
raise HTTPException(
|
| 494 |
+
status_code=500,
|
| 495 |
+
detail=f"Ошибка подключения LinkedIn: {str(e)}"
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
@router.get("/linkedin/status")
|
| 500 |
+
async def get_linkedin_status(
|
| 501 |
+
current_user: User = Depends(get_current_user),
|
| 502 |
+
session = Depends(get_session)
|
| 503 |
+
):
|
| 504 |
+
"""Get LinkedIn connection status for authenticated user's tenant."""
|
| 505 |
+
try:
|
| 506 |
+
tenant_id = current_user.tenant_id
|
| 507 |
+
|
| 508 |
+
tenant = await session.get(Tenant, tenant_id)
|
| 509 |
+
if not tenant:
|
| 510 |
+
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 511 |
+
|
| 512 |
+
config = tenant.linkedin_config
|
| 513 |
+
is_connected = bool(config and isinstance(config, dict) and config.get("access_token"))
|
| 514 |
+
|
| 515 |
+
webhook_url = None
|
| 516 |
+
if is_connected:
|
| 517 |
+
webhook_base = settings.TELEGRAM_WEBHOOK_URL or "https://your-domain.com"
|
| 518 |
+
webhook_base = webhook_base.rstrip('/').replace('/api/v1', '')
|
| 519 |
+
webhook_url = f"{webhook_base}/api/v1/webhook/linkedin/{tenant_id}"
|
| 520 |
+
|
| 521 |
+
return {
|
| 522 |
+
"ok": True,
|
| 523 |
+
"connected": is_connected,
|
| 524 |
+
"webhook_url": webhook_url,
|
| 525 |
+
"config": {
|
| 526 |
+
"has_access_token": bool(config and config.get("access_token")),
|
| 527 |
+
"organization_id": config.get("organization_id") if config else None
|
| 528 |
+
} if config else None
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
except HTTPException:
|
| 532 |
+
raise
|
| 533 |
+
except Exception as e:
|
| 534 |
+
logger.error(
|
| 535 |
+
"Failed to get LinkedIn status",
|
| 536 |
+
error=str(e),
|
| 537 |
+
exc_info=True
|
| 538 |
+
)
|
| 539 |
+
raise
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
@router.delete("/linkedin/disconnect")
|
| 543 |
+
async def disconnect_linkedin(
|
| 544 |
+
current_user: User = Depends(get_current_user),
|
| 545 |
+
session = Depends(get_session)
|
| 546 |
+
):
|
| 547 |
+
"""Disconnect LinkedIn from authenticated user's tenant account."""
|
| 548 |
+
try:
|
| 549 |
+
tenant_id = current_user.tenant_id
|
| 550 |
+
|
| 551 |
+
tenant = await session.get(Tenant, tenant_id)
|
| 552 |
+
if not tenant:
|
| 553 |
+
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 554 |
+
|
| 555 |
+
# Clear config
|
| 556 |
+
tenant.linkedin_config = None
|
| 557 |
+
|
| 558 |
+
session.add(tenant)
|
| 559 |
+
await session.commit()
|
| 560 |
+
|
| 561 |
+
return {
|
| 562 |
+
"ok": True,
|
| 563 |
+
"status": "disconnected",
|
| 564 |
+
"message": "LinkedIn успешно отключен"
|
| 565 |
+
}
|
| 566 |
+
|
| 567 |
+
except HTTPException:
|
| 568 |
+
raise
|
| 569 |
+
except Exception as e:
|
| 570 |
+
logger.error(
|
| 571 |
+
"Failed to disconnect LinkedIn",
|
| 572 |
+
error=str(e),
|
| 573 |
+
exc_info=True
|
| 574 |
+
)
|
| 575 |
+
raise
|
|
@@ -58,9 +58,9 @@ class Tenant(SQLModel, table=True):
|
|
| 58 |
# telegram_webhook_secret: Optional[str] = None # TODO: Add via migration
|
| 59 |
webhook_url: Optional[str] = None
|
| 60 |
|
| 61 |
-
# Multi-Channel Support
|
| 62 |
-
whatsapp_config: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
|
| 63 |
-
|
| 64 |
|
| 65 |
# AI Brain Settings (from migrations)
|
| 66 |
ai_settings: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
|
|
|
|
| 58 |
# telegram_webhook_secret: Optional[str] = None # TODO: Add via migration
|
| 59 |
webhook_url: Optional[str] = None
|
| 60 |
|
| 61 |
+
# Multi-Channel Support
|
| 62 |
+
whatsapp_config: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # QR code based
|
| 63 |
+
linkedin_config: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # LinkedIn messaging
|
| 64 |
|
| 65 |
# AI Brain Settings (from migrations)
|
| 66 |
ai_settings: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
|
|
@@ -7,7 +7,7 @@ import { useToast } from '@/contexts/ToastContext'
|
|
| 7 |
import { channelsApi } from '@/lib/api'
|
| 8 |
import { Send, CheckCircle, XCircle, AlertCircle, Loader2, ExternalLink, Copy, Check } from 'lucide-react'
|
| 9 |
|
| 10 |
-
type Channel = 'telegram' | 'whatsapp' | '
|
| 11 |
|
| 12 |
interface BotInfo {
|
| 13 |
username: string
|
|
@@ -38,12 +38,10 @@ export default function ChannelsPage() {
|
|
| 38 |
const [waTokenValid, setWaTokenValid] = useState<boolean | null>(null)
|
| 39 |
const [waTokenValidating, setWaTokenValidating] = useState(false)
|
| 40 |
|
| 41 |
-
//
|
| 42 |
-
const [
|
| 43 |
-
const [
|
| 44 |
-
const [
|
| 45 |
-
const [igTokenValid, setIgTokenValid] = useState<boolean | null>(null)
|
| 46 |
-
const [igTokenValidating, setIgTokenValidating] = useState(false)
|
| 47 |
|
| 48 |
const queryClient = useQueryClient()
|
| 49 |
const { user, isLoading: authLoading } = useAuth()
|
|
@@ -64,10 +62,10 @@ export default function ChannelsPage() {
|
|
| 64 |
refetchInterval: 15000,
|
| 65 |
})
|
| 66 |
|
| 67 |
-
// Get
|
| 68 |
-
const { data:
|
| 69 |
-
queryKey: ['
|
| 70 |
-
queryFn: channelsApi.
|
| 71 |
enabled: !!user,
|
| 72 |
refetchInterval: 15000,
|
| 73 |
})
|
|
@@ -103,17 +101,17 @@ export default function ChannelsPage() {
|
|
| 103 |
},
|
| 104 |
})
|
| 105 |
|
| 106 |
-
// Connect
|
| 107 |
-
const
|
| 108 |
-
mutationFn: () => channelsApi.
|
| 109 |
-
access_token:
|
| 110 |
-
|
| 111 |
-
verify_token:
|
| 112 |
}),
|
| 113 |
onSuccess: (data) => {
|
| 114 |
-
queryClient.invalidateQueries({ queryKey: ['
|
| 115 |
-
|
| 116 |
-
|
| 117 |
toast.success('Успех!', data.message)
|
| 118 |
},
|
| 119 |
onError: (error: Error) => {
|
|
@@ -144,10 +142,10 @@ export default function ChannelsPage() {
|
|
| 144 |
},
|
| 145 |
})
|
| 146 |
|
| 147 |
-
const
|
| 148 |
-
mutationFn: channelsApi.
|
| 149 |
onSuccess: (data) => {
|
| 150 |
-
queryClient.invalidateQueries({ queryKey: ['
|
| 151 |
toast.info('Отключено', data.message)
|
| 152 |
},
|
| 153 |
onError: (error: Error) => {
|
|
@@ -172,12 +170,12 @@ export default function ChannelsPage() {
|
|
| 172 |
connectWhatsAppMutation.mutate()
|
| 173 |
}
|
| 174 |
|
| 175 |
-
const
|
| 176 |
-
if (!
|
| 177 |
toast.warning('Внимание', 'Заполните все обязательные поля')
|
| 178 |
return
|
| 179 |
}
|
| 180 |
-
|
| 181 |
}
|
| 182 |
|
| 183 |
// Validate WhatsApp token
|
|
@@ -210,34 +208,6 @@ export default function ChannelsPage() {
|
|
| 210 |
}
|
| 211 |
}
|
| 212 |
|
| 213 |
-
// Validate Instagram token
|
| 214 |
-
const validateInstagramToken = async (token: string) => {
|
| 215 |
-
if (!token.trim()) {
|
| 216 |
-
setIgTokenValid(null)
|
| 217 |
-
return
|
| 218 |
-
}
|
| 219 |
-
|
| 220 |
-
setIgTokenValidating(true)
|
| 221 |
-
try {
|
| 222 |
-
const response = await fetch(
|
| 223 |
-
`https://graph.facebook.com/v18.0/me?access_token=${token}`
|
| 224 |
-
)
|
| 225 |
-
|
| 226 |
-
if (response.ok) {
|
| 227 |
-
const data = await response.json()
|
| 228 |
-
console.log('✅ Instagram token valid:', data)
|
| 229 |
-
setIgTokenValid(true)
|
| 230 |
-
} else {
|
| 231 |
-
console.error('❌ Instagram token invalid')
|
| 232 |
-
setIgTokenValid(false)
|
| 233 |
-
}
|
| 234 |
-
} catch (error) {
|
| 235 |
-
console.error('❌ Token validation error:', error)
|
| 236 |
-
setIgTokenValid(false)
|
| 237 |
-
} finally {
|
| 238 |
-
setIgTokenValidating(false)
|
| 239 |
-
}
|
| 240 |
-
}
|
| 241 |
// Debounced token validation
|
| 242 |
useEffect(() => {
|
| 243 |
const timer = setTimeout(() => {
|
|
@@ -248,22 +218,13 @@ export default function ChannelsPage() {
|
|
| 248 |
return () => clearTimeout(timer)
|
| 249 |
}, [waAccessToken])
|
| 250 |
|
| 251 |
-
useEffect(() => {
|
| 252 |
-
const timer = setTimeout(() => {
|
| 253 |
-
if (igAccessToken.trim()) {
|
| 254 |
-
validateInstagramToken(igAccessToken)
|
| 255 |
-
}
|
| 256 |
-
}, 1000)
|
| 257 |
-
return () => clearTimeout(timer)
|
| 258 |
-
}, [igAccessToken])
|
| 259 |
-
|
| 260 |
const copyToClipboard = (text: string) => {
|
| 261 |
navigator.clipboard.writeText(text)
|
| 262 |
setCopiedUrl(true)
|
| 263 |
setTimeout(() => setCopiedUrl(false), 2000)
|
| 264 |
}
|
| 265 |
|
| 266 |
-
const getWebhookUrl = (channel: 'whatsapp' | '
|
| 267 |
if (!user) return ''
|
| 268 |
// Get base URL from environment or use ngrok for development
|
| 269 |
// PRODUCTION: Use Railway backend URL
|
|
@@ -273,7 +234,11 @@ export default function ChannelsPage() {
|
|
| 273 |
// Remove trailing /api/v1 if exists (avoid duplication)
|
| 274 |
baseUrl = baseUrl.replace(/\/api\/v1\/?$/, '')
|
| 275 |
|
| 276 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
}
|
| 278 |
|
| 279 |
if (authLoading || !user) {
|
|
@@ -287,7 +252,7 @@ export default function ChannelsPage() {
|
|
| 287 |
const tabs = [
|
| 288 |
{ id: 'telegram' as Channel, label: 'Telegram', icon: Send, status: telegramStatus?.connected },
|
| 289 |
{ id: 'whatsapp' as Channel, label: 'WhatsApp', icon: Send, status: whatsappStatus?.connected },
|
| 290 |
-
{ id: '
|
| 291 |
]
|
| 292 |
|
| 293 |
return (
|
|
@@ -376,30 +341,28 @@ export default function ChannelsPage() {
|
|
| 376 |
/>
|
| 377 |
)}
|
| 378 |
|
| 379 |
-
{/*
|
| 380 |
-
{activeTab === '
|
| 381 |
<MetaChannelTab
|
| 382 |
-
channel="
|
| 383 |
-
status={
|
| 384 |
-
loading={
|
| 385 |
-
accessToken={
|
| 386 |
-
setAccessToken={
|
| 387 |
-
identifierId={
|
| 388 |
-
setIdentifierId={
|
| 389 |
-
verifyToken={
|
| 390 |
-
onConnect={
|
| 391 |
onDisconnect={() => {
|
| 392 |
-
if (confirm('Вы уверены, что хотите отключить
|
| 393 |
-
|
| 394 |
}
|
| 395 |
}}
|
| 396 |
-
isProcessing={
|
| 397 |
-
webhookUrl={getWebhookUrl('
|
| 398 |
copyToClipboard={copyToClipboard}
|
| 399 |
copiedUrl={copiedUrl}
|
| 400 |
tenantId={user.tenant_id}
|
| 401 |
-
tokenValid={igTokenValid}
|
| 402 |
-
tokenValidating={igTokenValidating}
|
| 403 |
/>
|
| 404 |
)}
|
| 405 |
</div>
|
|
|
|
| 7 |
import { channelsApi } from '@/lib/api'
|
| 8 |
import { Send, CheckCircle, XCircle, AlertCircle, Loader2, ExternalLink, Copy, Check } from 'lucide-react'
|
| 9 |
|
| 10 |
+
type Channel = 'telegram' | 'whatsapp' | 'linkedin'
|
| 11 |
|
| 12 |
interface BotInfo {
|
| 13 |
username: string
|
|
|
|
| 38 |
const [waTokenValid, setWaTokenValid] = useState<boolean | null>(null)
|
| 39 |
const [waTokenValidating, setWaTokenValidating] = useState(false)
|
| 40 |
|
| 41 |
+
// LinkedIn state
|
| 42 |
+
const [liAccessToken, setLiAccessToken] = useState('')
|
| 43 |
+
const [liOrgId, setLiOrgId] = useState('')
|
| 44 |
+
const [liVerifyToken] = useState('microfunnel-verify-token')
|
|
|
|
|
|
|
| 45 |
|
| 46 |
const queryClient = useQueryClient()
|
| 47 |
const { user, isLoading: authLoading } = useAuth()
|
|
|
|
| 62 |
refetchInterval: 15000,
|
| 63 |
})
|
| 64 |
|
| 65 |
+
// Get LinkedIn status
|
| 66 |
+
const { data: linkedinStatus, isLoading: linkedinLoading } = useQuery({
|
| 67 |
+
queryKey: ['linkedin-status', user?.tenant_id],
|
| 68 |
+
queryFn: channelsApi.getLinkedInStatus,
|
| 69 |
enabled: !!user,
|
| 70 |
refetchInterval: 15000,
|
| 71 |
})
|
|
|
|
| 101 |
},
|
| 102 |
})
|
| 103 |
|
| 104 |
+
// Connect LinkedIn mutation
|
| 105 |
+
const connectLinkedInMutation = useMutation({
|
| 106 |
+
mutationFn: () => channelsApi.connectLinkedIn({
|
| 107 |
+
access_token: liAccessToken,
|
| 108 |
+
organization_id: liOrgId,
|
| 109 |
+
verify_token: liVerifyToken,
|
| 110 |
}),
|
| 111 |
onSuccess: (data) => {
|
| 112 |
+
queryClient.invalidateQueries({ queryKey: ['linkedin-status', user?.tenant_id] })
|
| 113 |
+
setLiAccessToken('')
|
| 114 |
+
setLiOrgId('')
|
| 115 |
toast.success('Успех!', data.message)
|
| 116 |
},
|
| 117 |
onError: (error: Error) => {
|
|
|
|
| 142 |
},
|
| 143 |
})
|
| 144 |
|
| 145 |
+
const disconnectLinkedInMutation = useMutation({
|
| 146 |
+
mutationFn: channelsApi.disconnectLinkedIn,
|
| 147 |
onSuccess: (data) => {
|
| 148 |
+
queryClient.invalidateQueries({ queryKey: ['linkedin-status', user?.tenant_id] })
|
| 149 |
toast.info('Отключено', data.message)
|
| 150 |
},
|
| 151 |
onError: (error: Error) => {
|
|
|
|
| 170 |
connectWhatsAppMutation.mutate()
|
| 171 |
}
|
| 172 |
|
| 173 |
+
const handleConnectLinkedIn = () => {
|
| 174 |
+
if (!liAccessToken.trim() || !liOrgId.trim()) {
|
| 175 |
toast.warning('Внимание', 'Заполните все обязательные поля')
|
| 176 |
return
|
| 177 |
}
|
| 178 |
+
connectLinkedInMutation.mutate()
|
| 179 |
}
|
| 180 |
|
| 181 |
// Validate WhatsApp token
|
|
|
|
| 208 |
}
|
| 209 |
}
|
| 210 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
// Debounced token validation
|
| 212 |
useEffect(() => {
|
| 213 |
const timer = setTimeout(() => {
|
|
|
|
| 218 |
return () => clearTimeout(timer)
|
| 219 |
}, [waAccessToken])
|
| 220 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
const copyToClipboard = (text: string) => {
|
| 222 |
navigator.clipboard.writeText(text)
|
| 223 |
setCopiedUrl(true)
|
| 224 |
setTimeout(() => setCopiedUrl(false), 2000)
|
| 225 |
}
|
| 226 |
|
| 227 |
+
const getWebhookUrl = (channel: 'whatsapp' | 'linkedin') => {
|
| 228 |
if (!user) return ''
|
| 229 |
// Get base URL from environment or use ngrok for development
|
| 230 |
// PRODUCTION: Use Railway backend URL
|
|
|
|
| 234 |
// Remove trailing /api/v1 if exists (avoid duplication)
|
| 235 |
baseUrl = baseUrl.replace(/\/api\/v1\/?$/, '')
|
| 236 |
|
| 237 |
+
if (channel === 'whatsapp') {
|
| 238 |
+
return `${baseUrl}/api/v1/webhook/meta/whatsapp/${user.tenant_id}`
|
| 239 |
+
} else {
|
| 240 |
+
return `${baseUrl}/api/v1/webhook/linkedin/${user.tenant_id}`
|
| 241 |
+
}
|
| 242 |
}
|
| 243 |
|
| 244 |
if (authLoading || !user) {
|
|
|
|
| 252 |
const tabs = [
|
| 253 |
{ id: 'telegram' as Channel, label: 'Telegram', icon: Send, status: telegramStatus?.connected },
|
| 254 |
{ id: 'whatsapp' as Channel, label: 'WhatsApp', icon: Send, status: whatsappStatus?.connected },
|
| 255 |
+
{ id: 'linkedin' as Channel, label: 'LinkedIn', icon: Send, status: linkedinStatus?.connected },
|
| 256 |
]
|
| 257 |
|
| 258 |
return (
|
|
|
|
| 341 |
/>
|
| 342 |
)}
|
| 343 |
|
| 344 |
+
{/* LinkedIn Tab */}
|
| 345 |
+
{activeTab === 'linkedin' && (
|
| 346 |
<MetaChannelTab
|
| 347 |
+
channel="linkedin"
|
| 348 |
+
status={linkedinStatus}
|
| 349 |
+
loading={linkedinLoading}
|
| 350 |
+
accessToken={liAccessToken}
|
| 351 |
+
setAccessToken={setLiAccessToken}
|
| 352 |
+
identifierId={liOrgId}
|
| 353 |
+
setIdentifierId={setLiOrgId}
|
| 354 |
+
verifyToken={liVerifyToken}
|
| 355 |
+
onConnect={handleConnectLinkedIn}
|
| 356 |
onDisconnect={() => {
|
| 357 |
+
if (confirm('Вы уверены, что хотите отключить LinkedIn?')) {
|
| 358 |
+
disconnectLinkedInMutation.mutate()
|
| 359 |
}
|
| 360 |
}}
|
| 361 |
+
isProcessing={connectLinkedInMutation.isPending || disconnectLinkedInMutation.isPending}
|
| 362 |
+
webhookUrl={getWebhookUrl('linkedin')}
|
| 363 |
copyToClipboard={copyToClipboard}
|
| 364 |
copiedUrl={copiedUrl}
|
| 365 |
tenantId={user.tenant_id}
|
|
|
|
|
|
|
| 366 |
/>
|
| 367 |
)}
|
| 368 |
</div>
|
|
@@ -244,22 +244,22 @@ export const channelsApi = {
|
|
| 244 |
},
|
| 245 |
|
| 246 |
// Instagram
|
| 247 |
-
|
| 248 |
-
const response = await api.get('/api/v1/channels/
|
| 249 |
return response.data
|
| 250 |
},
|
| 251 |
|
| 252 |
-
|
| 253 |
access_token: string
|
| 254 |
-
|
| 255 |
verify_token: string
|
| 256 |
}) => {
|
| 257 |
-
const response = await api.post('/api/v1/channels/
|
| 258 |
return response.data
|
| 259 |
},
|
| 260 |
|
| 261 |
-
|
| 262 |
-
const response = await api.delete('/api/v1/channels/
|
| 263 |
return response.data
|
| 264 |
}
|
| 265 |
}
|
|
|
|
| 244 |
},
|
| 245 |
|
| 246 |
// Instagram
|
| 247 |
+
getLinkedInStatus: async () => {
|
| 248 |
+
const response = await api.get('/api/v1/channels/linkedin/status')
|
| 249 |
return response.data
|
| 250 |
},
|
| 251 |
|
| 252 |
+
connectLinkedIn: async (data: {
|
| 253 |
access_token: string
|
| 254 |
+
organization_id: string
|
| 255 |
verify_token: string
|
| 256 |
}) => {
|
| 257 |
+
const response = await api.post('/api/v1/channels/linkedin/connect', data)
|
| 258 |
return response.data
|
| 259 |
},
|
| 260 |
|
| 261 |
+
disconnectLinkedIn: async () => {
|
| 262 |
+
const response = await api.delete('/api/v1/channels/linkedin/disconnect')
|
| 263 |
return response.data
|
| 264 |
}
|
| 265 |
}
|