Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
wbcrm / crm / tasks.py
Size: Mime:
from __future__ import absolute_import, unicode_literals

import logging
from datetime import datetime, timedelta

from celery import shared_task

from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.db.models import Q
from django.template.loader import get_template
from django.utils import timezone
from django.utils.html import strip_tags
from rest_framework.reverse import reverse

from wbutils.strings import enumerated_string_join 
from crm.models.activities import Activity
from crm.models.entries import Person
from notifications.models import Notification, NotificationType

logger = logging.getLogger()


@shared_task
def notify(time_offset=60):
    from notifications.models import Notification, NotificationType
    upcomming_activities = Activity.objects.filter(
        Q(status='planned') &
        Q(reminder__gte=timezone.now()) &
        Q(reminder__lte=timezone.now() + timedelta(seconds=60))
    )
    for activity in upcomming_activities:
        for participant in activity.participants.filter(status__title='Employee'):
            notifications = Notification.objects.filter(
                attachment__model__name='Activity',
                attachment__model__id=activity.id,
                recipient=participant
            )
            if not notifications.exists():
                attachment = {
                    'api-source': reverse('crm:activity-detail', args=[activity.id]),
                    'model': {
                        'name': 'Activity',
                        'id': activity.id,
                        'path': 'crm.Activity',
                        # NOTE: activity.type may be None
                        'type': activity.type.id if activity.type else None,
                        # NOTE: activity.type may be None
                        'type_repr': activity.type.title if activity.type else None
                    }
                }
                try:
                    Notification.objects.create(
                        type=NotificationType.REMINDER.value,
                        recipient=participant.get_casted_entry(),
                        attachment=attachment,
                        title=activity.title,
                        mailed_after=60,
                        message='You are participating in a {0.type}:<br /><br />{0.description}'.format(
                            activity)
                    )
                except Exception as e:
                    logger.info(e)


@shared_task
def daily_summery():
    for employee in Person.employees.all():
        upcomming_activities = Activity.objects.filter(start__date__lte=datetime.today(
        ), end__date__gte=datetime.today(), participants__in=[employee]).order_by('start')
        if upcomming_activities.exists() and employee.primary_email_contact():
            for activity in upcomming_activities:
                activity.other_participants = enumerated_string_join(list(
                    activity.participants.exclude(id=employee.id).values_list('search_name', flat=True)))
            context = {'person': employee, 'activities': upcomming_activities}
            template = get_template('crm/daily_summery.html')
            rendered_template = template.render(context)
            msg = EmailMultiAlternatives('Your schedule for today', strip_tags(
                rendered_template), settings.DEFAULT_FROM_EMAIL, [employee.primary_email_contact().address])
            msg.attach_alternative(rendered_template, 'text/html')
            msg.send()


@shared_task
def finish():
    finished_activities = Activity.objects.filter(
        Q(status='planned') &
        Q(end__lte=timezone.now())
    )
    for activity in finished_activities:
        activity.finish(
            by=None, description='Set to finished, because the End Datetime was reached.')
        activity.save()
        if activity.assigned_to and activity.assigned_to.is_employee:
            attachment = {
                'api-source': reverse('crm:activity-detail', args=[activity.id]),
                'model': {
                    'name': 'Activity',
                    'id': activity.id,
                    'path': 'crm.Activity',
                    'type': activity.type.id if activity.type else None,
                    'type_repr': activity.type.title if activity.type else None
                }
            }
            try:
                Notification.objects.create(
                    type=NotificationType.REMINDER.value,
                    recipient=activity.assigned_to.get_casted_entry(),
                    attachment=attachment,
                    title=activity.title,
                    message=f'{activity.title} just finished and you are in charge of this. You should review it!'
                )
            except Exception as e:
                    logger.info(e)