42 lines
1.9 KiB
Python
42 lines
1.9 KiB
Python
from datetime import datetime, timedelta
|
|
import json
|
|
import shutil
|
|
import os
|
|
|
|
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 synchro_orleans.data.models import Facture, InvoiceNotificationEmail
|
|
|
|
tmp_json_location = settings.INVOICES_MAIL_DIR
|
|
json_location = settings.INVOICES_MAIL_LOCATION_PATTERN
|
|
notification_timeout = settings.INVOICES_NOTIFICATION_TIMEOUT
|
|
|
|
class Command(BaseCommand):
|
|
|
|
help = """Checks for new active invoices and creates emails to send to the users"""
|
|
|
|
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]
|
|
tmp_json_file = os.path.join(tmp_json_location, '%s.json' % invoice.id)
|
|
with open(tmp_json_file, 'w') as json_output:
|
|
json.dump({'nameid': nameid.name_id, 'invoice_id': invoice.id}, json_output)
|
|
invoice.date_envoi_dernier_mail = make_aware(datetime.now(), get_current_timezone())
|
|
InvoiceNotificationEmail.objects.create(invoice_number=invoice.id)
|
|
invoice.save()
|
|
shutil.move(tmp_json_file, json_location.format(invoice_id=invoice.id))
|
|
|