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

53 lines
2.2 KiB
Python

# -*- coding: utf-8 -*-
import requests
from datetime import datetime, timedelta
import urllib.parse
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
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')
use_http_auth = getattr(settings, 'ENCOMBRANTS_API_HTTP_AUTH', False)
kwargs = {}
if use_http_auth:
kwargs['auth'] = (settings.ENCOMBRANTS_API_HTTP_USERNAME, settings.ENCOMBRANTS_API_HTTP_PASSWORD)
elif sign:
url = (
sign_url(url + '&email=' + urllib.parse.quote(api_user), secret)
+ '&orig='
+ urllib.parse.quote(orig)
)
return requests.get(url, headers={'Accept': 'application/json'}, *kwargs)
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)]
if datetime.today().weekday() == 4:
# on Fridays we also notify about Sundays (just to be sure) and Mondays
tomorrows.append(datetime.today() + timedelta(days=2))
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)