passerelle-montpellier-enco.../passerelle_montpellier_enco.../management/commands/notify_sectors.py

44 lines
1.9 KiB
Python

# -*- coding: utf-8 -*-
import requests
from datetime import datetime, timedelta
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.utils.six.moves.urllib import parse as urllib
from passerelle.base.signature import sign_url
from passerelle_montpellier_encombrants.utils import email_sectors
class Command(BaseCommand):
def get(self, url, sign=False):
api_user = getattr(settings, 'ENCOMBRANTS_API_USER')
secret = getattr(settings, 'ENCOMBRANTS_API_SECRET')
orig = getattr(settings, 'ENCOMBRANTS_API_ORIG')
if sign:
url = sign_url(url + '&email=' + urllib.quote(api_user), secret) + '&orig='+urllib.quote(orig)
return requests.get(url, headers={'Accept': 'application/json'})
def handle(self, *args, **kwargs):
if not getattr(settings, 'ENCOMBRANTS_FORM_URL', None):
return
if datetime.today().weekday() in (5, 6):
# we don't notify during the weekend
return
tomorrows = [datetime.today() + timedelta(days=1)]
tomorrows.append(datetime.today() + timedelta(days=2))
if datetime.today().weekday() == 4:
# on Fridays we also notify about Sundays (just to be sure) and Mondays
tomorrows.append(datetime.today() + timedelta(days=3))
for tomorrow in tomorrows:
filter_query = '?filter=all&filter-date=%s&full=on' % tomorrow.strftime('%Y-%m-%d')
url = getattr(settings, 'ENCOMBRANTS_FORM_URL') + filter_query
r = self.get(url, True)
response = r.json()
if 'err' in response:
raise CommandError('Error while retrieving formdefs: %s' % r.json())
response = [x for x in response if x.get('workflow', {}).get('status', {}).get('name') != u'Annulé']
email_sectors(response, tomorrow)