361 lines
13 KiB
Python
361 lines
13 KiB
Python
import logging
|
|
from typing import Any, Dict, List, Optional
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
|
from pydantic import BaseModel, Field
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.database.db_session import get_db
|
|
from app.models.UserModel import User
|
|
from app.core.permissions.RoleChecker import get_current_user
|
|
from app.services.IntegrationService import IntegrationService
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
router = APIRouter(prefix="/api/v1/integrations", tags=["Integrations Hub"])
|
|
|
|
# ==============================================================================
|
|
# Pydantic Request Models
|
|
# ==============================================================================
|
|
|
|
class OpenWaTestSendRequest(BaseModel):
|
|
phone: str = Field(..., description="10 or 12 digit recipient phone number")
|
|
message: str = Field("Test verification message from iFixKart ERP", description="Text message")
|
|
|
|
class WatiCredentialsRequest(BaseModel):
|
|
api_endpoint: str = Field("https://live-mt-server.wati.io", description="WATI API base URL")
|
|
api_token: str = Field(..., description="WATI access token / API key")
|
|
|
|
class WatiTestRequest(BaseModel):
|
|
api_endpoint: str
|
|
api_token: str
|
|
|
|
class WatiSendTemplateRequest(BaseModel):
|
|
phone: str
|
|
template_name: str
|
|
broadcast_name: Optional[str] = None
|
|
parameters: Optional[List[Dict[str, Any]]] = None
|
|
|
|
class EmailCredentialsRequest(BaseModel):
|
|
provider: str = Field("SMTP", description="SMTP or ZeptoMail")
|
|
sender_email: str
|
|
sender_name: Optional[str] = "iFixKart"
|
|
smtp_server: Optional[str] = None
|
|
smtp_port: Optional[int] = 587
|
|
smtp_username: Optional[str] = None
|
|
smtp_password: Optional[str] = None
|
|
use_tls: Optional[bool] = True
|
|
|
|
class EmailTestRequest(BaseModel):
|
|
recipient: str
|
|
subject: Optional[str] = "iFixKart Email Verification"
|
|
body: Optional[str] = "This is a verified test email sent from iFixKart ERP."
|
|
|
|
class MetaCredentialsRequest(BaseModel):
|
|
app_id: Optional[str] = None
|
|
ad_account_id: Optional[str] = None
|
|
page_id: Optional[str] = None
|
|
instagram_id: Optional[str] = None
|
|
access_token: Optional[str] = None
|
|
|
|
class MetaTestRequest(BaseModel):
|
|
access_token: str
|
|
ad_account_id: Optional[str] = None
|
|
|
|
class KnowlarityCredentialsRequest(BaseModel):
|
|
api_key: str
|
|
authorization: str
|
|
virtual_number: Optional[str] = None
|
|
call_url: Optional[str] = "https://kpi.knowlarity.com/Basic/v1/account/call/makecall"
|
|
log_url: Optional[str] = "https://kpi.knowlarity.com/Basic/v1/account/calllog"
|
|
|
|
class KnowlarityCallRequest(BaseModel):
|
|
agent_number: str
|
|
customer_number: str
|
|
|
|
class ShiprocketCredentialsRequest(BaseModel):
|
|
email: str
|
|
pickup_location: Optional[str] = "Primary"
|
|
pickup_pin: Optional[str] = None
|
|
api_url: Optional[str] = "https://apiv2.shiprocket.in/v1/external"
|
|
token: Optional[str] = None
|
|
|
|
class ShiprocketAuthRequest(BaseModel):
|
|
email: str
|
|
password: str
|
|
|
|
class ShiprocketServiceabilityRequest(BaseModel):
|
|
pickup_pin: str
|
|
delivery_pin: str
|
|
weight: Optional[float] = 0.5
|
|
cod: Optional[bool] = False
|
|
|
|
# ==============================================================================
|
|
# 0. Overview
|
|
# ==============================================================================
|
|
|
|
@router.get("/overview")
|
|
def get_integrations_overview(
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
"""
|
|
Returns real-time status of all ERP integrations (WhatsApp OpenWA, WATI, Email, Meta, GA4, Knowlarity, Shiprocket).
|
|
"""
|
|
return IntegrationService.get_overview(db)
|
|
|
|
# ==============================================================================
|
|
# 1. Internal WhatsApp Gateway (OpenWA)
|
|
# ==============================================================================
|
|
|
|
@router.get("/whatsapp/qr")
|
|
def get_whatsapp_qr(
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
"""
|
|
Streams live QR code directly from OpenWA session for browser scanning.
|
|
"""
|
|
return IntegrationService.get_openwa_qr()
|
|
|
|
@router.post("/whatsapp/test-send")
|
|
def send_whatsapp_test_message(
|
|
payload: OpenWaTestSendRequest,
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
"""
|
|
Dispatches a real WhatsApp test message using OpenWA gateway.
|
|
"""
|
|
return IntegrationService.send_test_openwa_message(payload.phone, payload.message)
|
|
|
|
@router.post("/whatsapp/restart")
|
|
def restart_whatsapp_session(
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
"""
|
|
Restarts the OpenWA WhatsApp session to trigger a fresh QR code.
|
|
"""
|
|
return IntegrationService.restart_openwa_session()
|
|
|
|
# ==============================================================================
|
|
# 2. Customer WhatsApp (WATI Cloud API)
|
|
# ==============================================================================
|
|
|
|
@router.get("/wati/credentials")
|
|
def get_wati_credentials(
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
return IntegrationService.get_wati_credentials(db)
|
|
|
|
@router.put("/wati/credentials")
|
|
def save_wati_credentials(
|
|
payload: WatiCredentialsRequest,
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
creds = IntegrationService.get_wati_credentials(db)
|
|
if creds.get("is_locked_by_config"):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="WATI credentials are locked by Config.py / environment variables."
|
|
)
|
|
IntegrationService.save_wati_credentials(payload.model_dump(), db)
|
|
return {"status": "SUCCESS", "message": "WATI credentials saved successfully."}
|
|
|
|
@router.post("/wati/test")
|
|
def test_wati(
|
|
payload: WatiTestRequest,
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
return IntegrationService.test_wati_connection(payload.api_endpoint, payload.api_token)
|
|
|
|
@router.get("/wati/templates")
|
|
def get_wati_templates(
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
templates = IntegrationService.get_wati_templates(db)
|
|
return {"status": "SUCCESS", "templates": templates}
|
|
|
|
@router.post("/wati/send-template")
|
|
def send_wati_template(
|
|
payload: WatiSendTemplateRequest,
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
return IntegrationService.send_wati_template_message(
|
|
phone=payload.phone,
|
|
template_name=payload.template_name,
|
|
broadcast_name=payload.broadcast_name or "test_send",
|
|
parameters=payload.parameters or [],
|
|
db=db
|
|
)
|
|
|
|
# ==============================================================================
|
|
# 3. Transactional Email (ZeptoMail CPaaS & SMTP)
|
|
# ==============================================================================
|
|
|
|
@router.get("/email/credentials")
|
|
def get_email_credentials(
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
return IntegrationService.get_email_credentials(db)
|
|
|
|
@router.put("/email/credentials")
|
|
def save_email_credentials(
|
|
payload: EmailCredentialsRequest,
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
creds = IntegrationService.get_email_credentials(db)
|
|
if creds.get("is_locked_by_config"):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Email provider is configured via Config.py (ZeptoMail) and locked."
|
|
)
|
|
IntegrationService.save_email_credentials(payload.model_dump(), db)
|
|
return {"status": "SUCCESS", "message": "Email settings saved successfully."}
|
|
|
|
@router.post("/email/test")
|
|
def send_test_email(
|
|
payload: EmailTestRequest,
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
res = IntegrationService.send_test_email(payload.recipient, payload.subject, payload.body, db)
|
|
if res.get("status") == "FAILED":
|
|
raise HTTPException(status_code=400, detail=res.get("detail", "Failed to send email"))
|
|
return res
|
|
|
|
# ==============================================================================
|
|
# 4. Meta Ads & Graph API
|
|
# ==============================================================================
|
|
|
|
@router.get("/meta/credentials")
|
|
def get_meta_credentials(
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
return IntegrationService.get_meta_credentials(db)
|
|
|
|
@router.put("/meta/credentials")
|
|
def save_meta_credentials(
|
|
payload: MetaCredentialsRequest,
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
creds = IntegrationService.get_meta_credentials(db)
|
|
if creds.get("is_locked_by_config"):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Meta Graph credentials are locked by Config.py / environment variables."
|
|
)
|
|
IntegrationService.save_meta_credentials(payload.model_dump(), db)
|
|
return {"status": "SUCCESS", "message": "Meta credentials saved successfully."}
|
|
|
|
@router.post("/meta/test")
|
|
def test_meta(
|
|
payload: MetaTestRequest,
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
return IntegrationService.test_meta_connection(payload.access_token, payload.ad_account_id or "")
|
|
|
|
# ==============================================================================
|
|
# 5. Knowlarity Cloud Telephony (IVR / Call Routing)
|
|
# ==============================================================================
|
|
|
|
@router.get("/call/credentials")
|
|
def get_knowlarity_credentials(
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
return IntegrationService.get_knowlarity_credentials(db)
|
|
|
|
@router.put("/call/credentials")
|
|
def save_knowlarity_credentials(
|
|
payload: KnowlarityCredentialsRequest,
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
creds = IntegrationService.get_knowlarity_credentials(db)
|
|
if creds.get("is_locked_by_config"):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Knowlarity credentials are locked by Config.py / environment variables."
|
|
)
|
|
IntegrationService.save_knowlarity_credentials(payload.model_dump(), db)
|
|
return {"status": "SUCCESS", "message": "Knowlarity credentials saved successfully."}
|
|
|
|
@router.post("/call/make-call")
|
|
def make_knowlarity_call(
|
|
payload: KnowlarityCallRequest,
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
res = IntegrationService.knowlarity_make_call(payload.agent_number, payload.customer_number, db)
|
|
if res.get("status") == "FAILED":
|
|
raise HTTPException(status_code=400, detail=res.get("detail", "Call initiation failed"))
|
|
return res
|
|
|
|
@router.get("/call/logs")
|
|
def get_knowlarity_call_logs(
|
|
page: int = Query(1, ge=1),
|
|
limit: int = Query(20, ge=1, le=100),
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
return IntegrationService.knowlarity_get_call_logs(page, limit, db)
|
|
|
|
# ==============================================================================
|
|
# 6. Shiprocket Logistics
|
|
# ==============================================================================
|
|
|
|
@router.get("/shipping/credentials")
|
|
def get_shiprocket_credentials(
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
return IntegrationService.get_shiprocket_credentials(db)
|
|
|
|
@router.put("/shipping/credentials")
|
|
def save_shiprocket_credentials(
|
|
payload: ShiprocketCredentialsRequest,
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
creds = IntegrationService.get_shiprocket_credentials(db)
|
|
if creds.get("is_locked_by_config"):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Shiprocket credentials are locked by Config.py / environment variables."
|
|
)
|
|
IntegrationService.save_shiprocket_credentials(payload.model_dump(), db)
|
|
return {"status": "SUCCESS", "message": "Shiprocket credentials saved successfully."}
|
|
|
|
@router.post("/shipping/auth")
|
|
def test_shiprocket_auth(
|
|
payload: ShiprocketAuthRequest,
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
res = IntegrationService.test_shiprocket_auth(payload.email, payload.password, db)
|
|
if res.get("status") == "FAILED":
|
|
raise HTTPException(status_code=400, detail=res.get("detail", "Authentication failed"))
|
|
return res
|
|
|
|
@router.post("/shipping/serviceability")
|
|
def check_shipping_serviceability(
|
|
payload: ShiprocketServiceabilityRequest,
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
res = IntegrationService.check_shiprocket_serviceability(
|
|
pickup_pin=payload.pickup_pin,
|
|
delivery_pin=payload.delivery_pin,
|
|
weight=payload.weight or 0.5,
|
|
cod=payload.cod or False,
|
|
db=db
|
|
)
|
|
if res.get("status") == "FAILED":
|
|
raise HTTPException(status_code=400, detail=res.get("detail", "Serviceability check failed"))
|
|
return res
|