Skip to content

Commit

Permalink
Merge pull request #247 from volunteers-for-city-projects/feature/inc…
Browse files Browse the repository at this point in the history
…omes_approve_send_email

Feature/incomes approve send email
  • Loading branch information
ArtemKAF authored Nov 27, 2023
2 parents d6c6adc + f19ffc8 commit 1362c7d
Show file tree
Hide file tree
Showing 5 changed files with 132 additions and 41 deletions.
90 changes: 49 additions & 41 deletions backend/api/serializers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import transaction
from django.utils import timezone
from djoser.serializers import UserCreateSerializer, UserSerializer
Expand All @@ -7,7 +8,7 @@
from rest_framework.validators import UniqueTogetherValidator
from taggit.models import Tag

from api.utils import NonEmptyBase64ImageField, create_user
from api.utils import NonEmptyBase64ImageField, create_user, get_site_data
from content.models import (
City,
Feedback,
Expand All @@ -16,6 +17,7 @@
Skills,
Valuation,
)
from notifications.tasks import incomes_approve_send_email
from projects.models import (
Address,
Category,
Expand All @@ -28,11 +30,12 @@
Volunteer,
VolunteerSkills,
)
from users.models import User

from .mixins import IsValidModifyErrorForFrontendMixin
from .validators import validate_dates, validate_status_incomes

User = get_user_model()


class AddressSerializer(serializers.ModelSerializer):
"""
Expand Down Expand Up @@ -641,44 +644,46 @@ class Meta:
# read_only_fields = ('id', 'created_at')
read_only_fields = ('id', 'created_at', 'volunteer')

# def create(self, validated_data):
# """
# Создает заявку волонтера.
# """
# project = validated_data['project']
# volunteer = validated_data['volunteer']
# status_incomes = validated_data.get(
# 'status_incomes', ProjectIncomes.APPLICATION_SUBMITTED
# )
# # if (
# # ProjectIncomes.objects.filter(project=project, volunteer=volunteer)
# # .exclude(status_incomes=ProjectIncomes.REJECTED)
# # .exists()
# # ):
# # проверить работу чере релейтед нейм
# if (
# project.project_incomes.filter(volunteer=volunteer)
# .exclude(status_incomes=ProjectIncomes.REJECTED).exists()
# ):
# raise serializers.ValidationError(
# 'Заявка волонтера на этот проект уже существует.'
# )
# if (project.project_incomes.filter(
# volunteer=volunteer, status_incomes=ProjectIncomes.REJECTED
# ).exists()
# ):
# raise serializers.ValidationError(
# 'Вы не можете повторно подать завку, ваша заявка ранее была отклонена'
# )
# project_income = ProjectIncomes.objects.create(
# project=project,
# volunteer=volunteer,
# status_incomes=status_incomes,
# phone=validated_data.get('phone', ''),
# telegram=validated_data.get('telegram', ''),
# cover_letter=validated_data.get('cover_letter', ''),
# )
# return project_income
# def create(self, validated_data):
# """
# Создает заявку волонтера.
# """
# project = validated_data['project']
# volunteer = validated_data['volunteer']
# status_incomes = validated_data.get(
# 'status_incomes', ProjectIncomes.APPLICATION_SUBMITTED
# )
# if (
# ProjectIncomes.objects.filter(
# project=project,
# volunteer=volunteer
# ).exclude(status_incomes=ProjectIncomes.REJECTED).exists()
# ):
# # TODO: проверить работу через релейтед нейм
# if (
# project.project_incomes.filter(volunteer=volunteer)
# .exclude(status_incomes=ProjectIncomes.REJECTED).exists()
# ):
# raise serializers.ValidationError(
# 'Заявка волонтера на этот проект уже существует.'
# )
# if (project.project_incomes.filter(
# volunteer=volunteer, status_incomes=ProjectIncomes.REJECTED
# ).exists()
# ):
# raise serializers.ValidationError(
# 'Вы не можете повторно подать завку, ваша заявка '
# 'ранее была отклонена'
# )
# project_income = ProjectIncomes.objects.create(
# project=project,
# volunteer=volunteer,
# status_incomes=status_incomes,
# phone=validated_data.get('phone', ''),
# telegram=validated_data.get('telegram', ''),
# cover_letter=validated_data.get('cover_letter', ''),
# )
# return project_income

