@app.route('/requests/<request_id>', methods=['GET', 'POST'])
def show_request(request_id):
    request_id = request_id.lstrip('#')
    form_errors = []
    submitted_email = None
    if (request.method == 'POST'):
        submitted_email = request.form.get('update_email')
        if submitted_email:
            success = subscribe_to_sr(request_id, submitted_email)
            if (not success):
                form_errors.append('Please use a valid e-mail address.')
    url = ('%s/requests/%s.json' % (app.config['OPEN311_SERVER'], request_id))
    params = {'extensions': 'true', 'legacy': 'false'}
    if app.config['OPEN311_API_KEY']:
        params['api_key'] = app.config['OPEN311_API_KEY']
    r = requests.get(url, params=params)
    if (r.status_code == 404):
        request_id_digits = re.sub('\\D', '', request_id)
        if (len(request_id_digits) == 8):
            request_id_digits = (datetime.date.today().strftime('%y') + request_id_digits)
        if (len(request_id_digits) == 10):
            reformatted = ('%s-%s' % (request_id_digits[:2], request_id_digits[2:]))
            if (reformatted != request_id):
                return redirect(url_for('show_request', request_id=reformatted))
        services = open311tools.services(app.config['OPEN311_SERVER'], app.config['OPEN311_API_KEY'])
        return (render_app_template('error_no_sr.html', request_id=request_id, services=services), 404)
    elif (r.status_code != 200):
        app.logger.error('OPEN311: Error (not 404) loading data for SR %s', request_id)
        return (render_app_template('error_311_api.html', request_id=request_id), 500)
    srs = r.json
    if srs:
        sr = fixup_sr(srs[0], request_id)
        if ('requested_datetime' in sr):
            sr['requested_datetime'] = iso8601.parse_date(sr['requested_datetime'])
        if ('notes' not in sr):
            sr['notes'] = []
        relevant_notes = 0
        for note in sr['notes']:
            note['datetime'] = iso8601.parse_date(note['datetime'])
            if (note['type'] in ('follow_on', 'follow_on_created', 'activity', 'closed')):
                relevant_notes += 1
        by_id = {}
        follow_on_open_count = 0
        follow_on_close_count = 0
        for note in sr['notes']:
            if (note['type'] in ('follow_on', 'follow_on_created', 'follow_on_closed')):
                note_sr_id = note['extended_attributes']['service_request_id']
                if ((note['type'] == 'follow_on_created') or note['description'].endswith('Created')):
                    note['type'] = 'follow_on_created'
                    follow_on_open_count += 1
                    by_id[note_sr_id] = note
                elif ((note['type'] == 'follow_on_closed') or note['description'].endswith('Closed')):
                    follow_on_close_count += 1
                    note['type'] = 'follow_on_closed'
                    if (note_sr_id in by_id):
                        original = by_id[note_sr_id]
                        original['extended_attributes']['closed_datetime'] = note['datetime']
        if (follow_on_open_count > 0):
            sr['notes'] = [n for n in sr['notes'] if (not (n['type'] == 'closed'))]
            sr['status'] = 'open'
            if (follow_on_open_count == follow_on_close_count):
                sr['status'] = 'closed'
                tmp_note = {}
                tmp_note['type'] = 'closed'
                tmp_note['summary'] = 'Request Completed'
                tmp_datetime = sorted([n['extended_attributes']['closed_datetime'] for n in by_id.values()])
                tmp_note['datetime'] = tmp_datetime[0]
                sr['notes'].append(tmp_note)
        if (relevant_notes == 0):
            sr['notes'].append({'type': 'activity', 'summary': ('Under review by %s staff' % sr.get('agency_responsible', ''))})
        subscribed = False
        if ((sr['status'] == 'open') and session.get('addr', None)):
            subscribed = updater.subscription_exists(request_id, 'email', session.get('addr', ''))
        body = render_app_template('service_request.html', sr=sr, subscribed=subscribed, errors=form_errors, submitted_email=submitted_email)
        return (body, 200, None)
    else:
        return (render_app_template('error_no_sr.html', request_id=request_id), 404)
