django-ctct 0.0.1.dev7__tar.gz → 0.0.1.dev8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/PKG-INFO +4 -4
  2. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/README.md +3 -3
  3. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/django_ctct/admin.py +138 -12
  4. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/django_ctct/conf.py +2 -2
  5. django_ctct-0.0.1.dev8/django_ctct/exceptions.py +15 -0
  6. django_ctct-0.0.1.dev8/django_ctct/forms.py +46 -0
  7. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/django_ctct/management/commands/import_ctct.py +11 -11
  8. django_ctct-0.0.1.dev8/django_ctct/managers.py +44 -0
  9. django_ctct-0.0.1.dev8/django_ctct/migrations/0002_alter_campaignactivity_html_content.py +19 -0
  10. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/django_ctct/models.py +53 -53
  11. django_ctct-0.0.1.dev7/django_ctct/managers.py → django_ctct-0.0.1.dev8/django_ctct/remote.py +67 -72
  12. django_ctct-0.0.1.dev8/django_ctct/services.py +26 -0
  13. django_ctct-0.0.1.dev8/django_ctct/templates/admin/compose_campaign.html +11 -0
  14. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/django_ctct/todo.md +33 -0
  15. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/pyproject.toml +14 -8
  16. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/pyproject.toml.orig +11 -8
  17. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/django_ctct/__init__.py +0 -0
  18. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/django_ctct/apps.py +0 -0
  19. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/django_ctct/management/__init__.py +0 -0
  20. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/django_ctct/management/commands/__init__.py +0 -0
  21. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/django_ctct/migrations/0001_initial.py +0 -0
  22. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/django_ctct/migrations/__init__.py +0 -0
  23. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/django_ctct/py.typed +0 -0
  24. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/django_ctct/urls.py +0 -0
  25. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/django_ctct/utils.py +0 -0
  26. {django_ctct-0.0.1.dev7 → django_ctct-0.0.1.dev8}/django_ctct/views.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: django-ctct
3
- Version: 0.0.1.dev7
3
+ Version: 0.0.1.dev8
4
4
  Summary: A Django interface for the Constant Contact API
5
5
  Author: Geoffrey Eisenbarth
6
6
  Author-email: Geoffrey Eisenbarth <geoffrey.eisenbarth@gmail.com>
@@ -172,13 +172,13 @@ To lint and format:
172
172
 
173
173
  Once version 0.0.1 is released on PyPI, we hope to implement the following new features (in no particular order):
174
174
 
175
- * Background task support using `django-tasks` (which hopefully will merge into Django). This will be controlled by the `CTCT_ENQUEUE_DEFAULT` setting.
175
+ * Background task support using `django-tasks` (which hopefully will merge into Django). This will be controlled by the `CTCT_ENQUEUE_DEFAULT` setting.
176
176
  * Add `models.CheckConstraint` and `models.UniqueConstraint` constraints that are currently commented out.
177
-
177
+
178
178
 
179
179
  I'm always open to new suggestions, so please reach out on GitHub: https://github.com/geoffrey-eisenbarth/django-ctct/
180
180
 
181
-
181
+
182
182
  ## License
183
183
 
184
184
  This package is currently distributed under the MIT license.
@@ -157,13 +157,13 @@ To lint and format:
157
157
 
158
158
  Once version 0.0.1 is released on PyPI, we hope to implement the following new features (in no particular order):
159
159
 
160
- * Background task support using `django-tasks` (which hopefully will merge into Django). This will be controlled by the `CTCT_ENQUEUE_DEFAULT` setting.
160
+ * Background task support using `django-tasks` (which hopefully will merge into Django). This will be controlled by the `CTCT_ENQUEUE_DEFAULT` setting.
161
161
  * Add `models.CheckConstraint` and `models.UniqueConstraint` constraints that are currently commented out.
162
-
162
+
163
163
 
164
164
  I'm always open to new suggestions, so please reach out on GitHub: https://github.com/geoffrey-eisenbarth/django-ctct/
165
165
 
166
-
166
+
167
167
  ## License
168
168
 
169
169
  This package is currently distributed under the MIT license.
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import functools
4
+ from abc import ABCMeta, abstractmethod
4
5
  from collections.abc import Callable, Iterable
5
6
  from typing import TYPE_CHECKING
6
7
 
@@ -13,14 +14,19 @@ from django.db.models import Case, Count, F, FloatField, Model, Q, QuerySet, Whe
13
14
  from django.db.models.functions import Cast
14
15
  from django.forms import ModelForm
15
16
  from django.forms.models import BaseInlineFormSet, BaseModelFormSet
16
- from django.http import HttpRequest
17
- from django.urls import reverse
17
+ from django.forms.widgets import MediaDefiningClass
18
+ from django.http import Http404, HttpRequest, HttpResponse
19
+ from django.template.response import TemplateResponse
20
+ from django.urls import path, reverse
21
+ from django.urls.resolvers import URLPattern
18
22
  from django.utils.formats import date_format
19
23
  from django.utils.html import format_html
20
- from django.utils.translation import gettext as _
24
+ from django.utils.translation import gettext
25
+ from django.utils.translation import gettext_lazy as _
21
26
  from requests.exceptions import HTTPError
22
27
 
23
28
  from django_ctct.conf import get_setting