def create(self, validated_data):
"""
Expand Down Expand Up @@ -753,9 +758,12 @@ def accept_incomes(self, instance):
)
instance.status_incomes = ProjectIncomes.ACCEPTED
instance.save()
ProjectParticipants.objects.create(
participiants = ProjectParticipants.objects.create(
project=instance.project, volunteer=instance.volunteer
)
incomes_approve_send_email.delay(
participiants.pk, get_site_data(self.context.get('request', {}))
)
return {
'message': 'Заявка волонтера принята и добавлена в '
'участники проекта.'
Expand Down
16 changes: 16 additions & 0 deletions backend/api/utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.contrib.sites.shortcuts import get_current_site
from django.http import Http404
from django.shortcuts import get_object_or_404
from djoser.compat import get_user_email
Expand Down Expand Up @@ -132,3 +133,18 @@ def get_instance(model, user, project, serializer_name):
{},
)
return instance


def get_site_data(request):
site_data = {}
if request:
site = get_current_site(request)
domain = (getattr(settings, 'DOMAIN', '') or site.domain)
protocol = ('https' if request.is_secure() else 'http')
site_name = (getattr(settings, 'SITE_NAME', '') or site.name)
site_data.update({
'domain': domain,
'protocol': protocol,
'site_name': site_name,
})
return site_data
18 changes: 18 additions & 0 deletions backend/notifications/email.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from templated_mail.mail import BaseEmailMessage


class IncomesApproveEmail(BaseEmailMessage):
template_name = 'email/incomes_approve.html'

def get_context_data(self):
context = super().get_context_data()

user = context.get('user')
project = context.get('project')
date_time = context.get('date_time')
context.update({
'user': user,
'project': project,
'date_time': date_time,
})
return context
23 changes: 23 additions & 0 deletions backend/notifications/tasks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from celery import shared_task
from django.contrib.auth import get_user_model
from django.utils import timezone
from djoser.compat import get_user_email

from .email import IncomesApproveEmail

User = get_user_model()


@shared_task
def incomes_approve_send_email(instance_pk, ctx):
from projects.models import ProjectParticipants # noqa
date_time = timezone.now()
instance = ProjectParticipants.objects.filter(
pk=instance_pk).select_related('volunteer__user', 'project').first()
ctx.update({
'user': instance.volunteer.user,
'project': instance.project,
'date_time': date_time,
})
to = [get_user_email(instance.volunteer.user)]
IncomesApproveEmail(context=ctx).send(to)
26 changes: 26 additions & 0 deletions backend/notifications/templates/email/incomes_approve.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{% load i18n %}

{% block subject %}
Заявка принята на {{ site_name }}
{% endblock subject %}

{% block text_body %}
Уважаемый {% if user.get_full_name %} {{ user.get_full_name }} {% else %} Волонтер {% endif %},
уведомляем, что ваша заявка на участие в проекте: {{ project.name }} одобрена
организатором.

{% trans "Thanks for using our site!" %}

{% blocktrans %}The {{ site_name }} team{% endblocktrans %}
{% endblock text_body %}

{% block html_body %}
<p>Уважаемый {% if user.get_full_name %} {{ user.get_full_name }} {% else %} Волонтер {% endif %},
уведомляем, что ваша заявка на участие в проекте: {{ project.name }} одобрена
организатором.

<p>{% trans "Thanks for using our site!" %}</p>

<p>{% blocktrans %}The {{ site_name }} team{% endblocktrans %}</p>

{% endblock html_body %}

0 comments on commit 1362c7d

Please sign in to comment.