from decimal import Decimal from django.db import models from django.contrib.auth import get_user_model from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.contrib.postgres.indexes import GinIndex from django.core.exceptions import ValidationError User = get_user_model() class Account(models.Model): ACCOUNT_TYPE_CHOICES = [ ('Prospect', 'Prospect'), ('Customer - Direct', 'Customer - Direct'), ('Customer - Channel', 'Customer - Channel'), ('Channel Partner / Reseller', 'Channel Partner / Reseller'), ('Installation Partner', 'Installation Partner'), ('Technology Partner', 'Technology Partner'), ('Other', 'Other'), ] RATING_CHOICES = [ ('Hot', 'Hot'), ('Warm', 'Warm'), ('Cold', 'Cold'), ] INDUSTRY_CHOICES = [ ('Technology', 'Technology'), ('Finance', 'Finance'), ('Healthcare', 'Healthcare'), ('Manufacturing', 'Manufacturing'), ('Retail', 'Retail'), ('Consulting', 'Consulting'), ('Education', 'Education'), ('Government', 'Government'), ('Media', 'Media'), ('Other', 'Other'), ] name = models.CharField(max_length=255) type = models.CharField(max_length=50, choices=ACCOUNT_TYPE_CHOICES, default='Prospect', blank=True, null=True) industry = models.CharField(max_length=50, choices=INDUSTRY_CHOICES, blank=True, null=True) annual_revenue = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) phone = models.CharField(max_length=40, blank=True, null=True) website = models.URLField(max_length=255, blank=True, null=True) rating = models.CharField(max_length=20, choices=RATING_CHOICES, blank=True, null=True) billing_street = models.CharField(max_length=255, blank=True, null=True) billing_city = models.CharField(max_length=100, blank=True, null=True) billing_state = models.CharField(max_length=100, blank=True, null=True) billing_postal_code = models.CharField(max_length=20, blank=True, null=True) billing_country = models.CharField(max_length=100, blank=True, null=True) shipping_street = models.CharField(max_length=255, blank=True, null=True) shipping_city = models.CharField(max_length=100, blank=True, null=True) shipping_state = models.CharField(max_length=100, blank=True, null=True) shipping_postal_code = models.CharField(max_length=20, blank=True, null=True) shipping_country = models.CharField(max_length=100, blank=True, null=True) parent = models.ForeignKey( 'self', null=True, blank=True, on_delete=models.SET_NULL, related_name='child_accounts' ) parent_account = models.ForeignKey( 'self', null=True, blank=True, on_delete=models.SET_NULL, related_name='legacy_child_accounts' ) owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, related_name='accounts') custom_fields = models.JSONField(default=dict, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_at'] indexes = [ GinIndex(fields=['custom_fields'], name='idx_account_custom_fields_gin'), ] def __str__(self): return self.name class Contact(models.Model): LEAD_SOURCE_CHOICES = [ ('Web', 'Web'), ('Phone Inquiry', 'Phone Inquiry'), ('Partner Referral', 'Partner Referral'), ('Purchased List', 'Purchased List'), ('Other', 'Other'), ] first_name = models.CharField(max_length=100, blank=True, default='') last_name = models.CharField(max_length=100) account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='contacts', null=True, blank=True) title = models.CharField(max_length=100, blank=True, null=True) department = models.CharField(max_length=100, blank=True, null=True) email = models.EmailField(unique=True, null=True, blank=True) phone = models.CharField(max_length=40, blank=True, null=True) mobile_phone = models.CharField(max_length=40, blank=True, null=True) lead_source = models.CharField(max_length=50, choices=LEAD_SOURCE_CHOICES, blank=True, null=True) reports_to = models.ForeignKey( 'self', null=True, blank=True, on_delete=models.SET_NULL, related_name='direct_reports' ) owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, related_name='contacts') custom_fields = models.JSONField(default=dict, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_at'] indexes = [ GinIndex(fields=['custom_fields'], name='idx_contact_custom_fields_gin'), ] def __str__(self): return f"{self.first_name} {self.last_name} ({self.email})".strip() class Lead(models.Model): LEAD_STATUS_CHOICES = [ ('New', 'New'), ('Contacted', 'Contacted'), ('Working', 'Working'), ('Qualified', 'Qualified'), ('Unqualified', 'Unqualified'), ('Converted', 'Converted'), ] RATING_CHOICES = [ ('Hot', 'Hot'), ('Warm', 'Warm'), ('Cold', 'Cold'), ] first_name = models.CharField(max_length=100, blank=True, default='') last_name = models.CharField(max_length=100) company = models.CharField(max_length=255) title = models.CharField(max_length=100, blank=True, null=True) email = models.EmailField(blank=True, null=True) phone = models.CharField(max_length=40, blank=True, null=True) status = models.CharField(max_length=50, choices=LEAD_STATUS_CHOICES, default='New') rating = models.CharField(max_length=20, choices=RATING_CHOICES, blank=True, null=True) owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, related_name='leads') is_converted = models.BooleanField(default=False) converted_date = models.DateTimeField(null=True, blank=True) converted_account = models.ForeignKey( Account, null=True, blank=True, on_delete=models.SET_NULL, related_name='converted_leads' ) converted_contact = models.ForeignKey( Contact, null=True, blank=True, on_delete=models.SET_NULL, related_name='converted_leads' ) converted_opportunity = models.ForeignKey( 'Opportunity', null=True, blank=True, on_delete=models.SET_NULL, related_name='converted_leads' ) custom_fields = models.JSONField(default=dict, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_at'] indexes = [ GinIndex(fields=['custom_fields'], name='idx_lead_custom_fields_gin'), ] def __str__(self): return f"{self.first_name} {self.last_name} - {self.company}".strip() class Opportunity(models.Model): STAGE_CHOICES = [ ('Prospecting', 'Prospecting'), ('Qualification', 'Qualification'), ('Needs Analysis', 'Needs Analysis'), ('Value Proposition', 'Value Proposition'), ('Id. Decision Makers', 'Id. Decision Makers'), ('Decision Makers', 'Decision Makers'), ('Perception Analysis', 'Perception Analysis'), ('Proposal/Price Quote', 'Proposal/Price Quote'), ('Negotiation/Review', 'Negotiation/Review'), ('Closed Won', 'Closed Won'), ('Closed Lost', 'Closed Lost'), ] STAGE_PROBABILITY_MAP = { 'Prospecting': 10, 'Qualification': 20, 'Needs Analysis': 30, 'Value Proposition': 50, 'Id. Decision Makers': 60, 'Decision Makers': 60, 'Perception Analysis': 70, 'Proposal/Price Quote': 75, 'Negotiation/Review': 90, 'Closed Won': 100, 'Closed Lost': 0, } TYPE_CHOICES = [ ('Existing Customer - Upgrade', 'Existing Customer - Upgrade'), ('Existing Customer - Replacement', 'Existing Customer - Replacement'), ('Existing Customer - Downgrade', 'Existing Customer - Downgrade'), ('New Customer', 'New Customer'), ] name = models.CharField(max_length=255) account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='opportunities') stage = models.CharField(max_length=50, choices=STAGE_CHOICES, default='Prospecting') amount = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) probability = models.IntegerField(default=10) expected_revenue = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) close_date = models.DateField() opp_type = models.CharField(max_length=50, choices=TYPE_CHOICES, blank=True, null=True) primary_contact = models.ForeignKey( Contact, null=True, blank=True, on_delete=models.SET_NULL, related_name='primary_opportunities' ) owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, related_name='opportunities') custom_fields = models.JSONField(default=dict, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-close_date'] indexes = [ GinIndex(fields=['custom_fields'], name='idx_opp_custom_fields_gin'), ] def clean(self): super().clean() valid_stages = dict(self.STAGE_CHOICES).keys() if self.stage not in valid_stages: raise ValidationError({'stage': f'Invalid stage: {self.stage}'}) if self.probability is not None and not (0 <= self.probability <= 100): raise ValidationError({'probability': 'Probability must be between 0 and 100.'}) if self.amount is not None and self.amount < 0: raise ValidationError({'amount': 'Amount cannot be negative.'}) def save(self, *args, **kwargs): if self.amount is not None and self.probability is not None: self.expected_revenue = (self.amount * Decimal(self.probability) / Decimal(100)).quantize(Decimal('0.01')) super().save(*args, **kwargs) def __str__(self): return f"{self.name} - ${self.amount}" class Activity(models.Model): ACTIVITY_TYPE_CHOICES = [ ('Task', 'Task'), ('Call', 'Call'), ('Meeting', 'Meeting'), ('Email', 'Email'), ] STATUS_CHOICES = [ ('Not Started', 'Not Started'), ('In Progress', 'In Progress'), ('Completed', 'Completed'), ('Waiting on someone else', 'Waiting on someone else'), ('Deferred', 'Deferred'), ] PRIORITY_CHOICES = [ ('High', 'High'), ('Normal', 'Normal'), ('Low', 'Low'), ] subject = models.CharField(max_length=255) activity_type = models.CharField(max_length=20, choices=ACTIVITY_TYPE_CHOICES, default='Task') status = models.CharField(max_length=30, choices=STATUS_CHOICES, default='Not Started') priority = models.CharField(max_length=20, choices=PRIORITY_CHOICES, default='Normal') due_date = models.DateField(null=True, blank=True) completed_at = models.DateTimeField(null=True, blank=True) description = models.TextField(blank=True, default='') # Polymorphic association (WhatId / WhoId equivalent) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True) object_id = models.PositiveIntegerField(null=True, blank=True) parent = GenericForeignKey('content_type', 'object_id') assigned_to = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, related_name='activities') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-due_date', '-created_at'] def __str__(self): return f"[{self.activity_type}] {self.subject}"