This repository has been archived on 2023-02-21. You can view files and clone it, but cannot push or open issues or pull requests.
synchro-orleans/synchro_orleans/data/management/commands/email_new_invoices.py

81 lines
3.4 KiB
Python

from datetime import datetime, timedelta
import json
import shutil
import os
import requests
import logging
from hashlib import sha256
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.utils.timezone import make_aware, get_current_timezone
from django.db.models import Q
from django.template.loader import get_template
from django.template import Context
from django.core.mail import EmailMultiAlternatives
from synchro_orleans.data.models import Facture, InvoiceNotificationEmail
from synchro_orleans import signature
notification_timeout = settings.INVOICES_NOTIFICATION_TIMEOUT
invoice_view_url_base = settings.INVOICE_VIEW_URL_BASE
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = """
Sends email notifications about the invoices
"""
email_subject = 'Nouvelle facture'
email_template = 'invoice_mail.txt'
email_from = settings.DEFAULT_FROM_EMAIL
def get_invoice_hash(self, *args):
hash = sha256(''.join(map(lambda s: str(s), args)))
return hash.hexdigest()[:8]
def handle(self, *args, **options):
for invoice in Facture.objects.filter(Q(paye=False) | Q(montant_regle=0),
active=True, date_limite_paie__gte=datetime.now(),
famille__liaisonnameidfamille__isnull=False):
try:
notification = InvoiceNotificationEmail.objects.filter(invoice_number=invoice.id).latest()
if notification.date_sent > make_aware(datetime.now(), get_current_timezone()) - timedelta(days=notification_timeout):
continue
except InvoiceNotificationEmail.DoesNotExist:
InvoiceNotificationEmail.objects.create(invoice_number=invoice.id)
nameid = invoice.famille.liaisonnameidfamille_set.all()[0]
signed_query = signature.sign_query('orig=synchro-orleans', settings.EMAILING_APIKEY)
url = '{url}/{nameid}?{query}'.format(url=settings.IDP_USER_INFO_URL,
nameid=nameid.name_id,
query=signed_query)
logger.debug('requesting: %s' % url)
response = requests.get(url)
data = response.json().get('data', None)
if not data:
continue
attachment = os.path.join(settings.INVOICES_DIR, 'facture_%s.pdf' % invoice.id)
invoice_hash = self.get_invoice_hash(invoice.id,
invoice.date_generation,
invoice.montant)
context = {'invoice': invoice, 'invoice_view_url_base': invoice_view_url_base,
'invoice_hash': invoice_hash}
context.update(data)
context = Context(context)
text_body = get_template(self.email_template).render(context)
message = EmailMultiAlternatives(self.email_subject, text_body, self.email_from, [data['email']])
message.attach_file(os.path.join(settings.INVOICES_DIR, 'facture_%s.pdf'% invoice.id))
message.send()
logger.debug('email for invoice nr. %s sent' % invoice.id)
invoice.date_envoi_dernier_mail = make_aware(datetime.now(), get_current_timezone())
InvoiceNotificationEmail.objects.create(invoice_number=invoice.id)
invoice.save()