import os import json import logging import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from datetime import datetime, timezone from typing import Dict, Any, List, Optional import httpx from sqlalchemy.orm import Session from sqlalchemy import text from app.core.config.Config import settings from app.models.SettingModel import Setting import ulid logger = logging.getLogger(__name__) class IntegrationService: """ Central service for all third-party integrations in iFixKart ERP. Architectural rule: 1. Config.py is PRIMARY. If credentials exist in settings, they are used. 2. Database settings table is FALLBACK. If Config.py is missing/empty, DB is consulted. """ # --------------------------------------------------------- # Helper: Resolve settings (Config.py primary, DB fallback) # --------------------------------------------------------- @staticmethod def get_setting_from_db(db: Session, group: str, key: str) -> Optional[Any]: try: row = db.query(Setting).filter(Setting.setting_key == key, Setting.group == group).first() if row and row.setting_value is not None: return row.setting_value except Exception as e: logger.warning(f"Error reading DB setting {key} ({group}): {e}") return None @staticmethod def save_setting_to_db(db: Session, group: str, key: str, value: Any, description: str = ""): try: row = db.query(Setting).filter(Setting.setting_key == key, Setting.group == group).first() if row: row.setting_value = value row.description = description row.updated_at = datetime.now(timezone.utc) else: row = Setting( setting_id=str(ulid.ULID()), setting_key=key, group=group, type="json" if isinstance(value, (dict, list)) else "string", setting_value=value, description=description, is_public=False, is_editable=True ) db.add(row) db.commit() return True except Exception as e: db.rollback() logger.error(f"Error saving setting {key}: {e}") raise e # --------------------------------------------------------- # Overview of all integrations # --------------------------------------------------------- @staticmethod def get_overview(db: Session) -> Dict[str, Any]: """ Returns real-time status of all configured services. """ # 1. OpenWA (Internal WhatsApp) openwa_status = "Disconnected" openwa_phone = None openwa_push_name = None try: headers = {"X-Api-Key": settings.OPENWA_MASTER_KEY} with httpx.Client(timeout=3.0) as client: r = client.get(f"{settings.OPENWA_GATEWAY_URL}/api/sessions", headers=headers) if r.status_code == 200: sessions = r.json() if sessions and isinstance(sessions, list): default_s = next((s for s in sessions if s.get("name") == "default"), sessions[0]) raw_st = default_s.get("status", "") openwa_status = "QR_READY" if raw_st == "qr_ready" else ("Connected" if raw_st in ("connected", "authenticated") else raw_st.upper()) openwa_phone = default_s.get("phone") openwa_push_name = default_s.get("pushName") except Exception: openwa_status = "Gateway Offline" # 2. WATI (Customer WhatsApp) wati_creds = IntegrationService.get_wati_credentials(db) wati_connected = bool(wati_creds.get("api_token") and wati_creds.get("api_endpoint")) # 3. Email (ZeptoMail / SMTP) email_creds = IntegrationService.get_email_credentials(db) email_connected = bool(email_creds.get("active_provider") and email_creds.get("active_provider") != "None") # 4. Meta Ads meta_creds = IntegrationService.get_meta_credentials(db) meta_connected = bool(meta_creds.get("access_token") and meta_creds.get("ad_account_id")) # 5. Google Analytics 4 ga4_connected = bool(settings.GA4_ENABLED and settings.GA4_PROPERTY_ID) # 6. Knowlarity Telephony knowlarity_creds = IntegrationService.get_knowlarity_credentials(db) knowlarity_connected = bool(knowlarity_creds.get("api_key") or knowlarity_creds.get("authorization")) # 7. Shiprocket Logistics shiprocket_creds = IntegrationService.get_shiprocket_credentials(db) shiprocket_connected = bool(shiprocket_creds.get("email") or shiprocket_creds.get("token") or settings.SHIPROCKET_ENABLED) return { "whatsapp_internal": { "name": "Internal WhatsApp Gateway (OpenWA)", "channel": "Internal Staff & Operations", "status": openwa_status, "phone": openwa_phone, "push_name": openwa_push_name, "gateway_url": settings.OPENWA_GATEWAY_URL, "source": "config.py" }, "whatsapp_customer": { "name": "Customer WhatsApp (WATI Cloud API)", "channel": "Customer Marketing & Broadcasts", "status": "Connected" if wati_connected else "Pending Configuration", "source": wati_creds.get("source"), "endpoint": wati_creds.get("api_endpoint") }, "email": { "name": "Transactional Email (ZeptoMail & SMTP)", "provider": email_creds.get("active_provider", "ZeptoMail"), "status": "Connected" if email_connected else "Pending Configuration", "sender": email_creds.get("sender_email"), "source": email_creds.get("source") }, "meta_ads": { "name": "Meta Graph API & Ads (Facebook/Instagram)", "status": "Connected" if meta_connected else "Pending Configuration", "app_id": meta_creds.get("app_id"), "ad_account_id": meta_creds.get("ad_account_id"), "page_id": meta_creds.get("page_id"), "source": meta_creds.get("source") }, "google_analytics": { "name": "Google Analytics 4 (GA4)", "status": "Connected" if ga4_connected else "Disabled", "property_id": settings.GA4_PROPERTY_ID, "source": "config.py" }, "knowlarity": { "name": "Knowlarity Cloud Telephony (IVR / Calls)", "status": "Connected" if knowlarity_connected else "Pending Configuration", "virtual_number": knowlarity_creds.get("virtual_number"), "source": knowlarity_creds.get("source") }, "shiprocket": { "name": "Shiprocket Logistics & Delivery", "status": "Connected" if shiprocket_connected else "Pending Configuration", "source": shiprocket_creds.get("source"), "pickup_location": shiprocket_creds.get("pickup_location") } } # --------------------------------------------------------- # 1. Internal WhatsApp (OpenWA Gateway on Port 8088) # --------------------------------------------------------- @staticmethod def get_openwa_qr() -> Dict[str, Any]: """ Streams live QR code directly from OpenWA session for browser scanning. """ headers = {"X-Api-Key": settings.OPENWA_MASTER_KEY} with httpx.Client(timeout=8.0) as client: sess_res = client.get(f"{settings.OPENWA_GATEWAY_URL}/api/sessions", headers=headers) if sess_res.status_code != 200: return {"status": "OFFLINE", "message": "OpenWA gateway is offline"} sessions = sess_res.json() if not sessions: return {"status": "NO_SESSION", "message": "No OpenWA sessions found"} default_s = next((s for s in sessions if s.get("name") == "default"), sessions[0]) sess_id = default_s.get("id") raw_status = default_s.get("status", "") if raw_status in ("connected", "authenticated"): return { "status": "CONNECTED", "session_id": sess_id, "phone": default_s.get("phone"), "push_name": default_s.get("pushName"), "connected_at": default_s.get("connectedAt"), "qr_code": None } qr_res = client.get(f"{settings.OPENWA_GATEWAY_URL}/api/sessions/{sess_id}/qr", headers=headers) if qr_res.status_code == 200: qr_data = qr_res.json() qr_str = qr_data.get("qrCode") or qr_data.get("qr_code_base64") return { "status": "QR_READY", "session_id": sess_id, "qr_code": qr_str, "phone": default_s.get("phone"), "push_name": default_s.get("pushName") } return { "status": raw_status.upper() or "INITIALIZING", "session_id": sess_id, "qr_code": None, "message": "Session is initializing or waiting for QR generation" } @staticmethod def send_test_openwa_message(phone: str, message: str) -> Dict[str, Any]: """ Sends real test message through OpenWA. """ clean_phone = "".join(filter(str.isdigit, phone)) if len(clean_phone) == 10: clean_phone = "91" + clean_phone headers = { "X-Api-Key": settings.OPENWA_MASTER_KEY, "Content-Type": "application/json" } payload = { "chatId": f"{clean_phone}@c.us", "message": message or "Test verification message from iFixKart ERP" } with httpx.Client(timeout=10.0) as client: r = client.post(f"{settings.OPENWA_GATEWAY_URL}/api/send/text", json=payload, headers=headers) if r.status_code in (200, 201): return {"status": "SUCCESS", "response": r.json()} return {"status": "FAILED", "code": r.status_code, "detail": r.text} @staticmethod def restart_openwa_session() -> Dict[str, Any]: headers = {"X-Api-Key": settings.OPENWA_MASTER_KEY} with httpx.Client(timeout=10.0) as client: sess_res = client.get(f"{settings.OPENWA_GATEWAY_URL}/api/sessions", headers=headers) if sess_res.status_code == 200 and sess_res.json(): sess_id = sess_res.json()[0].get("id") r = client.post(f"{settings.OPENWA_GATEWAY_URL}/api/sessions/{sess_id}/restart", headers=headers) return {"status": "SUCCESS", "detail": "Session restart initiated"} return {"status": "FAILED", "detail": "Could not locate active session"} # --------------------------------------------------------- # 2. External Customer WhatsApp (WATI Cloud API) # --------------------------------------------------------- @staticmethod def get_wati_credentials(db: Session) -> Dict[str, Any]: """ Primary: Config.py | Fallback: DB settings """ endpoint = settings.WATI_API_ENDPOINT token = settings.WATI_API_TOKEN if token and endpoint: return { "api_endpoint": endpoint, "api_token": token, "source": "config.py", "is_locked_by_config": True } db_val = IntegrationService.get_setting_from_db(db, "integration_wati", "credentials") if db_val and isinstance(db_val, dict): return { "api_endpoint": db_val.get("api_endpoint", "https://live-mt-server.wati.io"), "api_token": db_val.get("api_token", ""), "source": "database", "is_locked_by_config": False } return { "api_endpoint": "https://live-mt-server.wati.io", "api_token": "", "source": "unconfigured", "is_locked_by_config": False } @staticmethod def save_wati_credentials(payload: Dict[str, Any], db: Session): return IntegrationService.save_setting_to_db( db, "integration_wati", "credentials", { "api_endpoint": payload.get("api_endpoint", "https://live-mt-server.wati.io").strip(), "api_token": payload.get("api_token", "").strip(), "updated_at": datetime.now(timezone.utc).isoformat() }, description="WATI Customer WhatsApp Cloud API Credentials" ) @staticmethod def test_wati_connection(endpoint: str, token: str) -> Dict[str, Any]: clean_endpoint = endpoint.rstrip("/") headers = {"Authorization": token if token.startswith("Bearer ") else f"Bearer {token}"} with httpx.Client(timeout=10.0) as client: r = client.get(f"{clean_endpoint}/api/v1/getMessageTemplates", headers={"Authorization": token}) if r.status_code != 200: r = client.get(f"{clean_endpoint}/api/v1/getMessageTemplates", headers=headers) if r.status_code == 200: data = r.json() templates = data.get("templates") or data.get("messageTemplates") or [] return { "status": "SUCCESS", "templates_count": len(templates), "templates": templates[:15] } return { "status": "FAILED", "status_code": r.status_code, "detail": r.text } @staticmethod def get_wati_templates(db: Session) -> List[Dict[str, Any]]: creds = IntegrationService.get_wati_credentials(db) if not creds.get("api_token"): return [] res = IntegrationService.test_wati_connection(creds["api_endpoint"], creds["api_token"]) return res.get("templates", []) if res.get("status") == "SUCCESS" else [] @staticmethod def send_wati_template_message(phone: str, template_name: str, broadcast_name: str, parameters: list, db: Session) -> Dict[str, Any]: creds = IntegrationService.get_wati_credentials(db) if not creds.get("api_token"): return {"status": "FAILED", "detail": "WATI credentials not configured"} clean_phone = "".join(filter(str.isdigit, phone)) endpoint = creds["api_endpoint"].rstrip("/") payload = { "template_name": template_name, "broadcast_name": broadcast_name or f"test_{int(datetime.now().timestamp())}", "whatsappNumber": clean_phone, "parameters": parameters or [] } headers = {"Authorization": creds["api_token"]} with httpx.Client(timeout=10.0) as client: r = client.post(f"{endpoint}/api/v1/sendTemplateMessage", json=payload, headers=headers) if r.status_code == 200: return {"status": "SUCCESS", "response": r.json()} return {"status": "FAILED", "code": r.status_code, "detail": r.text} # --------------------------------------------------------- # 3. Transactional Email (ZeptoMail & SMTP) # --------------------------------------------------------- @staticmethod def get_email_credentials(db: Session) -> Dict[str, Any]: """ Primary: ZeptoMail from Config.py | Fallback: Custom SMTP in DB """ if settings.ZEPTOMAIL_API_KEY: return { "active_provider": "ZeptoMail", "sender_email": settings.EMAIL_SENDER_ADDRESS, "sender_name": "iFixKart", "host": settings.ZEPTOMAIL_HOST, "endpoint": settings.ZEPTOMAIL_API_ENDPOINT, "source": "config.py", "is_locked_by_config": True } db_val = IntegrationService.get_setting_from_db(db, "integration_email", "credentials") if db_val and isinstance(db_val, dict): return { "active_provider": db_val.get("provider", "SMTP"), "sender_email": db_val.get("sender_email", ""), "sender_name": db_val.get("sender_name", "iFixKart"), "smtp_server": db_val.get("smtp_server", ""), "smtp_port": db_val.get("smtp_port", 587), "smtp_username": db_val.get("smtp_username", ""), "use_tls": db_val.get("use_tls", True), "source": "database", "is_locked_by_config": False } return { "active_provider": "None", "source": "unconfigured", "is_locked_by_config": False } @staticmethod def save_email_credentials(payload: Dict[str, Any], db: Session): return IntegrationService.save_setting_to_db( db, "integration_email", "credentials", payload, description="Custom SMTP Email Dispatcher Settings" ) @staticmethod def send_test_email(recipient: str, subject: str, body: str, db: Session) -> Dict[str, Any]: creds = IntegrationService.get_email_credentials(db) # 1. ZeptoMail path if creds.get("active_provider") == "ZeptoMail" and settings.ZEPTOMAIL_API_KEY: headers = { "Accept": "application/json", "Content-Type": "application/json", "Authorization": f"Zoho-enczapikey {settings.ZEPTOMAIL_API_KEY}" } payload = { "from": {"address": settings.EMAIL_SENDER_ADDRESS, "name": "iFixKart ERP"}, "to": [{"email_address": {"address": recipient, "name": recipient.split("@")[0]}}], "subject": subject or "iFixKart Email Integration Active", "htmlbody": f"
{body or 'This is a verified test email sent from iFixKart ERP.'}