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"

iFixKart Email Integration Active

{body or 'This is a verified test email sent from iFixKart ERP.'}


Sent via Zoho ZeptoMail CPaaS
" } with httpx.Client(timeout=8.0) as client: r = client.post(settings.ZEPTOMAIL_API_ENDPOINT, json=payload, headers=headers) if r.status_code in (200, 201): return {"status": "SUCCESS", "provider": "ZeptoMail", "response": r.json()} return {"status": "FAILED", "provider": "ZeptoMail", "detail": r.text} # 2. Custom SMTP fallback path smtp_server = creds.get("smtp_server") smtp_port = int(creds.get("smtp_port", 587)) smtp_user = creds.get("smtp_username") smtp_pass = creds.get("smtp_password") if not smtp_server or not smtp_user: return {"status": "FAILED", "detail": "No valid ZeptoMail or SMTP credentials configured"} try: msg = MIMEMultipart() msg["From"] = creds.get("sender_email", smtp_user) msg["To"] = recipient msg["Subject"] = subject or "iFixKart SMTP Verification Test" msg.attach(MIMEText(body or "This is a test email sent from iFixKart SMTP integration.", "html")) with smtplib.SMTP(smtp_server, smtp_port, timeout=10) as server: if creds.get("use_tls", True): server.starttls() if smtp_pass: server.login(smtp_user, smtp_pass) server.send_message(msg) return {"status": "SUCCESS", "provider": "SMTP", "recipient": recipient} except Exception as e: return {"status": "FAILED", "provider": "SMTP", "detail": str(e)} # --------------------------------------------------------- # 4. Meta Ads & Graph API (Facebook & Instagram) # --------------------------------------------------------- @staticmethod def get_meta_credentials(db: Session) -> Dict[str, Any]: """ Primary: Config.py | Fallback: DB """ if settings.META_ACCESS_TOKEN and settings.META_APP_ID: return { "app_id": settings.META_APP_ID, "ad_account_id": settings.META_AD_ACCOUNT_ID, "page_id": settings.FACEBOOK_PAGE_ID, "instagram_id": settings.INSTAGRAM_BUSINESS_ACCOUNT_ID, "access_token": settings.META_ACCESS_TOKEN, "source": "config.py", "is_locked_by_config": True } db_val = IntegrationService.get_setting_from_db(db, "integration_meta", "credentials") if db_val and isinstance(db_val, dict): return { "app_id": db_val.get("app_id", ""), "ad_account_id": db_val.get("ad_account_id", ""), "page_id": db_val.get("page_id", ""), "instagram_id": db_val.get("instagram_id", ""), "access_token": db_val.get("access_token", ""), "source": "database", "is_locked_by_config": False } return { "app_id": "", "ad_account_id": "", "page_id": "", "access_token": "", "source": "unconfigured", "is_locked_by_config": False } @staticmethod def save_meta_credentials(payload: Dict[str, Any], db: Session): return IntegrationService.save_setting_to_db( db, "integration_meta", "credentials", payload, description="Meta Ads & Facebook/Instagram Graph API Credentials" ) @staticmethod def test_meta_connection(token: str, ad_account_id: str = "") -> Dict[str, Any]: clean_token = token.strip() url = f"{settings.META_GRAPH_API_BASE}/me?fields=id,name,accounts&access_token={clean_token}" with httpx.Client(timeout=10.0) as client: r = client.get(url) if r.status_code == 200: user_data = r.json() ad_account_info = None if ad_account_id: act_clean = ad_account_id if ad_account_id.startswith("act_") else f"act_{ad_account_id}" act_url = f"{settings.META_GRAPH_API_BASE}/{act_clean}?fields=id,name,account_status,currency,amount_spent&access_token={clean_token}" act_r = client.get(act_url) if act_r.status_code == 200: ad_account_info = act_r.json() return { "status": "SUCCESS", "user": user_data, "ad_account": ad_account_info } return {"status": "FAILED", "code": r.status_code, "detail": r.text} # --------------------------------------------------------- # 5. Knowlarity Cloud Telephony (IVR / Click-to-Call) # --------------------------------------------------------- @staticmethod def get_knowlarity_credentials(db: Session) -> Dict[str, Any]: """ Primary: Config.py | Fallback: DB """ if settings.KNOWLARITY_API_KEY and settings.KNOWLARITY_AUTHORIZATION: return { "api_key": settings.KNOWLARITY_API_KEY, "authorization": settings.KNOWLARITY_AUTHORIZATION, "virtual_number": settings.KNOWLARITY_SR_NUMBER, "call_url": settings.KNOWLARITY_CALL_URL, "log_url": settings.KNOWLARITY_LOG_URL, "source": "config.py", "is_locked_by_config": True } db_val = IntegrationService.get_setting_from_db(db, "integration_knowlarity", "credentials") if db_val and isinstance(db_val, dict): return { "api_key": db_val.get("api_key", ""), "authorization": db_val.get("authorization", ""), "virtual_number": db_val.get("virtual_number", ""), "call_url": db_val.get("call_url", "https://kpi.knowlarity.com/Basic/v1/account/call/makecall"), "log_url": db_val.get("log_url", "https://kpi.knowlarity.com/Basic/v1/account/calllog"), "source": "database", "is_locked_by_config": False } return { "api_key": "", "authorization": "", "virtual_number": "", "source": "unconfigured", "is_locked_by_config": False } @staticmethod def save_knowlarity_credentials(payload: Dict[str, Any], db: Session): return IntegrationService.save_setting_to_db( db, "integration_knowlarity", "credentials", payload, description="Knowlarity SuperReceptionist Telephony Settings" ) @staticmethod def knowlarity_make_call(agent_number: str, customer_number: str, db: Session) -> Dict[str, Any]: creds = IntegrationService.get_knowlarity_credentials(db) if not creds.get("api_key") or not creds.get("authorization"): return {"status": "FAILED", "detail": "Knowlarity API Key / Authorization missing"} headers = { "x-api-key": creds["api_key"], "authorization": creds["authorization"], "content-type": "application/json" } payload = { "k_number": creds.get("virtual_number", ""), "agent_number": agent_number.strip(), "customer_number": customer_number.strip() } call_url = creds.get("call_url", "https://kpi.knowlarity.com/Basic/v1/account/call/makecall") with httpx.Client(timeout=12.0) as client: try: r = client.post(call_url, 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} except Exception as e: return {"status": "FAILED", "detail": str(e)} @staticmethod def knowlarity_get_call_logs(page: int, limit: int, db: Session) -> Dict[str, Any]: creds = IntegrationService.get_knowlarity_credentials(db) if not creds.get("api_key") or not creds.get("authorization"): return {"status": "FAILED", "detail": "Knowlarity credentials missing", "call_logs": []} headers = { "x-api-key": creds["api_key"], "authorization": creds["authorization"] } log_url = creds.get("log_url", "https://kpi.knowlarity.com/Basic/v1/account/calllog") with httpx.Client(timeout=10.0) as client: try: r = client.get(f"{log_url}?page={page}&limit={limit}", headers=headers) if r.status_code == 200: return {"status": "SUCCESS", "data": r.json()} return {"status": "FAILED", "code": r.status_code, "detail": r.text, "call_logs": []} except Exception as e: return {"status": "FAILED", "detail": str(e), "call_logs": []} # --------------------------------------------------------- # 6. Shiprocket Logistics # --------------------------------------------------------- @staticmethod def get_shiprocket_credentials(db: Session) -> Dict[str, Any]: """ Primary: Config.py | Fallback: DB """ if settings.SHIPROCKET_EMAIL and settings.SHIPROCKET_PASSWORD: return { "email": settings.SHIPROCKET_EMAIL, "pickup_location": settings.SHIPROCKET_PICKUP_LOCATION, "pickup_pin": settings.SHIPROCKET_PICKUP_PIN, "api_url": settings.SHIPROCKET_API_URL, "source": "config.py", "is_locked_by_config": True } db_val = IntegrationService.get_setting_from_db(db, "integration_shiprocket", "credentials") if db_val and isinstance(db_val, dict): return { "email": db_val.get("email", ""), "pickup_location": db_val.get("pickup_location", "Primary"), "pickup_pin": db_val.get("pickup_pin", ""), "api_url": db_val.get("api_url", "https://apiv2.shiprocket.in/v1/external"), "token": db_val.get("token", ""), "source": "database", "is_locked_by_config": False } return { "email": "", "pickup_location": "Primary", "pickup_pin": "", "api_url": "https://apiv2.shiprocket.in/v1/external", "source": "unconfigured", "is_locked_by_config": False } @staticmethod def save_shiprocket_credentials(payload: Dict[str, Any], db: Session): return IntegrationService.save_setting_to_db( db, "integration_shiprocket", "credentials", payload, description="Shiprocket API Logistics Credentials" ) @staticmethod def test_shiprocket_auth(email: str, password: str, db: Session = None) -> Dict[str, Any]: payload = {"email": email.strip(), "password": password.strip()} url = "https://apiv2.shiprocket.in/v1/external/auth/login" with httpx.Client(timeout=10.0) as client: try: r = client.post(url, json=payload) if r.status_code == 200: token = r.json().get("token") if db and token: IntegrationService.save_setting_to_db( db, "integration_shiprocket", "cached_token", {"token": token, "generated_at": datetime.now(timezone.utc).isoformat()} ) return {"status": "SUCCESS", "token": token} return {"status": "FAILED", "code": r.status_code, "detail": r.text} except Exception as e: return {"status": "FAILED", "detail": str(e)} @staticmethod def check_shiprocket_serviceability(pickup_pin: str, delivery_pin: str, weight: float, cod: bool, db: Session) -> Dict[str, Any]: creds = IntegrationService.get_shiprocket_credentials(db) token = creds.get("token") or "" cached = IntegrationService.get_setting_from_db(db, "integration_shiprocket", "cached_token") if cached and isinstance(cached, dict): token = cached.get("token", token) if not token: return {"status": "FAILED", "detail": "Shiprocket authentication token required"} headers = {"Authorization": f"Bearer {token}"} url = f"https://apiv2.shiprocket.in/v1/external/courier/serviceability/?pickup_postcode={pickup_pin}&delivery_postcode={delivery_pin}&weight={weight}&cod={1 if cod else 0}" with httpx.Client(timeout=10.0) as client: try: r = client.get(url, headers=headers) if r.status_code == 200: return {"status": "SUCCESS", "data": r.json()} return {"status": "FAILED", "code": r.status_code, "detail": r.text} except Exception as e: return {"status": "FAILED", "detail": str(e)}