commit 86afab03bcb8f5053d910dae5fa7a562be1d40ac Author: Goose Date: Sat Sep 26 07:21:21 2026 +0000 Scaffold Phase 1 CRM models and apps diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..161cb33 --- /dev/null +++ b/.coveragerc @@ -0,0 +1,21 @@ +[run] +source = + crm_core + custom_objects + workflows + outreach +omit = + */migrations/* + */tests/* + */settings/* + manage.py + openforce/wsgi.py + openforce/asgi.py + +[report] +show_missing = True +fail_under = 80 +exclude_lines = + pragma: no cover + def __repr__ + raise NotImplementedError diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e91c5de --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +*.pyc +__pycache__/ +*.sqlite3 +.venv/ +.coverage +htmlcov/ +.pytest_cache/ +media/ +staticfiles/ diff --git a/crm_core/__init__.py b/crm_core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/crm_core/apps.py b/crm_core/apps.py new file mode 100644 index 0000000..51dc384 --- /dev/null +++ b/crm_core/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + +class CrmCoreConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'crm_core' diff --git a/crm_core/migrations/0001_initial.py b/crm_core/migrations/0001_initial.py new file mode 100644 index 0000000..70d4d68 --- /dev/null +++ b/crm_core/migrations/0001_initial.py @@ -0,0 +1,137 @@ +# Generated by Django 4.2.30 on 2026-09-26 07:21 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('contenttypes', '0002_remove_content_type_name'), + ] + + operations = [ + migrations.CreateModel( + name='Account', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255)), + ('account_type', models.CharField(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')], default='Prospect', max_length=50)), + ('industry', models.CharField(blank=True, choices=[('Technology', 'Technology'), ('Finance', 'Finance'), ('Healthcare', 'Healthcare'), ('Manufacturing', 'Manufacturing'), ('Retail', 'Retail'), ('Consulting', 'Consulting'), ('Education', 'Education'), ('Government', 'Government'), ('Media', 'Media'), ('Other', 'Other')], max_length=50, null=True)), + ('annual_revenue', models.DecimalField(blank=True, decimal_places=2, max_digits=15, null=True)), + ('phone', models.CharField(blank=True, max_length=40, null=True)), + ('website', models.URLField(blank=True, max_length=255, null=True)), + ('rating', models.CharField(blank=True, choices=[('Hot', 'Hot'), ('Warm', 'Warm'), ('Cold', 'Cold')], max_length=20, null=True)), + ('billing_street', models.CharField(blank=True, max_length=255, null=True)), + ('billing_city', models.CharField(blank=True, max_length=100, null=True)), + ('billing_state', models.CharField(blank=True, max_length=100, null=True)), + ('billing_postal_code', models.CharField(blank=True, max_length=20, null=True)), + ('billing_country', models.CharField(blank=True, max_length=100, null=True)), + ('shipping_street', models.CharField(blank=True, max_length=255, null=True)), + ('shipping_city', models.CharField(blank=True, max_length=100, null=True)), + ('shipping_state', models.CharField(blank=True, max_length=100, null=True)), + ('shipping_postal_code', models.CharField(blank=True, max_length=20, null=True)), + ('shipping_country', models.CharField(blank=True, max_length=100, null=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('owner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='accounts', to=settings.AUTH_USER_MODEL)), + ('parent_account', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='child_accounts', to='crm_core.account')), + ], + options={ + 'ordering': ['-created_at'], + }, + ), + migrations.CreateModel( + name='Contact', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('first_name', models.CharField(blank=True, default='', max_length=100)), + ('last_name', models.CharField(max_length=100)), + ('title', models.CharField(blank=True, max_length=100, null=True)), + ('department', models.CharField(blank=True, max_length=100, null=True)), + ('email', models.EmailField(blank=True, max_length=254, null=True, unique=True)), + ('phone', models.CharField(blank=True, max_length=40, null=True)), + ('mobile_phone', models.CharField(blank=True, max_length=40, null=True)), + ('lead_source', models.CharField(blank=True, choices=[('Web', 'Web'), ('Phone Inquiry', 'Phone Inquiry'), ('Partner Referral', 'Partner Referral'), ('Purchased List', 'Purchased List'), ('Other', 'Other')], max_length=50, null=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('account', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='contacts', to='crm_core.account')), + ('owner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='contacts', to=settings.AUTH_USER_MODEL)), + ('reports_to', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='direct_reports', to='crm_core.contact')), + ], + options={ + 'ordering': ['-created_at'], + }, + ), + migrations.CreateModel( + name='Opportunity', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255)), + ('stage', models.CharField(choices=[('Prospecting', 'Prospecting'), ('Qualification', 'Qualification'), ('Needs Analysis', 'Needs Analysis'), ('Value Proposition', 'Value Proposition'), ('Decision Makers', 'Decision Makers'), ('Proposal/Price Quote', 'Proposal/Price Quote'), ('Negotiation/Review', 'Negotiation/Review'), ('Closed Won', 'Closed Won'), ('Closed Lost', 'Closed Lost')], default='Prospecting', max_length=50)), + ('amount', models.DecimalField(blank=True, decimal_places=2, max_digits=15, null=True)), + ('probability', models.IntegerField(default=10)), + ('expected_revenue', models.DecimalField(blank=True, decimal_places=2, max_digits=15, null=True)), + ('close_date', models.DateField()), + ('opp_type', models.CharField(blank=True, choices=[('Existing Customer - Upgrade', 'Existing Customer - Upgrade'), ('Existing Customer - Replacement', 'Existing Customer - Replacement'), ('Existing Customer - Downgrade', 'Existing Customer - Downgrade'), ('New Customer', 'New Customer')], max_length=50, null=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('account', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='opportunities', to='crm_core.account')), + ('owner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='opportunities', to=settings.AUTH_USER_MODEL)), + ('primary_contact', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='primary_opportunities', to='crm_core.contact')), + ], + options={ + 'ordering': ['-close_date'], + }, + ), + migrations.CreateModel( + name='Lead', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('first_name', models.CharField(blank=True, default='', max_length=100)), + ('last_name', models.CharField(max_length=100)), + ('company', models.CharField(max_length=255)), + ('title', models.CharField(blank=True, max_length=100, null=True)), + ('email', models.EmailField(blank=True, max_length=254, null=True)), + ('phone', models.CharField(blank=True, max_length=40, null=True)), + ('status', models.CharField(choices=[('New', 'New'), ('Contacted', 'Contacted'), ('Working', 'Working'), ('Qualified', 'Qualified'), ('Unqualified', 'Unqualified'), ('Converted', 'Converted')], default='New', max_length=50)), + ('rating', models.CharField(blank=True, choices=[('Hot', 'Hot'), ('Warm', 'Warm'), ('Cold', 'Cold')], max_length=20, null=True)), + ('is_converted', models.BooleanField(default=False)), + ('converted_date', models.DateTimeField(blank=True, null=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('converted_account', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='converted_leads', to='crm_core.account')), + ('converted_contact', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='converted_leads', to='crm_core.contact')), + ('converted_opportunity', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='converted_leads', to='crm_core.opportunity')), + ('owner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='leads', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'ordering': ['-created_at'], + }, + ), + migrations.CreateModel( + name='Activity', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('subject', models.CharField(max_length=255)), + ('activity_type', models.CharField(choices=[('Task', 'Task'), ('Call', 'Call'), ('Meeting', 'Meeting'), ('Email', 'Email')], default='Task', max_length=20)), + ('status', models.CharField(choices=[('Not Started', 'Not Started'), ('In Progress', 'In Progress'), ('Completed', 'Completed'), ('Waiting on someone else', 'Waiting on someone else'), ('Deferred', 'Deferred')], default='Not Started', max_length=30)), + ('priority', models.CharField(choices=[('High', 'High'), ('Normal', 'Normal'), ('Low', 'Low')], default='Normal', max_length=20)), + ('due_date', models.DateField(blank=True, null=True)), + ('completed_at', models.DateTimeField(blank=True, null=True)), + ('description', models.TextField(blank=True, default='')), + ('object_id', models.PositiveIntegerField(blank=True, null=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('assigned_to', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='activities', to=settings.AUTH_USER_MODEL)), + ('content_type', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.contenttype')), + ], + options={ + 'ordering': ['-due_date', '-created_at'], + }, + ), + ] diff --git a/crm_core/migrations/__init__.py b/crm_core/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/crm_core/models.py b/crm_core/models.py new file mode 100644 index 0000000..e615d49 --- /dev/null +++ b/crm_core/models.py @@ -0,0 +1,270 @@ +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.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) + account_type = models.CharField(max_length=50, choices=ACCOUNT_TYPE_CHOICES, default='Prospect') + 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_account = models.ForeignKey( + 'self', null=True, blank=True, on_delete=models.SET_NULL, related_name='child_accounts' + ) + owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, related_name='accounts') + + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + ordering = ['-created_at'] + + 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') + + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + ordering = ['-created_at'] + + def __str__(self): + return f"{self.first_name} {self.last_name}".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' + ) + + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + ordering = ['-created_at'] + + 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'), + ('Decision Makers', 'Decision Makers'), + ('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, + 'Decision Makers': 60, + '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') + + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + ordering = ['-close_date'] + + 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}" diff --git a/crm_core/serializers.py b/crm_core/serializers.py new file mode 100644 index 0000000..d4a45e6 --- /dev/null +++ b/crm_core/serializers.py @@ -0,0 +1,49 @@ +from rest_framework import serializers +from .models import Account, Contact, Lead, Opportunity, Activity + + +class AccountSerializer(serializers.ModelSerializer): + class Meta: + model = Account + fields = '__all__' + read_only_fields = ['id', 'created_at', 'updated_at'] + + +class ContactSerializer(serializers.ModelSerializer): + class Meta: + model = Contact + fields = '__all__' + read_only_fields = ['id', 'created_at', 'updated_at'] + + +class LeadSerializer(serializers.ModelSerializer): + class Meta: + model = Lead + fields = '__all__' + read_only_fields = [ + 'id', 'is_converted', 'converted_date', + 'converted_account', 'converted_contact', + 'converted_opportunity', 'created_at', 'updated_at' + ] + + +class OpportunitySerializer(serializers.ModelSerializer): + class Meta: + model = Opportunity + fields = '__all__' + read_only_fields = ['id', 'expected_revenue', 'created_at', 'updated_at'] + + +class ActivitySerializer(serializers.ModelSerializer): + class Meta: + model = Activity + fields = '__all__' + read_only_fields = ['id', 'completed_at', 'created_at', 'updated_at'] + + +class LeadConvertSerializer(serializers.Serializer): + create_opportunity = serializers.BooleanField(required=False, default=False) + account_name = serializers.CharField(required=False, allow_blank=True) + opportunity_name = serializers.CharField(required=False, allow_blank=True) + opportunity_amount = serializers.DecimalField(required=False, max_digits=15, decimal_places=2, allow_null=True) + opportunity_close_date = serializers.DateField(required=False, allow_null=True) diff --git a/crm_core/services.py b/crm_core/services.py new file mode 100644 index 0000000..c0159ec --- /dev/null +++ b/crm_core/services.py @@ -0,0 +1,98 @@ +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 + + +@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 = 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, + ) + + # 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 { + 'account': account, + 'contact': contact, + 'opportunity': opportunity, + } diff --git a/crm_core/views.py b/crm_core/views.py new file mode 100644 index 0000000..543a4eb --- /dev/null +++ b/crm_core/views.py @@ -0,0 +1,80 @@ +from decimal import Decimal +from rest_framework import viewsets, status +from rest_framework.decorators import action +from rest_framework.response import Response +from rest_framework.permissions import IsAuthenticated +from rest_framework.exceptions import ValidationError + +from .models import Account, Contact, Lead, Opportunity, Activity +from .serializers import ( + AccountSerializer, ContactSerializer, LeadSerializer, + OpportunitySerializer, ActivitySerializer, LeadConvertSerializer +) +from .services import convert_lead + + +class AccountViewSet(viewsets.ModelViewSet): + permission_classes = [IsAuthenticated] + queryset = Account.objects.all().order_by('-created_at') + serializer_class = AccountSerializer + search_fields = ['name', 'industry'] + + +class ContactViewSet(viewsets.ModelViewSet): + permission_classes = [IsAuthenticated] + queryset = Contact.objects.all().order_by('-created_at') + serializer_class = ContactSerializer + filterset_fields = ['account', 'lead_source'] + search_fields = ['first_name', 'last_name', 'email'] + + +class LeadViewSet(viewsets.ModelViewSet): + permission_classes = [IsAuthenticated] + queryset = Lead.objects.all().order_by('-created_at') + serializer_class = LeadSerializer + filterset_fields = ['status', 'rating'] + search_fields = ['first_name', 'last_name', 'company', 'email'] + + @action(detail=True, methods=['post'], url_path='convert') + def convert(self, request, pk=None): + lead = self.get_object() + serializer = LeadConvertSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + validated = serializer.validated_data + + try: + result = convert_lead( + lead=lead, + account_name=validated.get('account_name'), + create_opportunity=validated.get('create_opportunity', False), + opportunity_name=validated.get('opportunity_name'), + opportunity_amount=validated.get('opportunity_amount'), + opportunity_close_date=validated.get('opportunity_close_date'), + user=request.user + ) + return Response({ + 'account_id': result['account'].id, + 'contact_id': result['contact'].id, + 'opportunity_id': result['opportunity'].id if result['opportunity'] else None, + 'status': 'converted' + }, status=status.HTTP_200_OK) + except ValidationError as e: + return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) + except Exception as e: + return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) + + +class OpportunityViewSet(viewsets.ModelViewSet): + permission_classes = [IsAuthenticated] + queryset = Opportunity.objects.all().order_by('-close_date') + serializer_class = OpportunitySerializer + filterset_fields = ['stage', 'account'] + search_fields = ['name'] + + +class ActivityViewSet(viewsets.ModelViewSet): + permission_classes = [IsAuthenticated] + queryset = Activity.objects.all().order_by('-due_date') + serializer_class = ActivitySerializer + filterset_fields = ['activity_type', 'status', 'priority'] + search_fields = ['subject', 'description'] diff --git a/custom_objects/__init__.py b/custom_objects/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/custom_objects/apps.py b/custom_objects/apps.py new file mode 100644 index 0000000..f4e645a --- /dev/null +++ b/custom_objects/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + +class CustomObjectsConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'custom_objects' diff --git a/custom_objects/migrations/0001_initial.py b/custom_objects/migrations/0001_initial.py new file mode 100644 index 0000000..9c9b8fa --- /dev/null +++ b/custom_objects/migrations/0001_initial.py @@ -0,0 +1,28 @@ +# Generated by Django 4.2.30 on 2026-09-26 07:21 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='CustomFieldDefinition', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255)), + ], + ), + migrations.CreateModel( + name='CustomObjectDefinition', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255)), + ], + ), + ] diff --git a/custom_objects/migrations/__init__.py b/custom_objects/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/custom_objects/models.py b/custom_objects/models.py new file mode 100644 index 0000000..2d6bc07 --- /dev/null +++ b/custom_objects/models.py @@ -0,0 +1,7 @@ +from django.db import models + +class CustomObjectDefinition(models.Model): + name = models.CharField(max_length=255) + +class CustomFieldDefinition(models.Model): + name = models.CharField(max_length=255) diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..726547f --- /dev/null +++ b/manage.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +import os +import sys + +def main(): + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'openforce.settings.base') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + +if __name__ == '__main__': + main() diff --git a/openforce/__init__.py b/openforce/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/openforce/settings.py b/openforce/settings.py new file mode 100644 index 0000000..e69de29 diff --git a/openforce/settings/__init__.py b/openforce/settings/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/openforce/settings/base.py b/openforce/settings/base.py new file mode 100644 index 0000000..bf7fc94 --- /dev/null +++ b/openforce/settings/base.py @@ -0,0 +1,63 @@ +import os +from pathlib import Path + +BASE_DIR = Path(__file__).resolve().parent.parent.parent + +SECRET_KEY = 'django-insecure-test-key-do-not-use-in-production' +DEBUG = True +ALLOWED_HOSTS = [] + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'crm_core.apps.CrmCoreConfig', + 'custom_objects.apps.CustomObjectsConfig', + 'workflows.apps.WorkflowsConfig', + 'outreach.apps.OutreachConfig', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'openforce.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + +LANGUAGE_CODE = 'en-us' +TIME_ZONE = 'UTC' +USE_I18N = True +USE_TZ = True +STATIC_URL = 'static/' +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/openforce/settings/test.py b/openforce/settings/test.py new file mode 100644 index 0000000..bfbde83 --- /dev/null +++ b/openforce/settings/test.py @@ -0,0 +1,8 @@ +from .base import * + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': ':memory:', + } +} diff --git a/openforce/urls.py b/openforce/urls.py new file mode 100644 index 0000000..dfc7362 --- /dev/null +++ b/openforce/urls.py @@ -0,0 +1,6 @@ +from django.contrib import admin +from django.urls import path + +urlpatterns = [ + path('admin/', admin.site.urls), +] diff --git a/openforce/wsgi.py b/openforce/wsgi.py new file mode 100644 index 0000000..2a3ddf1 --- /dev/null +++ b/openforce/wsgi.py @@ -0,0 +1,5 @@ +import os +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'openforce.settings.base') +application = get_wsgi_application() diff --git a/outreach/__init__.py b/outreach/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/outreach/apps.py b/outreach/apps.py new file mode 100644 index 0000000..1bae190 --- /dev/null +++ b/outreach/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + +class OutreachConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "outreach" diff --git a/outreach/migrations/0001_initial.py b/outreach/migrations/0001_initial.py new file mode 100644 index 0000000..f41c8ef --- /dev/null +++ b/outreach/migrations/0001_initial.py @@ -0,0 +1,21 @@ +# Generated by Django 4.2.30 on 2026-09-26 07:21 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Campaign', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255)), + ], + ), + ] diff --git a/outreach/migrations/__init__.py b/outreach/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/outreach/models.py b/outreach/models.py new file mode 100644 index 0000000..46e1ecd --- /dev/null +++ b/outreach/models.py @@ -0,0 +1,4 @@ +from django.db import models + +class Campaign(models.Model): + name = models.CharField(max_length=255) diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..50d8f76 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,4 @@ +[pytest] +DJANGO_SETTINGS_MODULE = openforce.settings.test +python_files = tests.py test_*.py *_tests.py +addopts = -v --tb=short diff --git a/workflows/__init__.py b/workflows/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/workflows/apps.py b/workflows/apps.py new file mode 100644 index 0000000..1c38c56 --- /dev/null +++ b/workflows/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + +class WorkflowsConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "workflows" diff --git a/workflows/engine.py b/workflows/engine.py new file mode 100644 index 0000000..d14b53c --- /dev/null +++ b/workflows/engine.py @@ -0,0 +1,3 @@ +class WorkflowEngine: + pass + diff --git a/workflows/migrations/0001_initial.py b/workflows/migrations/0001_initial.py new file mode 100644 index 0000000..f77ff60 --- /dev/null +++ b/workflows/migrations/0001_initial.py @@ -0,0 +1,21 @@ +# Generated by Django 4.2.30 on 2026-09-26 07:21 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='WorkflowItem', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255)), + ], + ), + ] diff --git a/workflows/migrations/__init__.py b/workflows/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/workflows/models.py b/workflows/models.py new file mode 100644 index 0000000..4622327 --- /dev/null +++ b/workflows/models.py @@ -0,0 +1,4 @@ +from django.db import models + +class WorkflowItem(models.Model): + name = models.CharField(max_length=255)