welco/welco/contrib/alfortville/management/commands/send-avis-email.py

56 lines
2.2 KiB
Python

# welco - multichannel request processing
# Copyright (C) 2015-2016 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.core.mail import EmailMessage, send_mass_mail
from django.core.management.base import BaseCommand, CommandError
from django.template.loader import render_to_string
from hobo.agent.common.models import Role
from welco.contrib.alfortville.models import Inbox
from welco.sources.mail.models import Mail
class Command(BaseCommand):
def handle(self, *args, **kwargs):
ctx = {}
ctx.update(getattr(settings, 'TEMPLATE_VARS', {}))
subject = render_to_string(['alfortville/avis-email_subject.txt'], ctx).strip()
message = render_to_string(['alfortville/avis-email_body.txt'], ctx)
mails = []
relevant_mails = Mail.objects.filter(status='done-dga')
content_type = ContentType.objects.get_for_model(Mail)
User = get_user_model()
for user in User.objects.all():
user_roles = [x.uuid for x in Role.objects.filter(user=user)]
avis = Inbox.objects.filter(
role_slug__in=user_roles,
source_type=content_type,
source_pk__in=[x.id for x in relevant_mails],
subtype__in=[Inbox.MANDATORY_AVIS, Inbox.AVIS],
done=False)
if avis.count() == 0:
continue
mails.append((subject, message, settings.DEFAULT_FROM_EMAIL, [user.email]))
if mails:
send_mass_mail(mails)