website/hub/services/odoo.py

167 lines
6.2 KiB
Python
Raw Permalink Normal View History

2025-01-27 16:51:23 +01:00
import odoorpc
import logging
from django.conf import settings
from urllib.parse import urlparse
# Set up logging
logger = logging.getLogger(__name__)
class OdooAPI:
def __init__(self):
self.odoo = None
self._connect()
def _connect(self):
2025-01-31 11:00:53 +01:00
"""Establish connection to Odoo"""
2025-01-27 16:51:23 +01:00
try:
# Parse URL to get host
url = settings.ODOO_CONFIG["url"]
parsed_url = urlparse(url)
2025-01-28 13:55:43 +01:00
host = parsed_url.netloc or parsed_url.path
2025-01-27 16:51:23 +01:00
# Log connection attempt
logger.info(f"Attempting to connect to Odoo at {host}")
logger.debug(
f"Connection parameters: HOST={host}, DB={settings.ODOO_CONFIG['db']}, "
f"USER={settings.ODOO_CONFIG['username']}"
)
self.odoo = odoorpc.ODOO(host, port=443, protocol="jsonrpc+ssl")
logger.info("Connection established, attempting login...")
self.odoo.login(
settings.ODOO_CONFIG["db"],
settings.ODOO_CONFIG["username"],
settings.ODOO_CONFIG["password"],
)
logger.info("Successfully logged into Odoo")
version_info = self.odoo.version
logger.info(f"Connected to Odoo version: {version_info}")
except odoorpc.error.RPCError as e:
logger.error(f"RPC Error connecting to Odoo: {str(e)}")
logger.debug("Full RPC error details:", exc_info=True)
raise
except odoorpc.error.InternalError as e:
logger.error(f"Internal Odoo error: {str(e)}")
logger.debug("Full internal error details:", exc_info=True)
raise
except Exception as e:
logger.error(f"Unexpected error connecting to Odoo: {str(e)}")
logger.debug("Full error details:", exc_info=True)
raise
2025-03-03 14:30:05 +01:00
def create_lead(self, lead, lead_title=""):
2025-01-31 11:00:53 +01:00
"""Create a lead in Odoo"""
2025-01-27 16:51:23 +01:00
try:
2025-02-27 15:44:55 +01:00
logger.info(f"Attempting to create lead for {lead.name}")
2025-01-28 13:55:43 +01:00
2025-01-27 16:51:23 +01:00
# Prepare lead data
lead_data = {
2025-03-03 14:30:05 +01:00
"name": "Servala" + lead_title,
2025-01-27 16:51:23 +01:00
"contact_name": lead.name,
2025-02-27 15:44:55 +01:00
"partner_name": (
lead.company if hasattr(lead, "company") and lead.company else ""
),
2025-01-27 16:51:23 +01:00
"email_from": lead.email,
2025-02-27 15:44:55 +01:00
"phone": lead.phone if hasattr(lead, "phone") and lead.phone else "",
2025-03-03 14:30:05 +01:00
"description": lead.message,
2025-01-27 16:51:23 +01:00
"type": "lead",
2025-01-31 11:00:53 +01:00
"campaign_id": settings.ODOO_CONFIG["campaign_id"],
"source_id": settings.ODOO_CONFIG["source_id"],
"medium_id": settings.ODOO_CONFIG["medium_id"],
"tag_ids": [(4, settings.ODOO_CONFIG["tag_id"])],
2025-01-27 16:51:23 +01:00
}
logger.debug(f"Prepared lead data: {lead_data}")
# Ensure we have a valid connection
if not self.odoo:
logger.warning("No active Odoo connection, attempting to reconnect")
self._connect()
# Create the lead
2025-01-28 13:55:43 +01:00
Lead = self.odoo.env["crm.lead"]
2025-01-27 16:51:23 +01:00
odoo_lead_id = Lead.create(lead_data)
logger.info(f"Successfully created lead in Odoo with ID: {odoo_lead_id}")
return odoo_lead_id
except odoorpc.error.RPCError as e:
logger.error(f"RPC Error creating lead: {str(e)}")
logger.debug("Full RPC error details:", exc_info=True)
raise
except Exception as e:
logger.error(f"Unexpected error creating lead: {str(e)}")
logger.debug("Full error details:", exc_info=True)
raise
def add_to_mailing_list(self, email, mailing_list_id=46):
"""Add an email to a mailing list in Odoo"""
try:
logger.info(
f"Attempting to add {email} to mailing list ID {mailing_list_id}"
)
# Ensure we have a valid connection
if not self.odoo:
logger.warning("No active Odoo connection, attempting to reconnect")
self._connect()
# Add contact to mailing list
MailingContact = self.odoo.env["mailing.contact"]
existing_mailing_contacts = MailingContact.search([("email", "=", email)])
if existing_mailing_contacts:
mailing_contact_id = existing_mailing_contacts[0]
# Check if already in this list
MailingContactList = self.odoo.env["mailing.contact.subscription"]
existing_subscriptions = MailingContactList.search(
[
("contact_id", "=", mailing_contact_id),
("list_id", "=", mailing_list_id),
]
)
if not existing_subscriptions:
# Add to this specific list
MailingContactList.create(
{
"contact_id": mailing_contact_id,
"list_id": mailing_list_id,
"opt_out": False,
}
)
else:
# Create new mailing contact and subscription
mailing_contact_id = MailingContact.create(
{
"name": email.split("@")[0],
"email": email,
}
)
MailingContactList = self.odoo.env["mailing.contact.subscription"]
MailingContactList.create(
{
"contact_id": mailing_contact_id,
"list_id": mailing_list_id,
"opt_out": False,
}
)
logger.info(f"Successfully added {email} to mailing list")
return True
except odoorpc.error.RPCError as e:
logger.error(f"RPC Error adding to mailing list: {str(e)}")
logger.debug("Full RPC error details:", exc_info=True)
return False
except Exception as e:
logger.error(f"Unexpected error adding to mailing list: {str(e)}")
logger.debug("Full error details:", exc_info=True)
return False