Example #1
0
def notify_updates_on_requests():
    """A scheduled task to check if there are any new requests or updated
    requests within the last hour and notify the involved parts"""

    today = date.today()

    start_date = today.strftime('%Y-%m-%d')
    end_date = (today + timedelta(days=1)).strftime('%Y-%m-%d')
    _requests = get_requests(start_date, end_date, True)

    time_ago = datetime.now(config.TZ) + timedelta(seconds=-(1 * 60 * 10))
    now = datetime.now(config.TZ)
    for _request in _requests:
        requested_datetime = parse(_request['requested_datetime'])
        updated_datetime = parse(_request['updated_datetime'])
        status = _request['status']

        if time_ago <= requested_datetime <= now and status == 'open':
            # New request -> notify responsible company/people
            location = Location.i().guess_location(_request)
            district = location['district']
            neighbourhood = location['neighbourhood']
            location_name = location['location_name']

            if neighbourhood:
                phones = Location.i().get_notified_companies_phones(_request['neighbourhood'], _request['service_code'])

                for phone in phones:
                    text_tpl = 'Novo problema reportado no mopa: No: %s - %s em %s. %s'
                    text = text_tpl % (_request['service_request_id'], _request['service_name'], _request['neighbourhood'], _request.get('description', '').replace('Criado por USSD.', ''))
                    text = truncate(text, 160)
                    db_sms = SMS.static_send(phone, text)
                    Uow.add(db_sms)
                Uow.commit()
            else:
                current_app.logger.error("New request with no neighbourhood data found. Cannot notify companies. Request ID: " + _request['service_request_id'])

        elif (time_ago <= updated_datetime <= now) and status != 'open' and _request.get('phone', ''):
            # Update on request -> notify the person who reported
            text_tpl = 'Caro cidadao, o problema reportado por si: %s foi actualizado. Novo estado: %s. Comentario CMM: %s'
            text = text_tpl % (_request['service_request_id'], _request['service_notice'],  _request.get('status_notes', ''))
            text = truncate(text, 160)
            db_sms = SMS.static_send(_request.get('phone'), text)
            Uow.add(db_sms)
            Uow.commit()

    return "Ok", 200
Example #2
0
def send_daily_survey():
    """Task to send daily survey"""
    survey = Survey(survey_type="G", question=config.SMS_INTRO)
    Uow.add(survey)
    Uow.commit()

    monitor_phones = Location.i().get_monitors_phones()
    for phone in monitor_phones:
        db_sms = SMS.static_send(phone, config.SMS_INTRO)
        Uow.add(db_sms)
        Uow.commit()

    return "Ok", 200
Example #3
0
def send_daily_survey():
    """Task to send daily survey"""
    survey = Survey(survey_type="G", question=config.SMS_INTRO)
    Uow.add(survey)
    Uow.commit()

    monitor_phones = Location.i().get_monitors_phones()
    for phone in monitor_phones:
        db_sms = SMS.static_send(phone, config.SMS_INTRO)
        Uow.add(db_sms)
        Uow.commit()

    return "Ok", 200
Example #4
0
def check_if_answers_were_received():
    """Task to check if monitor answered daily survey and alert them if they did not"""
    monitor_phones = Location.i().get_monitors_phones()

    survey = Survey.todays()

    if survey:
        monitors_who_answered = Survey.get_answerers(survey.id) or []

        for phone in monitor_phones:
            if ("258" + phone) not in monitors_who_answered:
                db_sms = SMS.static_send(phone, config.SMS_NO_FEEDBACK_RECEIVED)
                Uow.add(db_sms)
                Uow.commit()

    return "Ok", 200
Example #5
0
def check_if_answers_were_received():
    """Task to check if monitor answered daily survey and alert them if they did not"""
    monitor_phones = Location.i().get_monitors_phones()

    survey = Survey.todays()

    if survey:
        monitors_who_answered = Survey.get_answerers(survey.id) or []

        for phone in monitor_phones:
            if ("258" + phone) not in monitors_who_answered:
                db_sms = SMS.static_send(phone,
                                         config.SMS_NO_FEEDBACK_RECEIVED)
                Uow.add(db_sms)
                Uow.commit()

    return "Ok", 200
Example #6
0
def notify_updates_on_requests():
    """A scheduled task to check if there are any new requests or updated
    requests within the last hour and notify the involved parts"""

    date_format = '%Y-%m-%d'
    today = date.today()
    start_date = today.strftime(date_format)
    end_date = (today + timedelta(days=1)).strftime(date_format)
    recent_requests = get_requests(start_date, end_date, True)

    time_ago = datetime.now(config.TZ) + timedelta(seconds=-(60 * 5))
    now = datetime.now(config.TZ)

    for _request in recent_requests:
        requested_datetime = parse(_request['requested_datetime'])
        updated_datetime = parse(_request['updated_datetime'])
        service_notice = _request['service_notice']
        request_id = _request['service_request_id']

        if (time_ago <= requested_datetime <=
                now) and service_notice == 'Registado':
            # New request -> notify responsible company/people

            http_response = retry_call(
                requests.get,
                fargs=[
                    config.OPEN311_END_POINTS['people'] + '/' + request_id +
                    '.' + config.OPEN311_RESPONSE_FORMATS['json']
                ],
                exceptions=ConnectTimeout,
                tries=3)

            if http_response.status_code != 200:
                current_app.logger.error(
                    "Could not find people to notify of new request: %s " %
                    _request['service_request_id'])
                continue

            people = http_response.json()
            phones = map(lambda x: x['phone'], people)

            text = ('MOPA - Novo problema No: %s - %s, %s' % (
                _request['service_request_id'],
                _request['service_name'],
                _request.get('description', '')
            )) \
                .replace('Criado por USSD.', '') \
                .replace('Criado por site.', '') \
                .replace('Criado por App.', '')

            for phone in phones:
                SMS.static_send(phone, text)

        elif (time_ago <= updated_datetime <= now) and _request.get(
                'phone', ''):
            # Update on request -> notify the person who reported
            text_tpl = 'Caro municipe, o problema %s tem agora o estado %s. %s'

            if service_notice != 'Em processo':
                text_tpl += '. Caso discorde responda N a esta SMS'

            text = text_tpl % (_request['service_request_id'],
                               _request['service_notice'],
                               _request.get('status_notes', ''))

            SMS.static_send(_request.get('phone'), text)

    return "notify-updates-on-requests completed\n", 200