Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/55 #152

Merged
merged 17 commits into from
Jul 8, 2022
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ black = "==22.3.0"
decorator = "==4.4.2"
docutils = "==0.16"
coverage = "==5.5"
factory-boy = "==3.2.1"
flake8 = "==4.0.1"
flake8-isort = "==4.1.1"
importlib-metadata = "==3.7.3"
Expand Down
42 changes: 33 additions & 9 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Empty file added campaigns/__init__.py
Empty file.
82 changes: 82 additions & 0 deletions campaigns/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import json
from typing import Any, Callable, Dict, List, Optional, Set, Union

from django.contrib import admin
from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from django.urls import URLPattern, path

from campaigns.models import Campaign
from drip.models import Drip
from drip.utils import get_simple_fields, get_user_model

User = get_user_model()


class DripInline(admin.TabularInline):
model = Drip


class CampaignAdmin(admin.ModelAdmin):
inlines = [
DripInline,
]
users_fields: Union[str, List[str]] = []

def av(self, view: Callable) -> Callable:
return self.admin_site.admin_view(view)

def timeline(
self,
request: WSGIRequest,
drip_id: int,
into_past: int,
into_future: int,
) -> HttpResponse:
"""
Return a list of people who should get emails.
"""

campaign = get_object_or_404(Campaign, id=drip_id)

shifted_drips = []
for drip in campaign.drip_set.all():
seen_users: Set[int] = set()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We aren't indicating the type of the variables, you can remove this if you want. Not mandatory

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I leave like this because of mypy.

for shifted_drip in drip.drip.walk(into_past=int(into_past), into_future=int(into_future) + 1):
shifted_drip.prune()
shifted_drips.append(
{
"drip_model": drip,
"drip": shifted_drip,
"qs": shifted_drip.get_queryset().exclude(
id__in=seen_users,
),
},
)
seen_users.update(shifted_drip.get_queryset().values_list("id", flat=True))

return render(request, "campaign/timeline.html", locals())

def build_extra_context(self, extra_context: Optional[Dict[str, Any]]) -> Dict[str, Any]:
extra_context = extra_context or {}
User = get_user_model()
if not self.users_fields:
self.users_fields = json.dumps(get_simple_fields(User))
extra_context["field_data"] = self.users_fields
return extra_context

def get_urls(self) -> List[URLPattern]:
urls = super(CampaignAdmin, self).get_urls()
my_urls = [
path(
"<int:drip_id>/timeline/<int:into_past>/<int:into_future>/",
self.av(self.timeline),
name="campaign_drip_timeline",
),
]

return my_urls + urls


admin.site.register(Campaign, CampaignAdmin)
5 changes: 5 additions & 0 deletions campaigns/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class CampaignsConfig(AppConfig):
name = "campaigns"
22 changes: 22 additions & 0 deletions campaigns/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Generated by Django 3.0.7 on 2020-12-30 21:11

from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name="Campaign",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
("name", models.CharField(default="Unnamed Campaign", max_length=256)),
("delete_drips", models.BooleanField(default=True)),
],
),
]
Empty file.
11 changes: 11 additions & 0 deletions campaigns/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from django.db import models


class Campaign(models.Model):
name = models.CharField(max_length=256, default="Unnamed Campaign")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could remove the default since it's mandatory

delete_drips = models.BooleanField(default=True)

def delete(self, using=None, keep_parents=False):
if self.delete_drips:
self.drip_set.all().delete()
super().delete(using, keep_parents)
19 changes: 19 additions & 0 deletions campaigns/templates/admin/campaigns/change_form.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{% extends "admin/change_form.html" %} {% load i18n static admin_list admin_urls %} {% block object-tools-items %}
<li>
<a href="{% url 'admin:campaign_drip_timeline' original.id 4 7 %}" class=""
>View Timeline</a
>
</li>
<li>
<a href="{% url 'admin:campaigns_campaign_history' original.pk %}" class="historylink">{% translate "History" %}</a>
</li>
{% if has_absolute_url %}
<li>
<a
href="../../../r/{{ content_type_id }}/{{ object_id }}/"
class="viewsitelink"
>{% trans "View on site" %}</a
>
</li>
{% endif%}
{% endblock %}
21 changes: 21 additions & 0 deletions campaigns/templates/campaign/timeline.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{% extends "admin/base_site.html" %}
{% load i18n static admin_modify %}
{% load admin_urls %}

