Merge branch 'feature/LIL-694' into 'master'

Feature/lil 694

See merge request lilcity/backend!195
remotes/origin/feature/LIL-711
cfwme 7 years ago
commit e4a61c5beb
  1. 42
      apps/notification/tasks.py
  2. 7
      project/sengrid.py
  3. 6
      project/settings.py
  4. 0
      project/utils/__init__.py
  5. 39
      project/utils/db.py

@ -1,13 +1,17 @@
from datetime import datetime
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.contrib.staticfiles.storage import staticfiles_storage
from django.utils.timezone import now
from django.db.models import Max
from apps.notification.models import UserNotification
from apps.notification.utils import send_email
from apps.payment.models import SchoolPayment
from apps.payment.models import SchoolPayment, CoursePayment, Payment
from project.celery import app
from project.utils.db import format_sql, execute_sql
from project.sengrid import get_sendgrid_client
User = get_user_model()
@ -58,3 +62,39 @@ def send_certificates(email=None, date=None, dry_run=False):
file.close()
un.certificate_last_email = now()
un.save()
@app.task
def sendgrid_update_recipients():
date_format = '%m/%d/%Y'
ct_course = ContentType.objects.get_for_model(CoursePayment).id
ct_school = ContentType.objects.get_for_model(SchoolPayment).id
course_payments_sql = '''
select {p.user}, max({p.created_at}) from {p} where {p}.polymorphic_ctype_id = {ct} group by {p.user}
'''
course_payments = {p[0]: p[1] for p in execute_sql(format_sql(course_payments_sql, p=Payment, ct=ct_course))}
school_payments_sql = '''
select {p.user}, max({p.created_at}) from {p} where {p}.polymorphic_ctype_id = {ct} group by {p.user}
'''
school_payments = {p[0]: p[1] for p in execute_sql(format_sql(school_payments_sql, p=Payment, ct=ct_school))}
users = list(User.objects.filter(role=User.USER_ROLE))
data = []
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({
'first_name': user.first_name,
'last_name': user.last_name,
'email': user.email,
'last_login': user.last_login and user.last_login.strftime(date_format),
'last_course_purchase': last_course_purchase,
'last_school_purchase': last_school_purchase,
'gender': {User.NOT_DEFINED: '', User.MALE: 'Мужчина', User.FEMALE: 'Женщина'}[user.gender],
'birthday': user.birthday and user.birthday.strftime(date_format),
'date_joined': user.date_joined.strftime(date_format),
})
sg = get_sendgrid_client()
response = sg.client.contactdb.recipients.patch(request_body=data)
print(response.body)

@ -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'
DEFAULT_FROM_EMAIL = os.getenv('DEFAULT_FROM_EMAIL', 'postmaster@mail.9ev.ru')
SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')
# SMS
# https://github.com/twilio/twilio-python
@ -254,6 +255,11 @@ CELERY_BEAT_SCHEDULE = {
'schedule': crontab(hour=19),
'args': (),
},
'sendgrid_update_recipients': {
'task': 'apps.notification.tasks.sendgrid_update_recipients',
'schedule': crontab(minute=0, hour=3),
'args': (),
},
}
try:

@ -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