Scaffold Phase 1 CRM models and apps
This commit is contained in:
commit
86afab03bc
35 changed files with 876 additions and 0 deletions
21
.coveragerc
Normal file
21
.coveragerc
Normal file
|
|
@ -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
|
||||
9
.gitignore
vendored
Normal file
9
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
*.pyc
|
||||
__pycache__/
|
||||
*.sqlite3
|
||||
.venv/
|
||||
.coverage
|
||||
htmlcov/
|
||||
.pytest_cache/
|
||||
media/
|
||||
staticfiles/
|
||||
0
crm_core/__init__.py
Normal file
0
crm_core/__init__.py
Normal file
5
crm_core/apps.py
Normal file
5
crm_core/apps.py
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
from django.apps import AppConfig
|
||||
|
||||
class CrmCoreConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'crm_core'
|
||||
137
crm_core/migrations/0001_initial.py
Normal file
137
crm_core/migrations/0001_initial.py
Normal file
|
|
@ -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'],
|
||||
},
|
||||
),
|
||||
]
|
||||
0
crm_core/migrations/__init__.py
Normal file
0
crm_core/migrations/__init__.py
Normal file
270
crm_core/models.py
Normal file
270
crm_core/models.py
Normal file
|
|
@ -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}"
|
||||
49
crm_core/serializers.py
Normal file
49
crm_core/serializers.py
Normal file
|
|
@ -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)
|
||||
98
crm_core/services.py
Normal file
98
crm_core/services.py
Normal file
|
|
@ -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,
|
||||
}
|
||||
80
crm_core/views.py
Normal file
80
crm_core/views.py
Normal file
|
|
@ -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']
|
||||
0
custom_objects/__init__.py
Normal file
0
custom_objects/__init__.py
Normal file
5
custom_objects/apps.py
Normal file
5
custom_objects/apps.py
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
from django.apps import AppConfig
|
||||
|
||||
class CustomObjectsConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'custom_objects'
|
||||
28
custom_objects/migrations/0001_initial.py
Normal file
28
custom_objects/migrations/0001_initial.py
Normal file
|
|
@ -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)),
|
||||
],
|
||||
),
|
||||
]
|
||||
0
custom_objects/migrations/__init__.py
Normal file
0
custom_objects/migrations/__init__.py
Normal file
7
custom_objects/models.py
Normal file
7
custom_objects/models.py
Normal file
|
|
@ -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)
|
||||
18
manage.py
Executable file
18
manage.py
Executable file
|
|
@ -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()
|
||||
0
openforce/__init__.py
Normal file
0
openforce/__init__.py
Normal file
0
openforce/settings.py
Normal file
0
openforce/settings.py
Normal file
0
openforce/settings/__init__.py
Normal file
0
openforce/settings/__init__.py
Normal file
63
openforce/settings/base.py
Normal file
63
openforce/settings/base.py
Normal file
|
|
@ -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'
|
||||
8
openforce/settings/test.py
Normal file
8
openforce/settings/test.py
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
from .base import *
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': ':memory:',
|
||||
}
|
||||
}
|
||||
6
openforce/urls.py
Normal file
6
openforce/urls.py
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
from django.contrib import admin
|
||||
from django.urls import path
|
||||
|
||||
urlpatterns = [
|
||||
path('admin/', admin.site.urls),
|
||||
]
|
||||
5
openforce/wsgi.py
Normal file
5
openforce/wsgi.py
Normal file
|
|
@ -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()
|
||||
0
outreach/__init__.py
Normal file
0
outreach/__init__.py
Normal file
5
outreach/apps.py
Normal file
5
outreach/apps.py
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
from django.apps import AppConfig
|
||||
|
||||
class OutreachConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "outreach"
|
||||
21
outreach/migrations/0001_initial.py
Normal file
21
outreach/migrations/0001_initial.py
Normal file
|
|
@ -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)),
|
||||
],
|
||||
),
|
||||
]
|
||||
0
outreach/migrations/__init__.py
Normal file
0
outreach/migrations/__init__.py
Normal file
4
outreach/models.py
Normal file
4
outreach/models.py
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
from django.db import models
|
||||
|
||||
class Campaign(models.Model):
|
||||
name = models.CharField(max_length=255)
|
||||
4
pytest.ini
Normal file
4
pytest.ini
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
[pytest]
|
||||
DJANGO_SETTINGS_MODULE = openforce.settings.test
|
||||
python_files = tests.py test_*.py *_tests.py
|
||||
addopts = -v --tb=short
|
||||
0
workflows/__init__.py
Normal file
0
workflows/__init__.py
Normal file
5
workflows/apps.py
Normal file
5
workflows/apps.py
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
from django.apps import AppConfig
|
||||
|
||||
class WorkflowsConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "workflows"
|
||||
3
workflows/engine.py
Normal file
3
workflows/engine.py
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
class WorkflowEngine:
|
||||
pass
|
||||
|
||||
21
workflows/migrations/0001_initial.py
Normal file
21
workflows/migrations/0001_initial.py
Normal file
|
|
@ -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)),
|
||||
],
|
||||
),
|
||||
]
|
||||
0
workflows/migrations/__init__.py
Normal file
0
workflows/migrations/__init__.py
Normal file
4
workflows/models.py
Normal file
4
workflows/models.py
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
from django.db import models
|
||||
|
||||
class WorkflowItem(models.Model):
|
||||
name = models.CharField(max_length=255)
|
||||
Loading…
Reference in a new issue