diff --git a/api/v1/views.py b/api/v1/views.py index a7f04cc7..ab473137 100644 --- a/api/v1/views.py +++ b/api/v1/views.py @@ -686,7 +686,6 @@ class CaptureEmail(views.APIView): def post(self, request): list_id = None list_name = 'captured-emails' - recipient_id = None email = request.data.get('email') sg = get_sendgrid_client() @@ -709,7 +708,7 @@ class CaptureEmail(views.APIView): response = sg.client.contactdb.recipients.patch(request_body=[{ 'email': email, }]) - if response.status_code != 201: + if response.status_code != 201 or not response.to_dict.get('persisted_recipients'): return Response({'error': 'Cannot update recipients'}, status=status.HTTP_400_BAD_REQUEST) recipient_id = response.to_dict.get('persisted_recipients')[0] # добавляем получателя в отдельный список diff --git a/apps/user/management/commands/subscribers_to_sendgrid.py b/apps/user/management/commands/subscribers_to_sendgrid.py new file mode 100644 index 00000000..c089aeff --- /dev/null +++ b/apps/user/management/commands/subscribers_to_sendgrid.py @@ -0,0 +1,10 @@ +from django.core.management.base import BaseCommand + +from apps.user.tasks import subscribers_to_sendgrid + + +class Command(BaseCommand): + help = 'Send subscribers to sendgrid' + + def handle(self, *args, **options): + subscribers_to_sendgrid() diff --git a/apps/user/migrations/0028_auto_20181214_0107.py b/apps/user/migrations/0028_auto_20181214_0107.py new file mode 100644 index 00000000..f8300885 --- /dev/null +++ b/apps/user/migrations/0028_auto_20181214_0107.py @@ -0,0 +1,25 @@ +# Generated by Django 2.0.7 on 2018-12-14 01:07 + +from django.db import migrations, models +import django.utils.timezone + + +class Migration(migrations.Migration): + + dependencies = [ + ('user', '0027_user_gallery'), + ] + + operations = [ + migrations.AddField( + model_name='emailsubscription', + name='created_at', + field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), + preserve_default=False, + ), + migrations.AddField( + model_name='emailsubscription', + name='sendgrid_sent', + field=models.BooleanField(default=False), + ), + ] diff --git a/apps/user/models.py b/apps/user/models.py index adb40b55..9ab545e7 100644 --- a/apps/user/models.py +++ b/apps/user/models.py @@ -285,6 +285,8 @@ class EmailSubscription(models.Model): email = models.EmailField(_('email address'), unique=True) categories = models.ManyToManyField(SubscriptionCategory) mailchimp_status = models.PositiveSmallIntegerField(choices=MAILCHIMP_STATUS_CHOICES, default=ERROR) + created_at = models.DateTimeField(auto_now_add=True) + sendgrid_sent = models.BooleanField(default=False) class Referral(models.Model): diff --git a/apps/user/tasks.py b/apps/user/tasks.py index e35accef..e4d5741a 100644 --- a/apps/user/tasks.py +++ b/apps/user/tasks.py @@ -6,6 +6,7 @@ from django.conf import settings from django.contrib.auth import get_user_model from project.celery import app +from project.sengrid import get_sendgrid_client @app.task @@ -43,3 +44,47 @@ def users_to_roistat(): key = settings.ROISTAT_KEY url = settings.ROISTAT_API_URL + f'/project/clients/import?key={key}&project={project}' resp = requests.post(url, json=users) + + +@app.task +def subscribers_to_sendgrid(): + from apps.user.models import EmailSubscription + list_id = None + list_name = 'subscribed' + sg = get_sendgrid_client() + # берем все списки + response = sg.client.contactdb.lists.get() + if response.status_code != 200: + print('Cannot get list of lists') + return + # ищем нужный список + for sg_list in response.to_dict.get('lists'): + if sg_list.get('name') == list_name: + list_id = sg_list.get('id') + break + # не нашли - создаем + if not list_id: + response = sg.client.contactdb.lists.post(request_body={'name': list_name}) + if response.status_code != 201: + print('List was not created') + return + list_id = response.to_dict.get('id') + + for subscriber in EmailSubscription.objects.filter(sendgrid_sent=False): + print('Adding subscriber %s ...' % subscriber.email, end=' ') + # добавляем получателя + response = sg.client.contactdb.recipients.patch(request_body=[{ + 'email': subscriber.email, + }]) + if response.status_code != 201 or not response.to_dict.get('persisted_recipients'): + print('Cannot update recipients') + continue + recipient_id = response.to_dict.get('persisted_recipients')[0] + # добавляем получателя в отдельный список + response = sg.client.contactdb.lists._(list_id).recipients._(recipient_id).post() + if response.status_code != 201: + print('Cannot add recipient to list') + else: + print('OK') + subscriber.sendgrid_sent = True + subscriber.save()