29
+ from django_ctct.forms import CampaignComposeForm
24
30
  from django_ctct.models import (
25
31
  CampaignActivity,
26
32
  CampaignSummary,
@@ -34,6 +40,7 @@ from django_ctct.models import (
34
40
  CustomField,
35
41
  EmailCampaign,
36
42
  )
43
+ from django_ctct.services import sync_campaign_for_host
37
44
 
38
45
  if TYPE_CHECKING:
39
46
  from typing import Any, Concatenate
@@ -61,7 +68,7 @@ def catch_api_errors[S: admin.ModelAdmin[Any], **P](
61
68
  raise e # pragma: no cover
62
69
  self.message_user(
63
70
  request=request,
64
- message=format_html(_("ConstantContact: {error}"), error=str(e)),
71
+ message=format_html(gettext("ConstantContact: {error}"), error=str(e)),
65
72
  level=messages.ERROR,
66
73
  )
67
74
 
@@ -199,7 +206,7 @@ class ContactListForm(forms.ModelForm[ContactList]):
199
206
  widgets = {
200
207
  "description": forms.Textarea,
201
208
  }
202
- fields = "__all__"
209
+ fields = ["name", "description", "favorite"]
203
210
 
204
211
 
205
212
  class ContactListAdmin(RemoteModelAdmin[ContactList]):
@@ -326,9 +333,9 @@ class ContactStatusFilter(admin.SimpleListFilter):
326
333
  """Simple filter for CTCT Status."""
327
334
 
328
335
  STATUSES = (
329
- ("sync", _("Synced")),
330
- ("not_synced", _("Not Synced")),
331
- ("optout", _("Opted Out")),
336
+ ("sync", "Synced"),
337
+ ("not_synced", "Not Synced"),
338
+ ("optout", "Opted Out"),
332
339
  )
333
340
 
334
341
  title = "Status"
@@ -567,7 +574,7 @@ class CampaignActivityInlineForm(forms.ModelForm[CampaignActivity]):
567
574
 
568
575
  class Meta:
569
576
  model = CampaignActivity
570
- fields = "__all__"
577
+ fields = "__all__" # noqa: DJ007
571
578
 
572
579
 
573
580
  class CampaignActivityInline(admin.StackedInline[CampaignActivity, EmailCampaign]):
@@ -664,7 +671,7 @@ class EmailCampaignAdmin(RemoteModelAdmin[EmailCampaign]):
664
671
  campaign_created = not change
665
672
  campaign_updated = change and ("name" in form.changed_data)
666
673
  if campaign_created:
667
- EmailCampaign.remote.create(campaign) # type: ignore[misc]
674
+ EmailCampaign.remote.create(campaign)
668
675
  elif campaign_updated:
669
676
  EmailCampaign.remote.update(campaign)
670
677
 
@@ -676,7 +683,9 @@ class EmailCampaignAdmin(RemoteModelAdmin[EmailCampaign]):
676
683
  activity_form = activity_formset[0]
677
684
  else: # pragma: no cover
678
685
  raise ImproperlyConfigured(
679
- _("CampaignActivityInline must be present in EmailCampaignAdmin.inlines")
686
+ gettext(
687
+ "CampaignActivityInline must be present in EmailCampaignAdmin.inlines"
688
+ )
680
689
  )
681
690
 
682
691
  inline_changed = activity_form.changed_data and not campaign_created
@@ -720,7 +729,7 @@ class EmailCampaignAdmin(RemoteModelAdmin[EmailCampaign]):
720
729
  preview = ""
721
730
 
722
731
  message = format_html(
723
- _("The {name} “{obj}” has been {action}{preview}."),
732
+ gettext("The {name} “{obj}” has been {action}{preview}."),
724
733
  **{
725
734
  "name": campaign._meta.verbose_name,
726
735
  "obj": campaign,
@@ -807,3 +816,120 @@ def register_admin(site: admin.AdminSite | None = None) -> None:
807
816
 
808
817
 
809
818
  register_admin()
819
+
820
+
821
+ class AbstractAdminMeta(ABCMeta, MediaDefiningClass):
822
+ """Metaclass for CampaignHostAdminMixin to ensure it is abstract."""
823
+
824
+ ...
825
+
826
+
827
+ class CampaignHostModelAdmin[M: Model](
828
+ admin.ModelAdmin[M],
829
+ metaclass=AbstractAdminMeta,
830
+ ):
831
+ """Abstract base class for models that host a Campaign."""
832
+
833
+ campaign_field_name = "campaign"
834
+
835
+ @abstractmethod
836
+ def get_campaign_name(self, request: HttpRequest, obj: M) -> str: ...
837
+
838
+ @abstractmethod
839
+ def get_campaign_subject(self, request: HttpRequest, obj: M) -> str: ...
840
+
841
+ @abstractmethod
842
+ def get_campaign_preheader(self, request: HttpRequest, obj: M) -> str: ...
843
+
844
+ @abstractmethod
845
+ def get_campaign_html_content(self, request: HttpRequest, obj: M) -> str: ...
846
+
847
+ @abstractmethod
848
+ def get_campaign_contact_lists(
849
+ self,
850
+ request: HttpRequest,
851
+ obj: M,
852
+ ) -> QuerySet[ContactList]: ...
853
+
854
+ @abstractmethod
855
+ def get_campaign_send_preview(
856
+ self,
857
+ request: HttpRequest,
858
+ obj: M,
859
+ ) -> bool: ...
860
+
861
+ @abstractmethod
862
+ def get_campaign_preview_recipients(
863
+ self,
864
+ request: HttpRequest,
865
+ obj: M,
866
+ ) -> list[str]: ...
867
+
868
+ @abstractmethod
869
+ def get_campaign_preview_message(self, request: HttpRequest, obj: M) -> str: ...
870
+
871
+ def get_urls(self) -> list[URLPattern]:
872
+ urls = super().get_urls() + [
873
+ path(
874
+ "<int:pk>/compose-campaign/",
875
+ self.admin_site.admin_view(self.compose_campaign_view),
876
+ name="compose-campaign",
877
+ ),
878
+ ]
879
+ return urls
880
+
881
+ def compose_campaign_view(self, request: HttpRequest, pk: str) -> HttpResponse:
882
+ # - On `GET`: Pre-populates form with hook defaults (or existing campaign data if
883
+ # one is already attached) and renders template.
884
+ # - On `POST`: Validates `CampaignComposeForm`, calls `sync_campaign_for_host()`,
885
+ # sets Django success message, and redirects back to host change page.
886
+ # - Add "Create/Edit Email Campaign" button in object tools or change form template
887
+ # (`change_form_template`).
888
+ obj = self.get_object(request, pk)
889
+ if obj is None:
890
+ raise Http404(gettext("Object does not exist."))
891
+
892
+ if request.method == "POST":
893
+ form = CampaignComposeForm(request.POST)
894
+ if form.is_valid():
895
+ sync_campaign_for_host(obj, form.cleaned_data, self.campaign_field_name)
896
+
897
+ self.message_user(
898
+ request,
899
+ format_html(
900
+ gettext('The {name} "{obj}" has been synced with Constant Contact.'),
901
+ **{
902
+ "name": self.model._meta.verbose_name,
903
+ "obj": obj,
904
+ },
905
+ ),
906
+ )
907
+ return HttpResponse(
908
+ status=302,
909
+ headers={
910
+ "Location": reverse(
911
+ f"admin:{self.model._meta.app_label}_{self.model._meta.model_name}_change",
912
+ args=[obj.pk],
913
+ ),
914
+ },
915
+ )
916
+ elif request.method == "GET":
917
+ # TODO: Or existing campaign/activity data if one is already attached
918
+ initial_data = {
919
+ "name": self.get_campaign_name(request, obj),
920
+ "subject": self.get_campaign_subject(request, obj),
921
+ "preheader": self.get_campaign_preheader(request, obj),
922
+ "html_content": self.get_campaign_html_content(request, obj),
923
+ "contact_lists": self.get_campaign_contact_lists(request, obj),
924
+ "send_preview": self.get_campaign_send_preview(request, obj),
925
+ "preview_message": self.get_campaign_preview_message(request, obj),
926
+ "preview_recipients": self.get_campaign_preview_recipients(request, obj),
927
+ }
928
+ form = CampaignComposeForm(initial=initial_data)
929
+
930
+ context = dict(
931
+ self.admin_site.each_context(request),
932
+ opts=self.model._meta,
933
+ object=obj,
934
+ ) | {"form": form}
935
+ return TemplateResponse(request, "admin/compose_campaign.html", context)
@@ -14,7 +14,7 @@ from typing import Any, Literal, overload
14
14
 
15
15
  from django.conf import settings
16
16
 
17
- REQUIRED_SETTINGS: tuple[str, ...] = (
17
+ REQUIRED_SETTINGS = (
18
18
  "CTCT_PUBLIC_KEY",
19
19
  "CTCT_SECRET_KEY",
20
20
  "CTCT_REDIRECT_URI",
@@ -24,7 +24,7 @@ REQUIRED_SETTINGS: tuple[str, ...] = (
24
24
 
25
25
  # Values may be zero-argument callables, evaluated lazily so that defaults
26
26
  # can depend on other Django settings.
27
- DEFAULTS: dict[str, Any] = {
27
+ DEFAULTS = {
28
28
  "CTCT_USE_ADMIN": False,
29
29
  "CTCT_SYNC_ADMIN": False,
30
30
  "CTCT_ENQUEUE_DEFAULT": False,
@@ -0,0 +1,15 @@
1
+ from django.utils.translation import gettext as _
2
+
3
+
4
+ class LocalObjectDoesNotExist(Exception):
5
+ """Exception raised when a local object does not exist."""
6
+
7
+ def __init__(self, message: str = _("Must create object locally first.")) -> None:
8
+ super().__init__(message)
9
+
10
+
11
+ class RemoteObjectDoesNotExist(Exception):
12
+ """Exception raised when a remote object does not exist."""
13
+
14
+ def __init__(self, message: str = _("Must create object remotely first.")) -> None:
15
+ super().__init__(message)
@@ -0,0 +1,46 @@
1
+ from django import forms
2
+ from django.contrib.admin import widgets as admin_widgets
3
+ from django.utils.translation import gettext_lazy as _
4
+
5
+ from django_ctct.models import ContactList
6
+
7
+
8
+ class CampaignComposeForm(forms.Form):
9
+ # EmailCampaign fields
10
+ name = forms.CharField(
11
+ max_length=80,
12
+ label=_("Name"),
13
+ )
14
+ scheduled_datetime = forms.SplitDateTimeField(
15
+ required=False,
16
+ label=_("Scheduled Date and Time"),
17
+ )
18
+ send_preview = forms.BooleanField(
19
+ required=False,
20
+ label=_("Send Preview?"),
21
+ )
22
+ preview_message = forms.CharField(
23
+ widget=forms.Textarea, required=False, label=_("Preview Message")
24
+ )
25
+ preview_recipients = forms.CharField(
26
+ widget=forms.Textarea,
27
+ required=False,
28
+ label=_("Preview Recipients (comma-separated emails)"),
29
+ )
30
+
31
+ # CampaignActivity fields
32
+ subject = forms.CharField(max_length=80, label=_("Email Subject"))
33
+ preheader = forms.CharField(
34
+ max_length=120, required=False, label=_("Email Preheader")
35
+ )
36
+ html_content = forms.CharField(
37
+ widget=forms.Textarea, max_length=150000, label=_("HTML Content")
38
+ )
39
+ contact_lists = forms.ModelMultipleChoiceField(
40
+ queryset=ContactList.objects.all(),
41
+ widget=admin_widgets.FilteredSelectMultiple(
42
+ "Contact Lists",
43
+ is_stacked=False,
44
+ ),
45
+ label=_("Contact Lists"),
46
+ )
@@ -3,7 +3,7 @@ from __future__ import annotations
3
3
  from argparse import ArgumentParser
4
4
  from collections import defaultdict
5
5
  from collections.abc import Collection
6
- from typing import TYPE_CHECKING, cast
6
+ from typing import TYPE_CHECKING
7
7
  from uuid import UUID
8
8
 
9
9
  from django.core.management.base import BaseCommand
@@ -70,7 +70,7 @@ class Command(BaseCommand):
70
70
 
71
71
  if model._meta.auto_created and hasattr(model, "contactlist_id"):
72
72
  # Delete existing through model instances
73
- model.objects.all().delete() # type: ignore
73
+ model._default_manager.all().delete()
74
74
  update_conflicts = False
75
75
  unique_fields = update_fields = None
76
76
  elif issubclass(model, ContactCustomField):
@@ -154,12 +154,11 @@ class Command(BaseCommand):
154
154
  # CampaignActivities do not have a bulk API endpoint
155
155
  return self.import_campaign_activities()
156
156
 
157
- try:
157
+ if list_of_tuples := model.remote.all():
158
158
  # Split apart so we can save objs to db and get pks
159
- list_of_tuples = model.remote.all()
160
- objs, per_obj_list_of_related_objs = zip(*list_of_tuples) # type: ignore[assignment]
161
- except ValueError: # pragma: no cover
162
- # No values returned
159
+ objs = [obj for obj, _ in list_of_tuples]
160
+ per_obj_list_of_related_objs = [rel for _, rel in list_of_tuples]
161
+ else: # pragma: no cover
163
162
  return
164
163
 
165
164
  # Upsert models to get Django pks
@@ -199,10 +198,11 @@ class Command(BaseCommand):
199
198
  # Set related object pk and store in db
200
199
  for related_model, objs in list_of_related_objs:
201
200
  if issubclass(related_model, CampaignActivity):
202
- for obj in cast(list[CampaignActivity], objs):
203
- if obj.role == "primary_email":
204
- obj.campaign_id = campaign.pk
205
- obj.save()
201
+ for obj in objs:
202
+ if isinstance(obj, CampaignActivity):
203
+ if obj.role == "primary_email":
204
+ obj.campaign_id = campaign.pk
205
+ obj.save()
206
206
 
207
207
  # Then, fetch CampaignActivity details
208
208
  activities = CampaignActivity.objects.filter(
@@ -0,0 +1,44 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from django.db.models.manager import Manager
6
+ from django.urls import reverse
7
+ from django.utils.translation import gettext as _
8
+ from jwt import ExpiredSignatureError
9
+
10
+ if TYPE_CHECKING: # pragma: no cover
11
+ from django_ctct.models import Token
12
+
13
+
14
+ class TokenManager(Manager["Token"]):
15
+ """Local manager for Token with in-memory caching and automatic refresh."""
16
+
17
+ _cached_token: Token | None = None
18
+
19
+ def get_valid(self, force_refresh: bool = False) -> Token:
20
+ """Fetches active Token, refreshing remotely if expired or on 401."""
21
+ if not force_refresh and self._cached_token is not None:
22
+ if not self._cached_token.is_expired:
23
+ return self._cached_token
24
+
25
+ token = self.first()
26
+ if not token:
27
+ self._cached_token = None
28
+ raise ValueError(
29
+ _(
30
+ "No tokens in the database yet. "
31
+ f"Go to {reverse('ctct:auth')} and sign into ConstantContact."
32
+ )
33
+ )
34
+
35
+ if force_refresh or token.is_expired:
36
+ token = self.model.remote.refresh(token)
37
+ else:
38
+ try:
39
+ token.decode()
40
+ except ExpiredSignatureError:
41
+ token = self.model.remote.refresh(token)
42
+
43
+ self._cached_token = token
44
+ return token
@@ -0,0 +1,19 @@
1
+ # Generated by Django 6.1.1 on 2026-09-17 19:34
2
+
3
+ import django.core.validators
4
+ from django.db import migrations, models
5
+
6
+
7
+ class Migration(migrations.Migration):
8
+
9
+ dependencies = [
10
+ ('django_ctct', '0001_initial'),
11
+ ]
12
+
13
+ operations = [
14
+ migrations.AlterField(
15
+ model_name='campaignactivity',
16
+ name='html_content',
17
+ field=models.TextField(help_text='The HTML content for the email campaign activity', validators=[django.core.validators.MaxLengthValidator(150000)], verbose_name='HTML Content'),
18
+ ),
19
+ ]
@@ -11,15 +11,17 @@ from typing import (
11
11
  import jwt
12
12
  from django.conf import settings
13
13
  from django.core.validators import MaxLengthValidator, validate_email
14
- from django.db import models
14
+ from django.db import IntegrityError, models
15
15
  from django.db.models import Model
16
16
  from django.db.models.base import Model as BaseModel
17
17
  from django.db.models.fields import NOT_PROVIDED
18
18
  from django.utils import formats, timezone
19
+ from django.utils.translation import gettext
19
20
  from django.utils.translation import gettext_lazy as _
20
21
 
21
22
  from django_ctct.conf import get_setting
22
- from django_ctct.managers import (
23
+ from django_ctct.managers import TokenManager
24
+ from django_ctct.remote import (
23
25
  CampaignActivityRemoteManager,
24
26
  CampaignSummaryRemoteManager,
25
27
  ContactListRemoteManager,
@@ -27,7 +29,6 @@ from django_ctct.managers import (
27
29
  EmailCampaignRemoteManager,
28
30
  RemoteManager,
29
31
  Serializer,
30
- TokenManager,
31
32
  TokenRemoteManager,
32
33
  )
33
34
  from django_ctct.utils import to_dt
@@ -133,14 +134,6 @@ class Token(CreatedAtMixin, EndpointMixin, Model):
133
134
  verbose_name=_("Expires In"),
134
135
  )
135
136
 
136
- @property
137
- def expires_at(self) -> dt.datetime:
138
- return self.created_at + dt.timedelta(seconds=self.expires_in)
139
-
140
- @property
141
- def is_expired(self) -> bool:
142
- return timezone.now() >= (self.expires_at - dt.timedelta(seconds=60))
143
-
144
137
  class Meta:
145
138
  ordering = ("-created_at",)
146
139
 
@@ -152,6 +145,14 @@ class Token(CreatedAtMixin, EndpointMixin, Model):
152
145
  s = f"{self.token_type} Token (Expires: {expires_at})"
153
146
  return s
154
147
 
148
+ @property
149
+ def expires_at(self) -> dt.datetime:
150
+ return self.created_at + dt.timedelta(seconds=self.expires_in)
151
+
152
+ @property
153
+ def is_expired(self) -> bool:
154
+ return timezone.now() >= (self.expires_at - dt.timedelta(seconds=60))
155
+
155
156
  def decode(self) -> JsonDict:
156
157
  """Decode JWT Token, which also verifies that it hasn't expired.
157
158
 
@@ -178,8 +179,7 @@ class SerialModel(Model):
178
179
  API_EDITABLE_FIELDS: tuple[str, ...] = tuple()
179
180
  API_READONLY_FIELDS: tuple[str, ...] = ("api_id",)
180
181
 
181
- # Must explicitly specify both
182
- objects: ClassVar[models.Manager[Self]] = models.Manager()
182
+ objects: ClassVar[models.Manager[Self]]
183
183
  serializer: ClassVar[Serializer[Self]] = Serializer()
184
184
 
185
185
  class Meta:
@@ -221,8 +221,8 @@ class CTCTModel(SerialModel):
221
221
  field = cls._meta.get_field(field_name)
222
222
  assert hasattr(field, "default")
223
223
  if field.default is NOT_PROVIDED: # pragma: no cover
224
- raise ValueError(
225
- _("Must provide a default value for {model}.{field}.").format(
224
+ raise IntegrityError(
225
+ gettext("Must provide a default value for {model}.{field}.").format(
226
226
  model=cls.__name__,
227
227
  field=field_name,
228
228
  )
@@ -242,8 +242,6 @@ class CTCTModel(SerialModel):
242
242
 
243
243
 
244
244
  class CTCTEndpointModel(EndpointMixin, CTCTModel):
245
- # Must explicitly specify both
246
- objects: ClassVar[models.Manager[Self]] = models.Manager()
247
245
  remote: ClassVar[RemoteManager[Self]] = RemoteManager()
248
246
 
249
247
  class Meta:
@@ -273,7 +271,6 @@ class ContactList(CreatedAtMixin, UpdatedAtMixin, CTCTEndpointModel):
273
271
  }
274
272
 
275
273
  # Must explicitly specify both
276
- objects: ClassVar[models.Manager[Self]] = models.Manager()
277
274
  remote: ClassVar[ContactListRemoteManager] = ContactListRemoteManager()
278
275
 
279
276
  # API editable fields
@@ -474,7 +471,6 @@ class Contact(CreatedAtMixin, UpdatedAtMixin, CTCTEndpointModel):
474
471
  }
475
472
 
476
473
  # Must explicitly specify both
477
- objects: ClassVar[models.Manager[Self]] = models.Manager()
478
474
  remote: ClassVar[ContactRemoteManager] = ContactRemoteManager()
479
475
 
480
476
  SALUTATIONS = (
@@ -544,7 +540,7 @@ class Contact(CreatedAtMixin, UpdatedAtMixin, CTCTEndpointModel):
544
540
  default="implicit",
545
541
  verbose_name=_("Permission to Send"),
546
542
  help_text=_(
547
- "Identifies the type of permission that the Constant Contact account has to send email to the contact" # noqa: E501
543
+ "Identifies the permission that the ConstantContact account has to send email"
548
544
  ),
549
545
  )
550
546
  create_source = models.CharField(
@@ -582,14 +578,6 @@ class Contact(CreatedAtMixin, UpdatedAtMixin, CTCTEndpointModel):
582
578
  verbose_name=_("Opt Out Reason"),
583
579
  )
584
580
 
585
- @property
586
- def ctct_source(self) -> dict[str, str]:
587
- if self.api_id:
588
- source = {"update_source": self.update_source}
589
- else:
590
- source = {"create_source": self.create_source}
591
- return source
592
-
593
581
  class Meta:
594
582
  verbose_name = _("Contact")
595
583
  verbose_name_plural = _("Contacts")
@@ -604,6 +592,14 @@ class Contact(CreatedAtMixin, UpdatedAtMixin, CTCTEndpointModel):
604
592
  validate_email(self.email)
605
593
  return super().clean()
606
594
 
595
+ @property
596
+ def ctct_source(self) -> dict[str, str]:
597
+ if self.api_id:
598
+ source = {"update_source": self.update_source}
599
+ else:
600
+ source = {"create_source": self.create_source}
601
+ return source
602
+
607
603
  @classmethod
608
604
  def clean_remote_email(cls, data: JsonDict) -> str:
609
605
  assert isinstance(data["email_address"], dict)
@@ -902,7 +898,6 @@ class EmailCampaign(CreatedAtMixin, UpdatedAtMixin, CTCTEndpointModel):
902
898
  }
903
899
 
904
900
  # Must explicitly specify both
905
- objects: ClassVar[models.Manager[Self]] = models.Manager()
906
901
  remote: ClassVar[EmailCampaignRemoteManager] = EmailCampaignRemoteManager()
907
902
 
908
903
  STATUSES = (
@@ -1025,7 +1020,6 @@ class CampaignActivity(CTCTEndpointModel):
1025
1020
  }
1026
1021
 
1027
1022
  # Must explicitly specify both
1028
- objects: ClassVar[models.Manager[Self]] = models.Manager()
1029
1023
  remote: ClassVar[CampaignActivityRemoteManager] = CampaignActivityRemoteManager()
1030
1024
 
1031
1025
  ROLES = (
@@ -1115,19 +1109,6 @@ class CampaignActivity(CTCTEndpointModel):
1115
1109
  verbose_name=_("Format Type"),
1116
1110
  )
1117
1111
 
1118
- @property
1119
- def physical_address_in_footer(self) -> dict[str, str] | None:
1120
- """Returns the company address for email footers.
1121
-
1122
- Notes
1123
- -----
1124
- If you do not include a physical address in the email campaign activity,
1125
- Constant Contact will use the physical address information saved for the
1126
- Constant Contact user account.
1127
-
1128
- """
1129
- return get_setting("CTCT_PHYSICAL_ADDRESS")
1130
-
1131
1112
  class Meta:
1132
1113
  verbose_name = _("Email Campaign Activity")
1133
1114
  verbose_name_plural = _("Email Campaign Activities")
@@ -1146,6 +1127,10 @@ class CampaignActivity(CTCTEndpointModel):
1146
1127
  s = super().__str__()
1147
1128
  return s
1148
1129
 
1130
+ def save(self, *args: Any, **kwargs: Any) -> None:
1131
+ self.html_content = self.clean_html_content(self.html_content)
1132
+ super().save(*args, **kwargs)
1133
+
1149
1134
  def serialize(self, data: JsonDict) -> JsonDict:
1150
1135
  if "contact_lists" in data:
1151
1136
  # Be careful to include data['contact_lists'] even if it's empty
@@ -1185,9 +1170,18 @@ class CampaignActivity(CTCTEndpointModel):
1185
1170
  html_content = self.TRACKING_IMAGE + "\n" + html_content
1186
1171
  return html_content
1187
1172
 
1188
- def save(self, *args: Any, **kwargs: Any) -> None:
1189
- self.html_content = self.clean_html_content(self.html_content)
1190
- super().save(*args, **kwargs)
1173
+ @property
1174
+ def physical_address_in_footer(self) -> dict[str, str] | None:
1175
+ """Returns the company address for email footers.
1176
+
1177
+ Notes
1178
+ -----
1179
+ If you do not include a physical address in the email campaign activity,
1180
+ Constant Contact will use the physical address information saved for the
1181
+ Constant Contact user account.
1182
+
1183
+ """
1184
+ return get_setting("CTCT_PHYSICAL_ADDRESS")
1191
1185
 
1192
1186
 
1193
1187
  class CampaignSummary(CTCTEndpointModel):
@@ -1209,7 +1203,6 @@ class CampaignSummary(CTCTEndpointModel):
1209
1203
  )
1210
1204
 
1211
1205
  # Must explicitly specify both
1212
- objects: ClassVar[models.Manager[Self]] = models.Manager()
1213
1206
  remote: ClassVar[CampaignSummaryRemoteManager] = CampaignSummaryRemoteManager()
1214
1207
 
1215
1208
  campaign = models.OneToOneField(
@@ -1275,6 +1268,19 @@ class CampaignSummary(CTCTEndpointModel):
1275
1268
 
1276
1269
  ordering = ("-campaign",)
1277
1270
 
1271
+ def __str__(self) -> str:
1272
+ try:
1273
+ s = f"{self.campaign} Summary"
1274
+ except EmailCampaign.DoesNotExist:
1275
+ s = super().__str__()
1276
+ return s
1277
+
1278
+ def save(self, *args: Any, **kwargs: Any) -> None:
1279
+ """Must set api_id manually."""
1280
+ if (self.api_id is None) and (self.campaign_id is not None):
1281
+ self.api_id = self.campaign.api_id
1282
+ super().save(*args, **kwargs)
1283
+
1278
1284
  @classmethod
1279
1285
  def clean_remote_counts(cls, field_name: str, data: JsonDict) -> int:
1280
1286
  counts = data.get("unique_counts", {})
@@ -1315,12 +1321,6 @@ class CampaignSummary(CTCTEndpointModel):
1315
1321
  def clean_remote_not_opened(cls, data: JsonDict) -> int:
1316
1322
  return cls.clean_remote_counts("not_opened", data)
1317
1323
 
1318
- def save(self, *args: Any, **kwargs: Any) -> None:
1319
- """Must set api_id manually."""
1320
- if (self.api_id is None) and (self.campaign_id is not None):
1321
- self.api_id = self.campaign.api_id
1322
- super().save(*args, **kwargs)
1323
-
1324
1324
 
1325
1325
  def is_ctct(
1326
1326
  val: type[BaseModel] | Literal["self"] | None,
@@ -1,8 +1,9 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import copy
3
4
  import datetime as dt
4
5
  from collections.abc import Iterable
5
- from typing import TYPE_CHECKING, Literal, NoReturn, cast
6
+ from typing import TYPE_CHECKING, Literal, NoReturn
6
7
  from urllib.parse import urlencode
7
8
  from uuid import UUID
8
9
 
@@ -10,23 +11,21 @@ import requests
10
11
  from django.conf import settings
11
12
  from django.core.exceptions import ImproperlyConfigured
12
13
  from django.db import models
13
- from django.db.models.manager import Manager
14
14
  from django.db.models.query import QuerySet
15
15
  from django.http import Http404, HttpRequest
16
- from django.urls import reverse
17
16
  from django.utils.crypto import get_random_string
18
17
  from django.utils.module_loading import import_string
19
- from django.utils.translation import gettext_lazy as _
20
- from jwt import ExpiredSignatureError
18
+ from django.utils.translation import gettext as _
21
19
  from ratelimit import limits, sleep_and_retry
22
20
  from requests.exceptions import HTTPError
23
21
  from requests.models import Response
24
22
 
25
23
  from django_ctct.conf import get_setting
24
+ from django_ctct.exceptions import LocalObjectDoesNotExist, RemoteObjectDoesNotExist
26
25
  from django_ctct.utils import get_related_fields
27
26
 
28
27
  if TYPE_CHECKING: # pragma: no cover
29
- from typing import Any, ClassVar
28
+ from typing import Any, ClassVar, Self
30
29
 
31
30
  from django_ctct.models import (
32
31
  CampaignActivity,
@@ -43,7 +42,32 @@ if TYPE_CHECKING: # pragma: no cover
43
42
  )
44
43
 
45
44
 
46
- class ConnectionManagerMixin[T: EndpointMixin](Manager[T]):
45
+ class RemoteBase[M: models.Model]:
46
+ """Descriptor base providing `.model`, in place of `Manager`.
47
+
48
+ `__get__` rebinds `.model` to the accessing class, mirroring Django's
49
+ abstract-manager inheritance so a descriptor declared on an abstract
50
+ base resolves per concrete model.
51
+ """
52
+
53
+ model: type[M]
54
+ _name: str
55
+
56
+ def contribute_to_class(self, cls: type[M], name: str) -> None:
57
+ self._name = name
58
+ self.model = cls
59
+ setattr(cls, name, self)
60
+
61
+ def __get__(self, instance: object, owner: type[M]) -> Self:
62
+ if getattr(self, "model", None) is owner:
63
+ return self
64
+ bound = copy.copy(self)
65
+ bound.model = owner
66
+ setattr(owner, self._name, bound)
67
+ return bound
68
+
69
+
70
+ class ConnectionManagerMixin[T: EndpointMixin](RemoteBase[T]):
47
71
  """Manager mixin for utilizing an API."""
48
72
 
49
73
  API_LIMIT_CALLS: int = 4 # four calls
@@ -145,40 +169,7 @@ class ConnectionManagerMixin[T: EndpointMixin](Manager[T]):
145
169
  return data
146
170
 
147
171
 
148
- class TokenManager(Manager["Token"]):
149
- """Local manager for Token with in-memory caching and automatic refresh."""
150
-
151
- _cached_token: Token | None = None
152
-
153
- def get_valid(self, force_refresh: bool = False) -> Token:
154
- """Fetches active Token, refreshing remotely if expired or on 401."""
155
- if not force_refresh and self._cached_token is not None:
156
- if not self._cached_token.is_expired:
157
- return self._cached_token
158
-
159
- token = self.first()
160
- if not token:
161
- self._cached_token = None
162
- raise ValueError(
163
- _(
164
- "No tokens in the database yet. "
165
- f"Go to {reverse('ctct:auth')} and sign into ConstantContact."
166
- )
167
- )
168
-
169
- if force_refresh or token.is_expired:
170
- token = self.model.remote.refresh(token)
171
- else:
172
- try:
173
- token.decode()
174
- except ExpiredSignatureError:
175
- token = self.model.remote.refresh(token)
176
-
177
- self._cached_token = token
178
- return token
179
-
180
-
181
- class TokenRemoteManager(ConnectionManagerMixin["Token"], Manager["Token"]):
172
+ class TokenRemoteManager(ConnectionManagerMixin["Token"]):
182
173
  """Manager for utilizing CTCT's Auth Token API."""
183
174
 
184
175
  OAUTH_STATE_SESSION_KEY: ClassVar[str] = "ctct_oauth_state"
@@ -211,7 +202,7 @@ class TokenRemoteManager(ConnectionManagerMixin["Token"], Manager["Token"]):
211
202
  self.session = requests.Session()
212
203
  self.session.auth = (settings.CTCT_PUBLIC_KEY, settings.CTCT_SECRET_KEY)
213
204
 
214
- def create(self, auth_code: str) -> Token: # type: ignore[override]
205
+ def create(self, auth_code: str) -> Token:
215
206
  """Creates the initial Token using an `auth_code` from CTCT.
216
207
 
217
208
  Notes
@@ -254,7 +245,7 @@ class TokenRemoteManager(ConnectionManagerMixin["Token"], Manager["Token"]):
254
245
  return new_token
255
246
 
256
247
 
257
- class Serializer[S: SerialModel](Manager[S]):
248
+ class Serializer[S: SerialModel](RemoteBase[S]):
258
249
  TS_FORMAT: ClassVar[str] = "%Y-%m-%dT%H:%M:%SZ"
259
250
 
260
251
  def serialize(
@@ -388,7 +379,7 @@ class Serializer[S: SerialModel](Manager[S]):
388
379
  RelatedModel = m2m_field.related_model
389
380
 
390
381
  if is_model(ThroughModel) and is_model(RelatedModel):
391
- related_obj_pks = RelatedModel.objects.filter( # type: ignore
382
+ related_obj_pks = RelatedModel._default_manager.filter(
392
383
  api_id__in=data.pop(m2m_field.name)
393
384
  ).values_list("pk", flat=True)
394
385
 
@@ -441,7 +432,7 @@ class Serializer[S: SerialModel](Manager[S]):
441
432
  if k.endswith("_id") and isinstance(v, str):
442
433
  RelatedModel = self.model._meta.get_field(k).related_model
443
434
  if RelatedModel is not None:
444
- data[k] = RelatedModel.objects.get(api_id=v).pk # type: ignore
435
+ data[k] = RelatedModel._default_manager.get(api_id=v).pk
445
436
 
446
437
  if pk:
447
438
  # Preserve unrelated db fields (e.g. EmailCampaign.send_preview)
@@ -458,11 +449,10 @@ class Serializer[S: SerialModel](Manager[S]):
458
449
  class RemoteManager[E: CTCTEndpointModel](
459
450
  ConnectionManagerMixin[E],
460
451
  Serializer[E],
461
- Manager[E],
462
452
  ):
463
453
  """Manager for utilizing the CTCT API."""
464
454
 
465
- def create(self, obj: E) -> E: # type: ignore[override]
455
+ def create(self, obj: E) -> E:
466
456
  """Creates an existing Django object on the remote server.
467
457
 
468
458
  Notes
@@ -473,7 +463,7 @@ class RemoteManager[E: CTCTEndpointModel](
473
463
  """
474
464
 
475
465
  if not obj.pk:
476
- raise ValueError("Must create object locally first.")
466
+ raise LocalObjectDoesNotExist
477
467
 
478
468
  response = self.request(
479
469
  "post",
@@ -491,7 +481,7 @@ class RemoteManager[E: CTCTEndpointModel](
491
481
 
492
482
  return obj
493
483
 
494
- def get( # type: ignore[override]
484
+ def get(
495
485
  self,
496
486
  api_id: str | UUID,
497
487
  ) -> tuple[E, list[RelatedObjects]]:
@@ -513,12 +503,16 @@ class RemoteManager[E: CTCTEndpointModel](
513
503
  try:
514
504
  data = self.raise_or_json(response)
515
505
  except Http404:
516
- raise self.model.DoesNotExist(api_id)
506
+ raise RemoteObjectDoesNotExist(
507
+ message=_("ConstantContact API returning 404 for {api_id}").format(
508
+ api_id=api_id
509
+ )
510
+ )
517
511
 
518
512
  obj, list_of_related_objs = self.deserialize(data)
519
513
  return obj, list_of_related_objs
520
514
 
521
- def all( # type: ignore[override]
515
+ def all(
522
516
  self,
523
517
  endpoint: str | None = None,
524
518
  ) -> list[tuple[E, list[RelatedObjects]]]:
@@ -553,7 +547,7 @@ class RemoteManager[E: CTCTEndpointModel](
553
547
 
554
548
  return list_of_tuples
555
549
 
556
- def update(self, obj: E) -> E: # type: ignore[override]
550
+ def update(self, obj: E) -> E:
557
551
  """Updates an existing Django object on the remote server.
558
552
 
559
553
  Notes
@@ -564,9 +558,9 @@ class RemoteManager[E: CTCTEndpointModel](
564
558
  """
565
559
 
566
560
  if obj.pk is None:
567
- raise ValueError("Must create object locally first.")
561
+ raise LocalObjectDoesNotExist
568
562
  elif obj.api_id is None:
569
- raise ValueError("Must create object remotely first.")
563
+ raise RemoteObjectDoesNotExist
570
564
 
571
565
  response = self.request(
572
566
  "put",
@@ -682,7 +676,7 @@ class ContactListRemoteManager(RemoteManager["ContactList"]):
682
676
  class ContactRemoteManager(RemoteManager["Contact"]):
683
677
  """Extend RemoteManager to handle Contacts."""
684
678
 
685
- def create(self, obj: Contact) -> Contact: # type: ignore[override]
679
+ def create(self, obj: Contact) -> Contact:
686
680
  try:
687
681
  obj = super().create(obj)
688
682
  except HTTPError as e:
@@ -693,7 +687,7 @@ class ContactRemoteManager(RemoteManager["Contact"]):
693
687
  raise e
694
688
  return obj
695
689
 
696
- def update_or_create(self, obj: Contact) -> Contact: # type: ignore[override]
690
+ def update_or_create(self, obj: Contact) -> Contact:
697
691
  """Updates or creates the Contact based on `email`.
698
692
 
699
693
  Notes
@@ -717,7 +711,7 @@ class ContactRemoteManager(RemoteManager["Contact"]):
717
711
  """
718
712
 
719
713
  if obj.pk is None:
720
- raise ValueError("Must create object locally first.")
714
+ raise LocalObjectDoesNotExist
721
715
 
722
716
  # This endpoint expects a slightly different serialization
723
717
  data = self.serialize(obj)
@@ -731,9 +725,11 @@ class ContactRemoteManager(RemoteManager["Contact"]):
731
725
  data = self.raise_or_json(response)
732
726
 
733
727
  # CTCT doesn't return a full object at this endpoint
734
- _, api_id = data.pop("action"), data.pop("contact_id")
728
+ __, api_id = data.pop("action"), data.pop("contact_id")
735
729
  if data:
736
- raise ValueError(f"Unexpected response data: {data}.")
730
+ raise NotImplementedError(
731
+ _("Unexpected response data: {data}.").format(data=data)
732
+ )
737
733
 
738
734
  # Save the API id
739
735
  obj.api_id = api_id
@@ -757,7 +753,7 @@ class EmailCampaignRemoteManager(RemoteManager["EmailCampaign"]):
757
753
  data = super().serialize(obj, field_types)
758
754
  return data
759
755
 
760
- def create(self, obj: EmailCampaign) -> EmailCampaign: # type: ignore[override]
756
+ def create(self, obj: EmailCampaign) -> EmailCampaign:
761
757
  """Creates a local EmailCampaign on the remote servers.
762
758
 
763
759
  Notes
@@ -772,7 +768,7 @@ class EmailCampaignRemoteManager(RemoteManager["EmailCampaign"]):
772
768
 
773
769
  # Validate
774
770
  if obj.pk is None:
775
- raise ValueError("Must create object locally first.")
771
+ raise LocalObjectDoesNotExist
776
772
  try:
777
773
  activity = obj.campaign_activities.get(role="primary_email")
778
774
  except CampaignActivity.DoesNotExist:
@@ -802,12 +798,11 @@ class EmailCampaignRemoteManager(RemoteManager["EmailCampaign"]):
802
798
  # Set CTCT's assigned api_id on our local CampaignActivity instance
803
799
  for model, related_objs in list_of_related_objs:
804
800
  if model is CampaignActivity:
805
- # NOTE: All lists are invariant, so mypy doesn't know that
806
- # `related_objs` is a list[CampaignActivity].
807
- for related_obj in cast(list[CampaignActivity], related_objs):
808
- if related_obj.role == "primary_email":
809
- activity.api_id = related_obj.api_id
810
- break
801
+ for related_obj in related_objs:
802
+ if isinstance(related_obj, CampaignActivity):
803
+ if related_obj.role == "primary_email":
804
+ activity.api_id = related_obj.api_id
805
+ break
811
806
 
812
807
  # Overwrite local obj with CTCT's response
813
808
  obj.save()
@@ -823,7 +818,7 @@ class EmailCampaignRemoteManager(RemoteManager["EmailCampaign"]):
823
818
 
824
819
  return obj
825
820
 
826
- def update(self, obj: EmailCampaign) -> EmailCampaign: # type: ignore[override]
821
+ def update(self, obj: EmailCampaign) -> EmailCampaign:
827
822
  """Update EmailCampaign on remote servers.
828
823
 
829
824
  Notes
@@ -834,9 +829,9 @@ class EmailCampaignRemoteManager(RemoteManager["EmailCampaign"]):
834
829
 
835
830
  """
836
831
  if obj.pk is None:
837
- raise ValueError("Must create object locally first.")
832
+ raise LocalObjectDoesNotExist
838
833
  elif obj.api_id is None:
839
- raise ValueError("Must create object remotely first.")
834
+ raise RemoteObjectDoesNotExist
840
835
 
841
836
  response = self.request(
842
837
  "patch",
@@ -858,7 +853,7 @@ class EmailCampaignRemoteManager(RemoteManager["EmailCampaign"]):
858
853
  class CampaignActivityRemoteManager(RemoteManager["CampaignActivity"]):
859
854
  """Extend RemoteManager to handle scheduling."""
860
855
 
861
- def create(self, obj: CampaignActivity) -> NoReturn: # type: ignore[override]
856
+ def create(self, obj: CampaignActivity) -> NoReturn:
862
857
  raise NotImplementedError(
863
858
  _(
864
859
  "ConstantContact API does not support creating CampaignActivities. "
@@ -866,7 +861,7 @@ class CampaignActivityRemoteManager(RemoteManager["CampaignActivity"]):
866
861
  )
867
862
  )
868
863
 
869
- def update(self, obj: CampaignActivity) -> CampaignActivity: # type: ignore[override]
864
+ def update(self, obj: CampaignActivity) -> CampaignActivity:
870
865
  """Update CampaignActivity on remote servers.
871
866
 
872
867
  Notes
@@ -0,0 +1,26 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ if TYPE_CHECKING:
6
+ from typing import Any
7
+
8
+ from django.db.models import Model
9
+
10
+ from django_ctct.models import EmailCampaign
11
+
12
+
13
+ def sync_campaign_for_host(
14
+ host_obj: Model,
15
+ cleaned_data: dict[str, Any],
16
+ campaign_field_name: str,
17
+ ) -> EmailCampaign | None:
18
+ """
19
+ 1. Creates or updates the local EmailCampaign instance linked to host_obj.
20
+ 2. Creates or updates the primary_email CampaignActivity instance.
21
+ 3. Pushes creation/updates to Constant Contact API via
22
+ EmailCampaign.remote.create()/update() and
23
+ CampaignActivity.remote.update().
24
+ 4. Saves the foreign key relation on host_obj if not already set.
25
+ """
26
+ return None
@@ -0,0 +1,11 @@
1
+ {% extends "admin/change_form.html" %}
2
+
3
+ {% block content %}
4
+ <h1>Compose Campaign</h1>
5
+ <form method="post" action="">
6
+ {% csrf_token %}
7
+ {{ form.as_p }}
8
+ <button type="submit" class="default">Send Campaign</button>
9
+ </form>{% endblock content %}
10
+
11
+ {% block object-tools %}{{ block.super }}{% endblock object-tools %}
@@ -68,6 +68,11 @@ A mixin for the host model's `ModelAdmin` providing customization hooks, routing
68
68
  - `def get_campaign_html_content(self, request: HttpRequest, obj: Model) -> str`: Rendered HTML content (e.g. from a template).
69
69
  - `def get_campaign_contact_lists(self, request: HttpRequest, obj: Model) -> QuerySet[ContactList]`: Default selected contact lists.
70
70
  - **Custom Admin URL & View:**
71
+ - **Not** a `ModelAdmin.actions` bulk action (those operate on a queryset selected via
72
+ changelist checkboxes, dispatched through `response_action()`). This is a
73
+ **single-object custom admin view**, registered by overriding `get_urls()` on the
74
+ host `ModelAdmin` — the same pattern Django's own built-in admin uses for
75
+ `auth.User`'s `<id>/password/` change-password view.
71
76
  - Custom endpoint: `<path:object_id>/compose-campaign/`
72
77
  - `compose_campaign_view(self, request: HttpRequest, object_id: str) -> HttpResponse`:
73
78
  - On `GET`: Pre-populates form with hook defaults (or existing campaign data if one is already attached) and renders template.
@@ -75,6 +80,34 @@ A mixin for the host model's `ModelAdmin` providing customization hooks, routing
75
80
  - **Admin UI Integration:**
76
81
  - Add "Create/Edit Email Campaign" button in object tools or change form template (`change_form_template`).
77
82
 
83
+ ### 5. Drift Detection (`django_ctct.admin.CampaignHostAdminMixin`)
84
+ Once a host object has an attached `EmailCampaign`, the mixin should proactively surface
85
+ (but never silently push) changes made to the host object after the last sync:
86
+
87
+ - **Hook:** `def get_host_modified_at(self, obj: Model) -> dt.datetime`: Defaults to
88
+ `obj.updated_at` (documented as a mixin requirement); override if the host model uses
89
+ a different field name.
90
+ - **Detection:** No new fields or content-hashing required. `EmailCampaign.updated_at`
91
+ (via `UpdatedAtMixin`) is already set from CTCT's own `updated_at` on every successful
92
+ remote sync, so it doubles as a "last synced at" timestamp. Drift is simply:
93
+ ```python
94
+ get_host_modified_at(obj) > obj.campaign.updated_at
95
+ ```
96
+ - **Where it runs:** Inside `save_model()` (or `response_change()`) on the host
97
+ `ModelAdmin`, called explicitly at the end of the normal admin save flow — the same
98
+ place `EmailCampaignAdmin.save_remotely` already lives. This is a plain, traceable
99
+ method call, not a signal.
100
+ - **Surfacing:** If `obj.campaign` is set, `obj.campaign.current_status != "DONE"`, and
101
+ drift is detected:
102
+ - Add a `messages.WARNING` (via `format_html` + `reverse`, matching the existing
103
+ `ctct_message_user` pattern) linking directly to the compose view, e.g. *"This post
104
+ has changed since its campaign was last synced. [Review & update campaign →]"*.
105
+ - Render the same warning as a persistent banner in the host's `change_form_template`
106
+ so it remains visible on return visits, not just as a one-time flash message.
107
+ - **No automatic sync:** Nothing is pushed to CTCT until the user explicitly clicks
108
+ through to the compose view and resubmits the form — consistent with constraint #2
109
+ below. This gives "stays in sync by default" visibility without hidden automation.
110
+
78
111
  ---
79
112
 
80
113
  ## User Constraints & Design Decisions
@@ -1,15 +1,15 @@
1
1
  [project]
2
2
  name = "django-ctct"
3
- version = "0.0.1.dev7"
3
+ version = "0.0.1.dev8"
4
4
  description = "A Django interface for the Constant Contact API"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
7
7
  dependencies = [
8
- "django (>=6.0)",
9
- "requests (>=2.32.3,<3.0.0)",
10
- "ratelimit (>=2.2.1,<3.0.0)",
11
- "tqdm (>=4.67.1,<5.0.0)",
12
- "pyjwt[crypto] (>=2.10.1,<3.0.0)",
8
+ "django>=6.0",
9
+ "requests>=2.32.3,<3.0.0",
10
+ "ratelimit>=2.2.1,<3.0.0",
11
+ "tqdm>=4.67.1,<5.0.0",
12
+ "pyjwt[crypto]>=2.10.1,<3.0.0",
13
13
  ]
14
14
 
15
15
  [[project.authors]]
@@ -46,6 +46,7 @@ select = [
46
46
  "I",
47
47
  "UP",
48
48
  "RUF100",
49
+ "DJ",
49
50
  ]
50
51
  ignore = [
51
52
  "E111",
@@ -59,6 +60,11 @@ indent-style = "space"
59
60
 
60
61
  [tool.pytest.ini_options]
61
62
  DJANGO_SETTINGS_MODULE = "project.settings"
63
+ pythonpath = [
64
+ ".",
65
+ "tests/project",
66
+ ]
67
+ testpaths = ["tests"]
62
68
 
63
69
  [tool.coverage.run]
64
70
  branch = true
@@ -96,12 +102,12 @@ dev = [
96
102
  "factory-boy>=3.3.3",
97
103
  "requests-mock>=1.12.1",
98
104
  "codecov>=2.1.13",
99
- "mypy>=1.15.0",
105
+ "mypy>=2.4.1",
100
106
  "django-stubs[compatible-mypy]>=6.1.0,<7.0.0",
101
107
  "types-requests>=2.32.0.20250306",
102
108
  "django-stubs-ext>=6.1.0",
103
109
  "pre-commit>=4.2.0",
104
110
  "types-ratelimit>=2.2.0.20250501",
105
111
  "types-factory-boy>=0.4.1",
106
- "ruff>=0.16.7",
112
+ "ruff>=0.17.6",
107
113
  ]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "django-ctct"
3
- version = "0.0.1.dev7"
3
+ version = "0.0.1.dev8"
4
4
  description = "A Django interface for the Constant Contact API"
5
5
  authors = [
6
6
  {name = "Geoffrey Eisenbarth",email = "geoffrey.eisenbarth@gmail.com"}
@@ -9,11 +9,11 @@ license = {text = "MIT"}
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.12"
11
11
  dependencies = [
12
- "django (>=6.0)",
13
- "requests (>=2.32.3,<3.0.0)",
14
- "ratelimit (>=2.2.1,<3.0.0)",
15
- "tqdm (>=4.67.1,<5.0.0)",
16
- "pyjwt[crypto] (>=2.10.1,<3.0.0)",
12
+ "django>=6.0",
13
+ "requests>=2.32.3,<3.0.0",
14
+ "ratelimit>=2.2.1,<3.0.0",
15
+ "tqdm>=4.67.1,<5.0.0",
16
+ "pyjwt[crypto]>=2.10.1,<3.0.0",
17
17
  ]
18
18
 
19
19
 
@@ -34,14 +34,14 @@ dev = [
34
34
  "factory-boy>=3.3.3",
35
35
  "requests-mock>=1.12.1",
36
36
  "codecov>=2.1.13",
37
- "mypy>=1.15.0",
37
+ "mypy>=2.4.1",
38
38
  "django-stubs[compatible-mypy]>=6.1.0,<7.0.0",
39
39
  "types-requests>=2.32.0.20250306",
40
40
  "django-stubs-ext>=6.1.0",
41
41
  "pre-commit>=4.2.0",
42
42
  "types-ratelimit>=2.2.0.20250501",
43
43
  "types-factory-boy>=0.4.1",
44
- "ruff>=0.16.7",
44
+ "ruff>=0.17.6",
45
45
  ]
46
46
 
47
47
  [tool.ruff]
@@ -64,6 +64,7 @@ select = [
64
64
  "I", # isort (automatically sorts and organizes imports)
65
65
  "UP", # pyupgrade (modernizes Python syntax)
66
66
  "RUF100", # flags unused noqa comments
67
+ "DJ", # flake8-django
67
68
  ]
68
69
  ignore = [
69
70
  "E111", # Indentation is not a multiple of four
@@ -77,6 +78,8 @@ indent-style = "space"
77
78
 
78
79
  [tool.pytest.ini_options]
79
80
  DJANGO_SETTINGS_MODULE = "project.settings"
81
+ pythonpath = [".", "tests/project"]
82
+ testpaths = ["tests"]
80
83
 
81
84
  [tool.coverage.run]
82
85
  branch = true