from decimal import Decimal from django.db import transaction from django.utils import timezone from django.core.exceptions import ValidationError from django.contrib.contenttypes.models import ContentType from .models import Account, Contact, Lead, Opportunity, Activity class LeadConversionResult(dict): def __iter__(self): return iter((self['account'], self['contact'], self['opportunity'])) @transaction.atomic def convert_lead( lead: Lead, account_name: str = None, create_opportunity: bool = False, opportunity_name: str = None, opportunity_amount: Decimal = None, opportunity_close_date = None, user = None ): """ Atomic conversion of Lead to Account, Contact, and optionally Opportunity. Polymorphic activities linked to the Lead are re-linked to the Contact/Opportunity. """ if lead.is_converted: raise ValidationError("Lead has already been converted.") owner = user or lead.owner # 1. Resolve / Create Account target_account_name = account_name.strip() if account_name else lead.company account, _ = Account.objects.get_or_create( name=target_account_name, defaults={ 'phone': lead.phone, 'owner': owner, } ) # 2. Create Contact contact = None if lead.email: contact = Contact.objects.filter(email=lead.email).first() if not contact: contact_custom_fields = dict(lead.custom_fields) if lead.custom_fields else {} contact = Contact.objects.create( first_name=lead.first_name, last_name=lead.last_name, account=account, title=lead.title, email=lead.email, phone=lead.phone, owner=owner, custom_fields=contact_custom_fields, ) elif lead.custom_fields: # Merge lead custom fields into contact merged = dict(contact.custom_fields or {}) merged.update(lead.custom_fields) contact.custom_fields = merged contact.save(update_fields=['custom_fields']) # 3. Optionally Create Opportunity opportunity = None if create_opportunity: opp_name = opportunity_name or f"{target_account_name} - Opportunity" close_date = opportunity_close_date or (timezone.now().date() + timezone.timedelta(days=30)) opp_amount = Decimal(opportunity_amount) if opportunity_amount is not None else Decimal('0.00') opportunity = Opportunity.objects.create( name=opp_name, account=account, stage='Prospecting', amount=opp_amount, close_date=close_date, primary_contact=contact, owner=owner, ) # 4. Repoint Polymorphic Activities from Lead to Contact lead_content_type = ContentType.objects.get_for_model(Lead) contact_content_type = ContentType.objects.get_for_model(Contact) activities = Activity.objects.filter( content_type=lead_content_type, object_id=lead.id ) activities.update( content_type=contact_content_type, object_id=contact.id ) # 5. Mark Lead as Converted lead.is_converted = True lead.status = 'Converted' lead.converted_date = timezone.now() lead.converted_account = account lead.converted_contact = contact lead.converted_opportunity = opportunity lead.save() return LeadConversionResult({ 'account': account, 'contact': contact, 'opportunity': opportunity, })