remotes/origin/feature/LIL-711
gzbender 7 years ago
parent 9a9ff6e013
commit b07e841419
  1. 22
      apps/notification/tasks.py
  2. 7
      project/sengrid.py
  3. 6
      project/settings.py
  4. 17
      project/utils/__init__.py
  5. 39
      project/utils/db.py

@ -11,6 +11,7 @@ from apps.notification.utils import send_email
from apps.payment.models import SchoolPayment, CoursePayment, Payment from apps.payment.models import SchoolPayment, CoursePayment, Payment
from project.celery import app from project.celery import app
from project.utils.db import format_sql, execute_sql from project.utils.db import format_sql, execute_sql
from project.sengrid import get_sendgrid_client
User = get_user_model() User = get_user_model()
@ -64,7 +65,8 @@ def send_certificates(email=None, date=None, dry_run=False):
@app.task @app.task
def sendgrid(): def sendgrid_update_recipients():
date_format = '%m/%d/%Y'
ct_course = ContentType.objects.get_for_model(CoursePayment).id ct_course = ContentType.objects.get_for_model(CoursePayment).id
ct_school = ContentType.objects.get_for_model(SchoolPayment).id ct_school = ContentType.objects.get_for_model(SchoolPayment).id
course_payments_sql = ''' course_payments_sql = '''
@ -79,13 +81,19 @@ def sendgrid():
users = list(User.objects.filter(role=User.USER_ROLE)) users = list(User.objects.filter(role=User.USER_ROLE))
data = [] data = []
for user in users: for user in users:
last_course_purchase = course_payments.get(user.id) and course_payments.get(user.id).strftime(date_format)
last_school_purchase = school_payments.get(user.id) and school_payments.get(user.id).strftime(date_format)
data.append({ data.append({
'first_name': user.first_name,
'last_name': user.last_name,
'name': user.get_full_name(), 'name': user.get_full_name(),
'email': user.email, 'email': user.email,
'last_login': user.last_login, 'last_login': user.last_login and user.last_login.strftime(date_format),
'last_course_purchase': course_payments.get(user.id), 'last_course_purchase': last_course_purchase,
'last_school_purchase': school_payments.get(user.id), 'last_school_purchase': last_school_purchase,
'gender': user.gender, 'gender': {User.NOT_DEFINED: '', User.MALE: 'Мужчина', User.FEMALE: 'Женщина'}[user.gender],
'birthday': user.birthday, 'birthday': user.birthday and user.birthday.strftime(date_format),
}) })
print(data)
sg = get_sendgrid_client()
response = sg.client.contactdb.recipients.patch(request_body=data)

@ -0,0 +1,7 @@
import sendgrid
from django.conf import settings
def get_sendgrid_client():
return sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY)

@ -191,6 +191,7 @@ ANYMAIL = {
EMAIL_BACKEND = 'anymail.backends.mailgun.EmailBackend' EMAIL_BACKEND = 'anymail.backends.mailgun.EmailBackend'
DEFAULT_FROM_EMAIL = os.getenv('DEFAULT_FROM_EMAIL', 'postmaster@mail.9ev.ru') DEFAULT_FROM_EMAIL = os.getenv('DEFAULT_FROM_EMAIL', 'postmaster@mail.9ev.ru')
SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')
# SMS # SMS
# https://github.com/twilio/twilio-python # https://github.com/twilio/twilio-python
@ -254,6 +255,11 @@ CELERY_BEAT_SCHEDULE = {
'schedule': crontab(hour=19), 'schedule': crontab(hour=19),
'args': (), 'args': (),
}, },
'sendgrid_update_recipients': {
'task': 'apps.notification.tasks.sendgrid_update_recipients',
'schedule': crontab(minute=0, hour=3),
'args': (),
},
} }
try: try:

@ -0,0 +1,17 @@
from datetime import datetime, timedelta
from collections import Counter
def date_range(start, end):
if isinstance(start, datetime):
start = start.date()
if isinstance(end, datetime):
end = end.date()
delta = end - start
for d in range(delta.days + 1):
yield start + timedelta(days=d)
return
def weekdays_in_date_range(start, end):
return Counter([d.isoweekday() for d in date_range(start, end)])

@ -0,0 +1,39 @@
from django.db.models.base import ModelBase
from django.db import connection
class ModelFieldsNames(object):
def __init__(self, model):
self.alias = None
self._meta = model._meta
def __getattr__(self, name):
alias = '__as__'
if name.startswith(alias):
self.alias = name[len(alias):]
return '%s as %s' % (self._meta.db_table, self.alias)
field = self._meta.get_field(name).get_attname_column()[1]
if self.alias:
return u"%s.%s" % (self.alias, field)
else:
return u"%s.%s" % (self._meta.db_table, field)
def __str__(self):
return '%s' % self._meta.db_table
def format_sql(sql, **kwargs):
for name, value in kwargs.items():
if issubclass(type(value), ModelBase):
kwargs[name] = ModelFieldsNames(value)
elif isinstance(value, (tuple, list)):
kwargs[name] = ','.join(map(lambda x: repr(x) if isinstance(x, str) else str(x), value))
elif not isinstance(value, str):
kwargs[name] = value
return sql.format(**kwargs)
def execute_sql(sql, args=()):
cursor = connection.cursor()
cursor.execute(sql, args)
return cursor.fetchall()
Loading…
Cancel
Save