{% block title %}Viewing Timeline for {{ drip.name }}{% endblock title %}

{% block breadcrumbs %}{% endblock %}

{% block content %}
<h1>{{ drip.name }} Schedule:</h1>

<div class="content-main">
<ul>{% for pack in shifted_drips %}
<li><strong>{% if pack.drip.now_shift_kwargs.days != 0 %}{{ pack.drip.now }}{% else %}today!{% endif %}</strong>{% if pack.qs %}
<ul>{% for user in pack.qs %}{% if user.email %}
<li><a href="{% url 'admin:drip_drip_change' pack.drip_model.pk %}">Drip ({{pack.drip_model}})</a> {{ user.email }} - {{ user.id }} - <a href="{% url 'admin:view_drip_email' drip_id into_past into_future user.id %}">view email</a></li>
{% endif %}{% endfor %}</ul>
{% endif %}</li>
{% endfor %}</ul>
</div>
{% endblock content %}
Empty file added campaigns/tests/__init__.py
Empty file.
22 changes: 22 additions & 0 deletions campaigns/tests/factories.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from factory import Faker, SubFactory
from factory.django import DjangoModelFactory

from campaigns.models import Campaign
from drip.models import Drip


class CampaignFactory(DjangoModelFactory):
name = Faker("word")
delete_drips = Faker("pybool")

class Meta:
model = Campaign


class DripFactory(DjangoModelFactory):
name = Faker("sentences", nb=3)
campaign = SubFactory(CampaignFactory)

class Meta:
model = Drip
django_get_or_create = ("name",)
43 changes: 43 additions & 0 deletions campaigns/tests/test_campaigns.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import random
from typing import Any, List

import pytest

from campaigns.models import Campaign
from campaigns.tests.factories import CampaignFactory, DripFactory
from drip.models import Drip

pytestmark = pytest.mark.django_db


def _drips_generator(amount: int, **drip_extra_args: Any) -> List[Campaign]:
return DripFactory.create_batch(amount, **drip_extra_args)


class TestCaseCampaign:
def test_campaings_creation(self):
campaign = CampaignFactory()
drip_count = random.randint(5, 15)
_drips_generator(drip_count, campaign=campaign)

assert len(campaign.drip_set.all()) == drip_count

@pytest.mark.parametrize(
("delete_drips, drip_count, drip_count_after_delete"),
(
(True, 10, 0),
(False, 10, 10),
),
)
def test_remove_campaings(
self,
delete_drips: bool,
drip_count: int,
drip_count_after_delete: int,
):
campaign = CampaignFactory(delete_drips=delete_drips)
_drips_generator(drip_count, campaign=campaign)

campaign.delete()

assert Drip.objects.count() == drip_count_after_delete
2 changes: 1 addition & 1 deletion drip/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "1.13.8"
__version__ = "1.14.0"
20 changes: 20 additions & 0 deletions drip/migrations/0003_drip_campaign.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Generated by Django 3.0.7 on 2020-12-30 22:10

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('campaigns', '0001_initial'),
('drip', '0002_querysetrule_rule_type'),
]

operations = [
migrations.AddField(
model_name='drip',
name='campaign',
field=models.ForeignKey(blank=True, help_text='If set, this is the campaign to which this Drip belongs to.', null=True, on_delete=django.db.models.deletion.CASCADE, to='campaigns.Campaign'),
),
]
Loading