@app.route('/requests/<request_id>', methods=['GET', 'POST'])
def show_request(request_id):
    request_id = request_id.lstrip('#')
    form_errors = []
    submitted_email = None
    if (request.method == 'POST'):
        submitted_email = request.form.get('update_email')
        if submitted_email:
            success = subscribe_to_sr(request_id, submitted_email)
            if (not success):
                form_errors.append('Please use a valid e-mail address.')
    url = ('%s/requests/%s.json' % (app.config['OPEN311_SERVER'], request_id))
    params = {'extensions': 'true', 'legacy': 'false'}
    if app.config['OPEN311_API_KEY']:
        params['api_key'] = app.config['OPEN311_API_KEY']
    r = requests.get(url, params=params)
    if (r.status_code == 404):
        request_id_digits = re.sub('\\D', , request_id)
        if (len(request_id_digits) == 8):
            request_id_digits = (datetime.date.today().strftime('%y') + request_id_digits)
        if (len(request_id_digits) == 10):
            reformatted = ('%s-%s' % (request_id_digits[:2], request_id_digits[2:]))
            if (reformatted != request_id):
                return redirect(url_for('show_request', request_id=reformatted))
        services = open311tools.services(app.config['OPEN311_SERVER'], app.config['OPEN311_API_KEY'])
        return (render_app_template('error_no_sr.html', request_id=request_id, services=services), 404)
    elif (r.status_code != 200):
        app.logger.error('OPEN311: Error (not 404) loading data for SR %s', request_id)
        return (render_app_template('error_311_api.html', request_id=request_id), 500)
    srs = r.json
    if srs:
        sr = fixup_sr(srs[0], request_id)
        if ('requested_datetime' in sr):
            sr['requested_datetime'] = iso8601.parse_date(sr['requested_datetime'])
        if ('notes' not in sr):
            sr['notes'] = []
        relevant_notes = 0
        for note in sr['notes']:
            note['datetime'] = iso8601.parse_date(note['datetime'])
            if (note['type'] in ('follow_on', 'follow_on_created', 'activity', 'closed')):
                relevant_notes += 1
        by_id = {}
        follow_on_open_count = 0
        follow_on_close_count = 0
        for note in sr['notes']:
            if (note['type'] in ('follow_on', 'follow_on_created', 'follow_on_closed')):
                note_sr_id = note['extended_attributes']['service_request_id']
                if ((note['type'] == 'follow_on_created') or note['description'].endswith('Created')):
                    note['type'] = 'follow_on_created'
                    follow_on_open_count += 1
                    by_id[note_sr_id] = note
                elif ((note['type'] == 'follow_on_closed') or note['description'].endswith('Closed')):
                    follow_on_close_count += 1
                    note['type'] = 'follow_on_closed'
                    if (note_sr_id in by_id):
                        original = by_id[note_sr_id]
                        original['extended_attributes']['closed_datetime'] = note['datetime']
        if (follow_on_open_count > 0):
            sr['notes'] = [n for n in sr['notes'] if (not (n['type'] == 'closed'))]
            sr['status'] = 'open'
            if (follow_on_open_count == follow_on_close_count):
                sr['status'] = 'closed'
                tmp_note = {}
                tmp_note['type'] = 'closed'
                tmp_note['summary'] = 'Request Completed'
                tmp_datetime = sorted([n['extended_attributes']['closed_datetime'] for n in by_id.values()])
                tmp_note['datetime'] = tmp_datetime[0]
                sr['notes'].append(tmp_note)
        if (relevant_notes == 0):
            sr['notes'].append({'type': 'activity', 'summary': ('Under review by %s staff' % sr.get('agency_responsible', ))})
        subscribed = False
        if ((sr['status'] == 'open') and session.get('addr', None)):
            subscribed = updater.subscription_exists(request_id, 'email', session.get('addr', ))
        body = render_app_template('service_request.html', sr=sr, subscribed=subscribed, errors=form_errors, submitted_email=submitted_email)
        return (body, 200, None)
    else:
        return (render_app_template('error_no_sr.html', request_id=request_id), 404)