Add Django site, Docker packaging, and beta/prod Gitea deploys.
Unignore site/ (was blocked by mkdocs /site rule), add compose/Docker/uv tooling, and split deploys so push to main goes to beta while prod stays manual.
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
from django.contrib import admin
|
||||
|
||||
from analytics.models import Attribution, UTMVisit
|
||||
|
||||
|
||||
@admin.register(UTMVisit)
|
||||
class UTMVisitAdmin(admin.ModelAdmin):
|
||||
list_display = ("utm_source", "utm_campaign", "path", "created_at")
|
||||
search_fields = ("utm_source", "utm_campaign", "correlation_id")
|
||||
|
||||
|
||||
@admin.register(Attribution)
|
||||
class AttributionAdmin(admin.ModelAdmin):
|
||||
list_display = ("lead", "utm_source", "utm_campaign", "created_at")
|
||||
@@ -0,0 +1,6 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class AnalyticsConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "analytics"
|
||||
@@ -0,0 +1,62 @@
|
||||
from django.utils.crypto import get_random_string
|
||||
|
||||
from analytics.models import Attribution, UTMVisit
|
||||
|
||||
|
||||
CORRELATION_COOKIE = "ms_cid"
|
||||
|
||||
|
||||
class UTMTrackingMiddleware:
|
||||
"""Capture UTM params into UTMVisit and stash a correlation id cookie."""
|
||||
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
|
||||
def __call__(self, request):
|
||||
cid = request.COOKIES.get(CORRELATION_COOKIE) or get_random_string(32)
|
||||
request.utm_correlation_id = cid
|
||||
|
||||
params = request.GET
|
||||
has_utm = any(params.get(k) for k in (
|
||||
"utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"
|
||||
))
|
||||
if has_utm or params.get("utm_source"):
|
||||
UTMVisit.objects.create(
|
||||
correlation_id=cid,
|
||||
path=request.path[:512],
|
||||
referrer=(request.META.get("HTTP_REFERER") or "")[:1024],
|
||||
utm_source=params.get("utm_source", "")[:128],
|
||||
utm_medium=params.get("utm_medium", "")[:128],
|
||||
utm_campaign=params.get("utm_campaign", "")[:128],
|
||||
utm_term=params.get("utm_term", "")[:128],
|
||||
utm_content=params.get("utm_content", "")[:128],
|
||||
user_agent=(request.META.get("HTTP_USER_AGENT") or "")[:512],
|
||||
)
|
||||
|
||||
response = self.get_response(request)
|
||||
if CORRELATION_COOKIE not in request.COOKIES:
|
||||
response.set_cookie(
|
||||
CORRELATION_COOKIE,
|
||||
cid,
|
||||
max_age=60 * 60 * 24 * 30,
|
||||
samesite="Lax",
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
def attribute_lead_from_request(request, lead) -> Attribution | None:
|
||||
cid = getattr(request, "utm_correlation_id", None) or request.COOKIES.get(
|
||||
CORRELATION_COOKIE
|
||||
)
|
||||
visit = None
|
||||
if cid:
|
||||
visit = (
|
||||
UTMVisit.objects.filter(correlation_id=cid).order_by("-created_at").first()
|
||||
)
|
||||
return Attribution.objects.create(
|
||||
lead=lead,
|
||||
visit=visit,
|
||||
utm_source=visit.utm_source if visit else "",
|
||||
utm_medium=visit.utm_medium if visit else "",
|
||||
utm_campaign=visit.utm_campaign if visit else "",
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
# Generated by Django 6.1 on 2026-08-06 18:01
|
||||
|
||||
import django.db.models.deletion
|
||||
import uuid
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
('leads', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='UTMVisit',
|
||||
fields=[
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
|
||||
('correlation_id', models.CharField(db_index=True, max_length=64)),
|
||||
('path', models.CharField(blank=True, max_length=512)),
|
||||
('referrer', models.URLField(blank=True, max_length=1024)),
|
||||
('utm_source', models.CharField(blank=True, max_length=128)),
|
||||
('utm_medium', models.CharField(blank=True, max_length=128)),
|
||||
('utm_campaign', models.CharField(blank=True, max_length=128)),
|
||||
('utm_term', models.CharField(blank=True, max_length=128)),
|
||||
('utm_content', models.CharField(blank=True, max_length=128)),
|
||||
('user_agent', models.CharField(blank=True, max_length=512)),
|
||||
],
|
||||
options={
|
||||
'ordering': ['-created_at'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Attribution',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('utm_source', models.CharField(blank=True, max_length=128)),
|
||||
('utm_medium', models.CharField(blank=True, max_length=128)),
|
||||
('utm_campaign', models.CharField(blank=True, max_length=128)),
|
||||
('lead', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='attribution', to='leads.lead')),
|
||||
('visit', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='analytics.utmvisit')),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,37 @@
|
||||
from django.db import models
|
||||
|
||||
from core.models import TimeStampedModel, UUIDPrimaryKeyModel
|
||||
from leads.models import Lead
|
||||
|
||||
|
||||
class UTMVisit(UUIDPrimaryKeyModel, TimeStampedModel):
|
||||
correlation_id = models.CharField(max_length=64, db_index=True)
|
||||
path = models.CharField(max_length=512, blank=True)
|
||||
referrer = models.URLField(blank=True, max_length=1024)
|
||||
utm_source = models.CharField(max_length=128, blank=True)
|
||||
utm_medium = models.CharField(max_length=128, blank=True)
|
||||
utm_campaign = models.CharField(max_length=128, blank=True)
|
||||
utm_term = models.CharField(max_length=128, blank=True)
|
||||
utm_content = models.CharField(max_length=128, blank=True)
|
||||
user_agent = models.CharField(max_length=512, blank=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ["-created_at"]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.utm_source or 'direct'} / {self.path}"
|
||||
|
||||
|
||||
class Attribution(TimeStampedModel):
|
||||
lead = models.OneToOneField(
|
||||
Lead, on_delete=models.CASCADE, related_name="attribution"
|
||||
)
|
||||
visit = models.ForeignKey(
|
||||
UTMVisit, null=True, blank=True, on_delete=models.SET_NULL
|
||||
)
|
||||
utm_source = models.CharField(max_length=128, blank=True)
|
||||
utm_medium = models.CharField(max_length=128, blank=True)
|
||||
utm_campaign = models.CharField(max_length=128, blank=True)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"attr {self.lead_id} ← {self.utm_source or 'direct'}"
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Analytics services."""
|
||||
|
||||
from analytics.middleware import attribute_lead_from_request # noqa: F401
|
||||
@@ -0,0 +1,124 @@
|
||||
{% extends "portal_base.html" %}
|
||||
{% block title %}Analytics · Portal{% endblock %}
|
||||
{% block topbar_title %}Analytics{% endblock %}
|
||||
{% block portal_content %}
|
||||
<div class="stat-row">
|
||||
<div class="stat-card">
|
||||
<div class="label">Views (last 30 days)</div>
|
||||
<div class="value">{{ visits_last_30_days }}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="label">UTM landings</div>
|
||||
<div class="value">{{ total_visits }}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="label">Attributed leads</div>
|
||||
<div class="value">{{ total_attributed }}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="label">Top source</div>
|
||||
<div class="value" style="font-size:18px">{{ top_source|default:"—" }}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="label">Top campaign</div>
|
||||
<div class="value" style="font-size:18px">{{ top_campaign|default:"—" }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel">
|
||||
<div class="panel-h"><h2>Landing volume by source</h2></div>
|
||||
<div class="panel-b">
|
||||
<div class="chart-placeholder">
|
||||
{% for row in visits_by_source|slice:":8" %}
|
||||
<div class="bar" style="height:{{ row.bar_pct }}%" title="{{ row.utm_source|default:'(direct)' }}: {{ row.count }}"></div>
|
||||
{% empty %}
|
||||
<div class="bar" style="height:12%"></div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel">
|
||||
<div class="panel-h"><h2>UTM landings</h2><span class="muted" style="font-size:12px">From ?utm_* hits</span></div>
|
||||
<div class="panel-b" style="padding:0">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Source</th>
|
||||
<th>Medium</th>
|
||||
<th>Campaign</th>
|
||||
<th>Landings</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for row in visits_by_combo %}
|
||||
<tr>
|
||||
<td>{{ row.utm_source|default:"(direct)" }}</td>
|
||||
<td>{{ row.utm_medium|default:"—" }}</td>
|
||||
<td>{{ row.utm_campaign|default:"—" }}</td>
|
||||
<td>{{ row.count }}</td>
|
||||
</tr>
|
||||
{% empty %}
|
||||
<tr><td colspan="4" class="empty-state">No UTM landings yet. Open a public URL with ?utm_source=…</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel">
|
||||
<div class="panel-h"><h2>Recent landings</h2></div>
|
||||
<div class="panel-b" style="padding:0">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>When</th>
|
||||
<th>Path</th>
|
||||
<th>Source</th>
|
||||
<th>Campaign</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for visit in recent_visits %}
|
||||
<tr>
|
||||
<td>{{ visit.created_at|date:"M j, g:i A" }}</td>
|
||||
<td>{{ visit.path }}</td>
|
||||
<td>{{ visit.utm_source|default:"—" }}</td>
|
||||
<td>{{ visit.utm_campaign|default:"—" }}</td>
|
||||
</tr>
|
||||
{% empty %}
|
||||
<tr><td colspan="4" class="empty-state">No visits recorded.</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel">
|
||||
<div class="panel-h"><h2>Lead attribution</h2><span class="muted" style="font-size:12px">After contact-form submit</span></div>
|
||||
<div class="panel-b" style="padding:0">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Source</th>
|
||||
<th>Medium</th>
|
||||
<th>Campaign</th>
|
||||
<th>Leads</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for row in leads_by_combo %}
|
||||
<tr>
|
||||
<td>{{ row.utm_source|default:"(direct)" }}</td>
|
||||
<td>{{ row.utm_medium|default:"—" }}</td>
|
||||
<td>{{ row.utm_campaign|default:"—" }}</td>
|
||||
<td>{{ row.count }}</td>
|
||||
</tr>
|
||||
{% empty %}
|
||||
<tr><td colspan="4" class="empty-state">No attributed leads yet — submit the contact form after a UTM landing.</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,9 @@
|
||||
from django.urls import path
|
||||
|
||||
from analytics import views
|
||||
|
||||
app_name = "analytics"
|
||||
|
||||
urlpatterns = [
|
||||
path("", views.report, name="report"),
|
||||
]
|
||||
@@ -0,0 +1,74 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.db.models import Count
|
||||
from django.shortcuts import render
|
||||
from django.utils import timezone
|
||||
|
||||
from analytics.models import Attribution, UTMVisit
|
||||
|
||||
|
||||
def _bar_pct(rows, key="count"):
|
||||
max_count = max((row[key] for row in rows), default=1) or 1
|
||||
for row in rows:
|
||||
row["bar_pct"] = max(12, int(100 * row[key] / max_count))
|
||||
return rows
|
||||
|
||||
|
||||
@login_required
|
||||
def report(request):
|
||||
since_30d = timezone.now() - timedelta(days=30)
|
||||
visits_last_30_days = UTMVisit.objects.filter(created_at__gte=since_30d).count()
|
||||
|
||||
visits_by_source = _bar_pct(
|
||||
list(
|
||||
UTMVisit.objects.values("utm_source")
|
||||
.annotate(count=Count("id"))
|
||||
.order_by("-count")[:20]
|
||||
)
|
||||
)
|
||||
visits_by_combo = list(
|
||||
UTMVisit.objects.values("utm_source", "utm_medium", "utm_campaign")
|
||||
.annotate(count=Count("id"))
|
||||
.order_by("-count")[:50]
|
||||
)
|
||||
top_visit = visits_by_source[0] if visits_by_source else None
|
||||
top_visit_campaign = (
|
||||
UTMVisit.objects.exclude(utm_campaign="")
|
||||
.values("utm_campaign")
|
||||
.annotate(count=Count("id"))
|
||||
.order_by("-count")
|
||||
.first()
|
||||
)
|
||||
|
||||
leads_by_source = _bar_pct(
|
||||
list(
|
||||
Attribution.objects.values("utm_source")
|
||||
.annotate(count=Count("id"))
|
||||
.order_by("-count")[:20]
|
||||
)
|
||||
)
|
||||
leads_by_combo = list(
|
||||
Attribution.objects.values("utm_source", "utm_medium", "utm_campaign")
|
||||
.annotate(count=Count("id"))
|
||||
.order_by("-count")[:50]
|
||||
)
|
||||
|
||||
recent_visits = UTMVisit.objects.all()[:25]
|
||||
|
||||
return render(
|
||||
request,
|
||||
"analytics/report.html",
|
||||
{
|
||||
"visits_last_30_days": visits_last_30_days,
|
||||
"total_visits": UTMVisit.objects.count(),
|
||||
"total_attributed": Attribution.objects.count(),
|
||||
"top_source": (top_visit or {}).get("utm_source") or "(direct)",
|
||||
"top_campaign": (top_visit_campaign or {}).get("utm_campaign") or "—",
|
||||
"visits_by_source": visits_by_source,
|
||||
"visits_by_combo": visits_by_combo,
|
||||
"leads_by_source": leads_by_source,
|
||||
"leads_by_combo": leads_by_combo,
|
||||
"recent_visits": recent_visits,
|
||||
},
|
||||
)
|
||||
Reference in New Issue
Block a user