Ejemplo n.º 1
0
def set_template_sender(service_id, template_id):
    template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)
    sender_details = get_template_sender_form_dict(service_id, template)
    no_senders = sender_details.get("no_senders", False)

    form = SetTemplateSenderForm(
        sender=sender_details["current_choice"],
        sender_choices=sender_details["value_and_label"],
    )
    option_hints = {sender_details["default_sender"]: "(Default)"}

    if form.validate_on_submit():
        service_api_client.update_service_template_sender(
            service_id,
            template_id,
            form.sender.data if form.sender.data else None,
        )
        return redirect(
            url_for(".view_template",
                    service_id=service_id,
                    template_id=template_id))

    return render_template(
        "views/templates/set-template-sender.html",
        form=form,
        template_id=template_id,
        no_senders=no_senders,
        option_hints=option_hints,
    )
Ejemplo n.º 2
0
def set_template_sender(service_id, template_id):
    template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)
    sender_details = get_template_sender_form_dict(service_id, template)
    no_senders = sender_details.get('no_senders', False)

    form = SetTemplateSenderForm(
        sender=sender_details['current_choice'],
        sender_choices=sender_details['value_and_label'],
    )
    form.sender.param_extensions = {'items': []}
    for item_value, _item_label in sender_details['value_and_label']:
        if item_value == sender_details['default_sender']:
            extensions = {'hint': {'text': '(Default)'}}
        else:
            extensions = {
            }  # if no extensions needed, send an empty dict to preserve order of items

        form.sender.param_extensions['items'].append(extensions)

    if form.validate_on_submit():
        service_api_client.update_service_template_sender(
            service_id,
            template_id,
            form.sender.data if form.sender.data else None,
        )
        return redirect(
            url_for('.view_template',
                    service_id=service_id,
                    template_id=template_id))

    return render_template('views/templates/set-template-sender.html',
                           form=form,
                           template_id=template_id,
                           no_senders=no_senders)
Ejemplo n.º 3
0
def send_test(service_id, template_id):
    session["recipient"] = None
    session["placeholders"] = {}
    session["send_test_letter_page_count"] = None

    db_template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)
    if db_template["template_type"] == "letter":
        session["sender_id"] = None

    if email_or_sms_not_enabled(db_template["template_type"],
                                current_service.permissions):
        return redirect(
            url_for(
                ".action_blocked",
                service_id=service_id,
                notification_type=db_template["template_type"],
                return_to="view_template",
                template_id=template_id,
            ))

    return redirect(
        url_for(
            {
                "main.send_test": ".send_test_step",
                "main.send_one_off": ".send_one_off_step",
            }[request.endpoint],
            service_id=service_id,
            template_id=template_id,
            step_index=0,
            help=get_help_argument(),
        ))
def begin_tour(service_id, template_id):
    db_template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)

    if (db_template['template_type'] != 'sms'
            or not current_user.mobile_number):
        abort(404)

    template = get_template(
        db_template,
        current_service,
        show_recipient=True,
    )

    template.values = {"phone_number": current_user.mobile_number}

    session['placeholders'] = {}

    return render_template('views/templates/start-tour.html',
                           template=template,
                           help='1',
                           continue_link=url_for('.tour_step',
                                                 service_id=service_id,
                                                 template_id=template_id,
                                                 step_index=1))
Ejemplo n.º 5
0
def send_test(service_id, template_id):
    session['recipient'] = None
    session['placeholders'] = {}
    session['send_test_letter_page_count'] = None

    db_template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)
    if db_template['template_type'] == 'letter':
        session['sender_id'] = None

    if email_or_sms_not_enabled(db_template['template_type'],
                                current_service.permissions):
        return redirect(
            url_for('.action_blocked',
                    service_id=service_id,
                    notification_type=db_template['template_type'],
                    return_to='view_template',
                    template_id=template_id))

    return redirect(
        url_for(
            {
                'main.send_test': '.send_test_step',
                'main.send_one_off': '.send_one_off_step',
            }[request.endpoint],
            service_id=service_id,
            template_id=template_id,
            step_index=0,
            help=get_help_argument(),
        ))
Ejemplo n.º 6
0
def send_one_off(service_id, template_id):
    session['recipient'] = None
    session['placeholders'] = {}

    db_template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)
    if db_template['template_type'] == 'letter':
        session['sender_id'] = None
        return redirect(
            url_for('.send_one_off_letter_address',
                    service_id=service_id,
                    template_id=template_id))

    if db_template[
            'template_type'] not in current_service.available_template_types:
        return redirect(
            url_for('.action_blocked',
                    service_id=service_id,
                    notification_type=db_template['template_type'],
                    return_to='view_template',
                    template_id=template_id))

    return redirect(
        url_for(
            '.send_one_off_step',
            service_id=service_id,
            template_id=template_id,
            step_index=0,
        ))
Ejemplo n.º 7
0
def set_template_sender(service_id, template_id):
    template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)
    sender_details = get_template_sender_form_dict(service_id, template)
    no_senders = sender_details.get('no_senders', False)

    form = SetTemplateSenderForm(
        sender=sender_details['current_choice'],
        sender_choices=sender_details['value_and_label'],
    )
    option_hints = {sender_details['default_sender']: '(Default)'}

    if form.validate_on_submit():
        service_api_client.update_service_template_sender(
            service_id,
            template_id,
            form.sender.data if form.sender.data else None,
        )
        return redirect(
            url_for('.view_template',
                    service_id=service_id,
                    template_id=template_id))

    return render_template('views/templates/set-template-sender.html',
                           form=form,
                           template_id=template_id,
                           no_senders=no_senders,
                           option_hints=option_hints)
Ejemplo n.º 8
0
def send_one_off_letter_address(service_id, template_id):
    if {'recipient', 'placeholders'} - set(session.keys()):
        # if someone has come here via a bookmark or back button they might have some stuff still in their session
        return redirect(url_for('.send_one_off', service_id=service_id, template_id=template_id))

    db_template = current_service.get_template_with_user_permission_or_403(template_id, current_user)

    template = get_template(
        db_template,
        current_service,
        show_recipient=True,
        letter_preview_url=url_for(
            'no_cookie.send_test_preview',
            service_id=service_id,
            template_id=template_id,
            filetype='png',
        ),
        page_count=get_page_count_for_letter(db_template),
        email_reply_to=None,
        sms_sender=None
    )

    current_session_address = PostalAddress.from_personalisation(
        get_normalised_placeholders_from_session()
    )

    form = LetterAddressForm(
        address=current_session_address.normalised,
        allow_international_letters=current_service.has_permission('international_letters'),
    )

    if form.validate_on_submit():
        session['placeholders'].update(PostalAddress(form.address.data).as_personalisation)

        placeholders = fields_to_fill_in(template)
        if all_placeholders_in_session(placeholders):
            return get_notification_check_endpoint(service_id, template)

        first_non_address_placeholder_index = len(address_lines_1_to_7_keys)

        return redirect(url_for(
            'main.send_one_off_step',
            service_id=service_id,
            template_id=template_id,
            step_index=first_non_address_placeholder_index,
        ))

    return render_template(
        'views/send-one-off-letter-address.html',
        page_title=get_send_test_page_title(
            template_type='letter',
            entering_recipient=True,
            name=template.name,
        ),
        template=template,
        form=form,
        back_link=get_back_link(service_id, template, 0),
        link_to_upload=True,
    )
Ejemplo n.º 9
0
def confirm_redact_template(service_id, template_id):
    template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)

    return render_template(
        'views/templates/template.html',
        template=get_email_preview_template(template, template['id'],
                                            service_id),
        user_has_template_permission=True,
        show_redaction_message=True,
    )
Ejemplo n.º 10
0
def set_sender(service_id, template_id):
    session['sender_id'] = None
    redirect_to_one_off = redirect(
        url_for('.send_one_off', service_id=service_id, template_id=template_id)
    )

    template = current_service.get_template_with_user_permission_or_403(template_id, current_user)

    if template['template_type'] == 'letter':
        return redirect_to_one_off

    sender_details = get_sender_details(service_id, template['template_type'])

    if len(sender_details) == 1:
        session['sender_id'] = sender_details[0]['id']

    if len(sender_details) <= 1:
        return redirect_to_one_off

    sender_context = get_sender_context(sender_details, template['template_type'])

    form = SetSenderForm(
        sender=sender_context['default_id'],
        sender_choices=sender_context['value_and_label'],
        sender_label=sender_context['description']
    )
    option_hints = {sender_context['default_id']: '(Default)'}
    if sender_context.get('receives_text_message', None):
        option_hints.update({sender_context['receives_text_message']: '(Receives replies)'})
    if sender_context.get('default_and_receives', None):
        option_hints = {sender_context['default_and_receives']: '(Default and receives replies)'}

    # extend all radios that need hint text
    form.sender.param_extensions = {'items': []}
    for item_id, _item_value in form.sender.choices:
        if item_id in option_hints:
            extensions = {'hint': {'text': option_hints[item_id]}}
        else:
            extensions = {}  # if no extensions needed, send an empty dict to preserve order of items
        form.sender.param_extensions['items'].append(extensions)

    if form.validate_on_submit():
        session['sender_id'] = form.sender.data
        return redirect(url_for('.send_one_off',
                                service_id=service_id,
                                template_id=template_id))

    return render_template(
        'views/templates/set-sender.html',
        form=form,
        template_id=template_id,
        sender_context={'title': sender_context['title'], 'description': sender_context['description']},
        option_hints=option_hints
    )
Ejemplo n.º 11
0
def set_sender(service_id, template_id):
    session["sender_id"] = None
    redirect_to_one_off = redirect(
        url_for(".send_one_off",
                service_id=service_id,
                template_id=template_id))

    template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)

    if template["template_type"] == "letter":
        return redirect_to_one_off

    sender_details = get_sender_details(service_id, template["template_type"])
    if len(sender_details) <= 1:
        return redirect_to_one_off

    sender_context = get_sender_context(sender_details,
                                        template["template_type"])

    form = SetSenderForm(
        sender=sender_context["default_id"],
        sender_choices=sender_context["value_and_label"],
        sender_label=sender_context["description"],
    )
    option_hints = {sender_context["default_id"]: _l("(Default)")}
    if sender_context.get("receives_text_message", None):
        option_hints.update({
            sender_context["receives_text_message"]:
            _l("(Receives replies)")
        })
    if sender_context.get("default_and_receives", None):
        option_hints = {
            sender_context["default_and_receives"]:
            _l("(Default and receives replies)")
        }

    if form.validate_on_submit():
        session["sender_id"] = form.sender.data
        return redirect(
            url_for(".send_one_off",
                    service_id=service_id,
                    template_id=template_id))

    return render_template(
        "views/templates/set-sender.html",
        form=form,
        template_id=template_id,
        sender_context={
            "title": sender_context["title"],
            "description": sender_context["description"],
        },
        option_hints=option_hints,
    )
Ejemplo n.º 12
0
def set_sender(service_id, template_id):
    session['sender_id'] = None
    redirect_to_one_off = redirect(
        url_for('.send_one_off',
                service_id=service_id,
                template_id=template_id))

    template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)

    if template['template_type'] == 'letter':
        return redirect_to_one_off

    sender_details = get_sender_details(service_id, template['template_type'])
    if len(sender_details) <= 1:
        return redirect_to_one_off

    sender_context = get_sender_context(sender_details,
                                        template['template_type'])

    form = SetSenderForm(sender=sender_context['default_id'],
                         sender_choices=sender_context['value_and_label'],
                         sender_label=sender_context['description'])
    option_hints = {sender_context['default_id']: _l('(Default)')}
    if sender_context.get('receives_text_message', None):
        option_hints.update({
            sender_context['receives_text_message']:
            _l('(Receives replies)')
        })
    if sender_context.get('default_and_receives', None):
        option_hints = {
            sender_context['default_and_receives']:
            _l('(Default and receives replies)')
        }

    if form.validate_on_submit():
        session['sender_id'] = form.sender.data
        return redirect(
            url_for('.send_one_off',
                    service_id=service_id,
                    template_id=template_id))

    return render_template('views/templates/set-sender.html',
                           form=form,
                           template_id=template_id,
                           sender_context={
                               'title': sender_context['title'],
                               'description': sender_context['description']
                           },
                           option_hints=option_hints)
Ejemplo n.º 13
0
def delete_service_template(service_id, template_id):
    template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)

    if request.method == "POST":
        service_api_client.delete_service_template(service_id, template_id)
        return redirect(
            url_for(
                ".choose_template",
                service_id=service_id,
                template_folder_id=template["folder"],
            ))

    try:
        last_used_notification = template_statistics_client.get_template_statistics_for_template(
            service_id, template["id"])

        last_used_text = ""
        if not last_used_notification:
            last_used_text = _l("more than seven days")
        else:
            last_used_date = parse(
                last_used_notification["created_at"]).replace(tzinfo=None)
            last_used_text = get_human_readable_delta(last_used_date,
                                                      datetime.utcnow())

        message = "{} {} {}".format(_l("This template was last used"),
                                    last_used_text, _l("ago."))

    except HTTPError as e:
        if e.status_code == 404:
            message = None
        else:
            raise e

    flash(
        [
            "{} ‘{}’?".format(_l("Are you sure you want to delete"),
                              template["name"]),
            message,
        ],
        "delete",
    )
    return render_template(
        "views/templates/template.html",
        template=get_email_preview_template(template, template["id"],
                                            service_id),
        user_has_template_permission=True,
    )
Ejemplo n.º 14
0
def choose_from_contact_list(service_id, template_id):
    db_template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)
    template = get_template(
        db_template,
        current_service,
    )
    return render_template(
        'views/send-contact-list.html',
        contact_lists=ContactListsAlphabetical(
            current_service.id,
            template_type=template.template_type,
        ),
        template=template,
    )
Ejemplo n.º 15
0
def delete_service_template(service_id, template_id):
    template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)

    if request.method == 'POST':
        service_api_client.delete_service_template(service_id, template_id)
        return redirect(
            url_for(
                '.choose_template',
                service_id=service_id,
                template_folder_id=template['folder'],
            ))

    try:
        last_used_notification = template_statistics_client.get_template_statistics_for_template(
            service_id, template['id'])
        message = 'This template was last used {} ago.'.format(
            'more than seven days'
            if not last_used_notification else get_human_readable_delta(
                parse(last_used_notification['created_at']).replace(
                    tzinfo=None), datetime.utcnow()))

    except HTTPError as e:
        if e.status_code == 404:
            message = None
        else:
            raise e

    flash([
        "Are you sure you want to delete ‘{}’?".format(template['name']),
        message
    ], 'delete')
    return render_template(
        'views/templates/template.html',
        template=get_template(
            template,
            current_service,
            expand_emails=True,
            letter_preview_url=url_for(
                '.view_letter_template_preview',
                service_id=service_id,
                template_id=template['id'],
                filetype='png',
            ),
            show_recipient=True,
        ),
        user_has_template_permission=True,
    )
Ejemplo n.º 16
0
def _check_notification(service_id, template_id, exception=None):
    db_template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)
    email_reply_to = None
    sms_sender = None
    if db_template['template_type'] == 'email':
        email_reply_to = get_email_reply_to_address_from_session()
    elif db_template['template_type'] == 'sms':
        sms_sender = get_sms_sender_from_session()
    template = get_template(
        db_template,
        current_service,
        show_recipient=True,
        email_reply_to=email_reply_to,
        sms_sender=sms_sender,
        letter_preview_url=url_for(
            'no_cookie.check_notification_preview',
            service_id=service_id,
            template_id=template_id,
            filetype='png',
        ),
        page_count=get_page_count_for_letter(db_template),
    )

    placeholders = fields_to_fill_in(template)

    back_link = get_back_link(service_id, template, len(placeholders),
                              placeholders)

    if ((not session.get('recipient')
         and db_template['template_type'] != 'letter')
            or not all_placeholders_in_session(template.placeholders)):
        raise PermanentRedirect(back_link)

    template.values = get_recipient_and_placeholders_from_session(
        template.template_type)
    page_count = get_page_count_for_letter(db_template, template.values)
    template.page_count = page_count
    return dict(
        template=template,
        back_link=back_link,
        help=get_help_argument(),
        letter_too_long=is_letter_too_long(page_count),
        letter_max_pages=LETTER_MAX_PAGE_COUNT,
        page_count=page_count,
        **(get_template_error_dict(exception) if exception else {}),
    )
Ejemplo n.º 17
0
def _check_notification(service_id, template_id, exception=None):
    db_template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)
    email_reply_to = None
    sms_sender = None
    if db_template["template_type"] == "email":
        email_reply_to = get_email_reply_to_address_from_session()
    elif db_template["template_type"] == "sms":
        sms_sender = get_sms_sender_from_session()
    template = get_template(
        db_template,
        current_service,
        show_recipient=True,
        email_reply_to=email_reply_to,
        sms_sender=sms_sender,
        letter_preview_url=url_for(
            ".check_notification_preview",
            service_id=service_id,
            template_id=template_id,
            filetype="png",
        ),
        page_count=get_page_count_for_letter(db_template),
    )

    step_index = len(
        fields_to_fill_in(
            template,
            prefill_current_user=(
                session.get("send_step") == "main.send_test_step"),
        ))
    back_link = get_back_link(service_id, template, step_index)

    if (not session.get("recipient")
            and db_template["template_type"] != "letter"
        ) or not all_placeholders_in_session(template.placeholders):
        raise PermanentRedirect(back_link)

    template.values = get_recipient_and_placeholders_from_session(
        template.template_type)
    return dict(
        template=template,
        back_link=back_link,
        help=get_help_argument(),
        **(get_template_error_dict(exception) if exception else {}),
    )
Ejemplo n.º 18
0
def edit_template_postage(service_id, template_id):
    template = current_service.get_template_with_user_permission_or_403(template_id, current_user)
    if template["template_type"] != "letter":
        abort(404)
    form = LetterTemplatePostageForm(**template)
    if form.validate_on_submit():
        postage = form.postage.data
        service_api_client.update_service_template_postage(service_id, template_id, postage)

        return redirect(url_for('.view_template', service_id=service_id, template_id=template_id))

    return render_template(
        'views/templates/edit-template-postage.html',
        form=form,
        service_id=service_id,
        template_id=template_id,
        template_postage=template["postage"]
    )
Ejemplo n.º 19
0
def delete_service_template(service_id, template_id):
    template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)

    if request.method == 'POST':
        service_api_client.delete_service_template(service_id, template_id)
        return redirect(
            url_for(
                '.choose_template',
                service_id=service_id,
                template_folder_id=template['folder'],
            ))

    try:
        last_used_notification = template_statistics_client.get_last_used_date_for_template(
            service_id, template['id'])
        message = 'This template has never been used.' if not last_used_notification else \
            'This template was last used {}.'.format(format_delta(last_used_notification))

    except HTTPError as e:
        if e.status_code == 404:
            message = None
        else:
            raise e

    flash([
        "Are you sure you want to delete ‘{}’?".format(template['name']),
        message
    ], 'delete')
    return render_template(
        'views/templates/template.html',
        template=get_template(
            template,
            current_service,
            letter_preview_url=url_for(
                'no_cookie.view_letter_template_preview',
                service_id=service_id,
                template_id=template['id'],
                filetype='png',
            ),
            show_recipient=True,
        ),
        user_has_template_permission=True,
    )
Ejemplo n.º 20
0
def confirm_redact_template(service_id, template_id):
    template = current_service.get_template_with_user_permission_or_403(template_id, current_user)

    return render_template(
        'views/templates/template.html',
        template=get_template(
            template,
            current_service,
            letter_preview_url=url_for(
                '.view_letter_template_preview',
                service_id=service_id,
                template_id=template_id,
                filetype='png',
            ),
            show_recipient=True,
        ),
        user_has_template_permission=True,
        show_redaction_message=True,
    )
Ejemplo n.º 21
0
def send_notification(service_id, template_id):
    if {"recipient", "placeholders"} - set(session.keys()):
        return redirect(
            url_for(
                ".send_one_off",
                service_id=service_id,
                template_id=template_id,
            ))

    db_template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)

    try:
        noti = notification_api_client.send_notification(
            service_id,
            template_id=db_template["id"],
            recipient=session["recipient"]
            or session["placeholders"]["address line 1"],
            personalisation=session["placeholders"],
            sender_id=session["sender_id"] if "sender_id" in session else None,
        )
    except HTTPError as exception:
        current_app.logger.info(
            'Service {} could not send notification: "{}"'.format(
                current_service.id, exception.message))
        return render_template(
            "views/notifications/check.html",
            **_check_notification(service_id, template_id, exception),
        )

    session.pop("placeholders")
    session.pop("recipient")
    session.pop("sender_id", None)
    session.pop("send_step", None)

    return redirect(
        url_for(
            ".view_notification",
            service_id=service_id,
            notification_id=noti["id"],
            help=request.args.get("help"),
            just_sent=True,
        ))
Ejemplo n.º 22
0
def send_one_off_to_myself(service_id, template_id):
    db_template = current_service.get_template_with_user_permission_or_403(template_id, current_user)

    if db_template['template_type'] not in ("sms", "email"):
        abort(404)

    # We aren't concerned with creating the exact template (for example adding recipient and sender names)
    # we just want to create enough to use `fields_to_fill_in`
    template = get_template(
        db_template,
        current_service,
    )
    fields_to_fill_in(template, prefill_current_user=True)

    return redirect(url_for(
        'main.send_one_off_step',
        service_id=service_id,
        template_id=template_id,
        step_index=1,
    ))
Ejemplo n.º 23
0
def send_notification(service_id, template_id):
    if {'recipient', 'placeholders'} - set(session.keys()):
        return redirect(
            url_for(
                '.send_one_off',
                service_id=service_id,
                template_id=template_id,
            ))

    db_template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)

    try:
        noti = notification_api_client.send_notification(
            service_id,
            template_id=db_template['id'],
            recipient=session['recipient']
            or Columns(session['placeholders'])['address line 1'],
            personalisation=session['placeholders'],
            sender_id=session['sender_id'] if 'sender_id' in session else None)
    except HTTPError as exception:
        current_app.logger.info(
            'Service {} could not send notification: "{}"'.format(
                current_service.id, exception.message))
        return render_template(
            'views/notifications/check.html',
            **_check_notification(service_id, template_id, exception),
        )

    session.pop('placeholders')
    session.pop('recipient')
    session.pop('sender_id', None)

    return redirect(
        url_for(
            '.view_notification',
            service_id=service_id,
            notification_id=noti['id'],
            # used to show the final step of the tour (help=3) or not show
            # a back link on a just sent one off notification (help=0)
            help=request.args.get('help')))
Ejemplo n.º 24
0
def send_test_preview(service_id, template_id, filetype):

    if filetype not in ('pdf', 'png'):
        abort(404)

    db_template = current_service.get_template_with_user_permission_or_403(template_id, current_user)

    template = get_template(
        db_template,
        current_service,
        letter_preview_url=url_for(
            '.send_test_preview',
            service_id=service_id,
            template_id=template_id,
            filetype='png',
        ),
    )

    template.values = get_normalised_placeholders_from_session()

    return TemplatePreview.from_utils_template(template, filetype, page=request.args.get('page'))
def check_tour_notification(service_id, template_id):
    db_template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)

    template = get_template(
        db_template,
        current_service,
        show_recipient=True,
    )

    if 'placeholders' not in session:
        return redirect(
            url_for('.begin_tour',
                    service_id=current_service.id,
                    template_id=template_id))

    placeholders = fields_to_fill_in(template, prefill_current_user=True)

    if not all_placeholders_in_session(template.placeholders):
        return redirect(
            url_for('.tour_step',
                    service_id=current_service.id,
                    template_id=template_id,
                    step_index=1))

    back_link = url_for('.tour_step',
                        service_id=current_service.id,
                        template_id=template_id,
                        step_index=len(placeholders))

    template.values = get_recipient_and_placeholders_from_session(
        template.template_type)

    return render_template(
        'views/notifications/check.html',
        template=template,
        back_link=back_link,
        help='2',
    )
Ejemplo n.º 26
0
def edit_service_template(service_id, template_id):
    template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)
    template['template_content'] = template['content']
    form = form_objects[template['template_type']](**template)
    if form.validate_on_submit():
        if form.process_type.data != template['process_type']:
            abort_403_if_not_admin_user()

        subject = form.subject.data if hasattr(form, 'subject') else None

        new_template_data = {
            'name': form.name.data,
            'content': form.template_content.data,
            'subject': subject,
            'template_type': template['template_type'],
            'id': template['id'],
            'process_type': form.process_type.data,
            'reply_to_text': template['reply_to_text'],
        }

        new_template = get_template(new_template_data, current_service)
        template_change = get_template(
            template, current_service).compare_to(new_template)

        if (template_change.placeholders_added
                and not request.form.get('confirm')
                and current_service.api_keys):
            return render_template(
                'views/templates/breaking-change.html',
                template_change=template_change,
                new_template=new_template,
                form=form,
            )
        try:
            service_api_client.update_service_template(
                template_id,
                form.name.data,
                template['template_type'],
                form.template_content.data,
                service_id,
                subject,
                form.process_type.data,
            )
        except HTTPError as e:
            if e.status_code == 400:
                if 'content' in e.message and any([
                        'character count greater than' in x
                        for x in e.message['content']
                ]):
                    form.template_content.errors.extend(e.message['content'])
                else:
                    raise e
            else:
                raise e
        else:
            return redirect(
                url_for('.view_template',
                        service_id=service_id,
                        template_id=template_id))

    if template[
            'template_type'] not in current_service.available_template_types:
        return redirect(
            url_for('.action_blocked',
                    service_id=service_id,
                    notification_type=template['template_type'],
                    return_to='view_template',
                    template_id=template_id))
    else:
        return render_template(
            'views/edit-{}-template.html'.format(template['template_type']),
            form=form,
            template=template,
            heading_action='Edit',
        )
Ejemplo n.º 27
0
def _check_messages(service_id,
                    template_id,
                    upload_id,
                    preview_row,
                    letters_as_pdf=False):

    try:
        # The happy path is that the job doesn’t already exist, so the
        # API will return a 404 and the client will raise HTTPError.
        job_api_client.get_job(service_id, upload_id)

        # the job exists already - so go back to the templates page
        # If we just return a `redirect` (302) object here, we'll get
        # errors when we try and unpack in the check_messages route.
        # Rasing a werkzeug.routing redirect means that doesn't happen.
        raise PermanentRedirect(
            url_for('.send_messages',
                    service_id=service_id,
                    template_id=template_id))
    except HTTPError as e:
        if e.status_code != 404:
            raise

    statistics = service_api_client.get_service_statistics(service_id,
                                                           today_only=True)
    remaining_messages = (current_service.message_limit -
                          sum(stat['requested']
                              for stat in statistics.values()))

    contents = s3download(service_id, upload_id)

    db_template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)

    email_reply_to = None
    sms_sender = None
    if db_template['template_type'] == 'email':
        email_reply_to = get_email_reply_to_address_from_session()
    elif db_template['template_type'] == 'sms':
        sms_sender = get_sms_sender_from_session()
    template = get_template(
        db_template,
        current_service,
        show_recipient=True,
        letter_preview_url=url_for(
            '.check_messages_preview',
            service_id=service_id,
            template_id=template_id,
            upload_id=upload_id,
            filetype='png',
            row_index=preview_row,
        ) if not letters_as_pdf else None,
        email_reply_to=email_reply_to,
        sms_sender=sms_sender,
        page_count=get_page_count_for_letter(db_template),
    )
    recipients = RecipientCSV(
        contents,
        template_type=template.template_type,
        placeholders=template.placeholders,
        max_initial_rows_shown=50,
        max_errors_shown=50,
        whitelist=itertools.chain.from_iterable(
            [user.name, user.mobile_number, user.email_address]
            for user in Users(service_id))
        if current_service.trial_mode else None,
        remaining_messages=remaining_messages,
        international_sms=current_service.has_permission('international_sms'),
    )

    if request.args.get('from_test'):
        # only happens if generating a letter preview test
        back_link = url_for('.send_test',
                            service_id=service_id,
                            template_id=template.id)
        choose_time_form = None
    else:
        back_link = url_for('.send_messages',
                            service_id=service_id,
                            template_id=template.id)
        choose_time_form = ChooseTimeForm()

    if preview_row < 2:
        abort(404)

    if preview_row < len(recipients) + 2:
        template.values = recipients[preview_row -
                                     2].recipient_and_personalisation
    elif preview_row > 2:
        abort(404)

    return dict(
        recipients=recipients,
        template=template,
        errors=recipients.has_errors,
        row_errors=get_errors_for_csv(recipients, template.template_type),
        count_of_recipients=len(recipients),
        count_of_displayed_recipients=len(list(recipients.displayed_rows)),
        original_file_name=request.args.get('original_file_name', ''),
        upload_id=upload_id,
        form=CsvUploadForm(),
        remaining_messages=remaining_messages,
        choose_time_form=choose_time_form,
        back_link=back_link,
        help=get_help_argument(),
        trying_to_send_letters_in_trial_mode=all((
            current_service.trial_mode,
            template.template_type == 'letter',
        )),
        required_recipient_columns=OrderedSet(
            recipients.recipient_column_headers) - optional_address_columns,
        preview_row=preview_row,
        sent_previously=job_api_client.has_sent_previously(
            service_id, template.id, db_template['version'],
            request.args.get('original_file_name', '')))
Ejemplo n.º 28
0
def send_test_step(service_id, template_id, step_index):
    if {'recipient', 'placeholders'} - set(session.keys()):
        return redirect(
            url_for(
                {
                    'main.send_test_step': '.send_test',
                    'main.send_one_off_step': '.send_one_off',
                }[request.endpoint],
                service_id=service_id,
                template_id=template_id,
            ))

    db_template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)

    if not session.get('send_test_letter_page_count'):
        session['send_test_letter_page_count'] = get_page_count_for_letter(
            db_template)
    email_reply_to = None
    sms_sender = None
    if db_template['template_type'] == 'email':
        email_reply_to = get_email_reply_to_address_from_session()
    elif db_template['template_type'] == 'sms':
        sms_sender = get_sms_sender_from_session()
    template = get_template(db_template,
                            current_service,
                            show_recipient=True,
                            letter_preview_url=url_for(
                                '.send_test_preview',
                                service_id=service_id,
                                template_id=template_id,
                                filetype='png',
                            ),
                            page_count=session['send_test_letter_page_count'],
                            email_reply_to=email_reply_to,
                            sms_sender=sms_sender)

    placeholders = fields_to_fill_in(
        template,
        prefill_current_user=(request.endpoint == 'main.send_test_step'),
    )

    # used to set the back link in the check_notification screen
    session['send_step'] = request.endpoint

    try:
        current_placeholder = placeholders[step_index]
    except IndexError:
        if all_placeholders_in_session(placeholders):
            return get_notification_check_endpoint(service_id, template)
        return redirect(
            url_for(
                {
                    'main.send_test_step': '.send_test',
                    'main.send_one_off_step': '.send_one_off',
                }[request.endpoint],
                service_id=service_id,
                template_id=template_id,
            ))

    optional_placeholder = (current_placeholder in optional_address_columns)
    form = get_placeholder_form_instance(
        current_placeholder,
        dict_to_populate_from=get_normalised_placeholders_from_session(),
        template_type=template.template_type,
        optional_placeholder=optional_placeholder,
        allow_international_phone_numbers=current_service.has_permission(
            'international_sms'),
    )

    if form.validate_on_submit():
        # if it's the first input (phone/email), we store against `recipient` as well, for easier extraction.
        # Only if it's not a letter.
        # And only if we're not on the test route, since that will already have the user's own number set
        if (step_index == 0 and template.template_type != 'letter'
                and request.endpoint != 'main.send_test_step'):
            session['recipient'] = form.placeholder_value.data

        session['placeholders'][
            current_placeholder] = form.placeholder_value.data

        if all_placeholders_in_session(placeholders):
            return get_notification_check_endpoint(service_id, template)

        return redirect(
            url_for(
                request.endpoint,
                service_id=service_id,
                template_id=template_id,
                step_index=step_index + 1,
                help=get_help_argument(),
            ))

    back_link = get_back_link(service_id, template, step_index)

    template.values = get_recipient_and_placeholders_from_session(
        template.template_type)
    template.values[current_placeholder] = None

    if (request.endpoint == 'main.send_one_off_step' and step_index == 0
            and template.template_type != 'letter'
            and not (template.template_type == 'sms'
                     and current_user.mobile_number is None)
            and current_user.has_permissions('manage_templates',
                                             'manage_service')):

        type = first_column_headings[template.template_type][0]

        if (type == "email address"):
            type = _l("email address")
        elif (type == "phone number"):
            type = _l("phone number")

        skip_link = (
            '{} {}'.format(_l("Use my"), type),
            url_for('.send_test',
                    service_id=service_id,
                    template_id=template.id),
        )
    else:
        skip_link = None
    return render_template(
        'views/send-test.html',
        page_title=get_send_test_page_title(
            template.template_type,
            get_help_argument(),
            entering_recipient=not session['recipient'],
            name=template.name,
        ),
        template=template,
        form=form,
        skip_link=skip_link,
        optional_placeholder=optional_placeholder,
        back_link=back_link,
        help=get_help_argument(),
        link_to_upload=(request.endpoint == 'main.send_one_off_step'
                        and step_index == 0),
    )
Ejemplo n.º 29
0
def send_messages(service_id, template_id):
    # if there's lots of data in the session, lets log it for debugging purposes
    # TODO: Remove this once we're confident we have session size under control
    if len(session.get('file_uploads', {}).keys()) > 2:
        current_app.logger.info(
            'session contains large file_uploads - json_len {}, keys: {}'.
            format(len(json.dumps(session['file_uploads'])),
                   session['file_uploads'].keys()))

    db_template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)

    email_reply_to = None
    sms_sender = None

    if db_template['template_type'] == 'email':
        email_reply_to = get_email_reply_to_address_from_session()
    elif db_template['template_type'] == 'sms':
        sms_sender = get_sms_sender_from_session()

    if email_or_sms_not_enabled(db_template['template_type'],
                                current_service.permissions):
        return redirect(
            url_for('.action_blocked',
                    service_id=service_id,
                    notification_type=db_template['template_type'],
                    return_to='view_template',
                    template_id=template_id))

    template = get_template(
        db_template,
        current_service,
        show_recipient=True,
        letter_preview_url=url_for(
            '.view_letter_template_preview',
            service_id=service_id,
            template_id=template_id,
            filetype='png',
            page_count=get_page_count_for_letter(db_template),
        ),
        email_reply_to=email_reply_to,
        sms_sender=sms_sender,
    )

    form = CsvUploadForm()
    if form.validate_on_submit():
        try:
            upload_id = s3upload(
                service_id,
                Spreadsheet.from_file(
                    form.file.data, filename=form.file.data.filename).as_dict,
                current_app.config['AWS_REGION'])
            return redirect(
                url_for(
                    '.check_messages',
                    service_id=service_id,
                    upload_id=upload_id,
                    template_id=template.id,
                    original_file_name=form.file.data.filename,
                ))
        except (UnicodeDecodeError, BadZipFile, XLRDError):
            flash(
                'Couldn’t read {}. Try using a different file format.'.format(
                    form.file.data.filename))
        except (XLDateError):
            flash((
                '{} contains numbers or dates that Notification can’t understand. '
                'Try formatting all columns as ‘text’ or export your file as CSV.'
            ).format(form.file.data.filename))

    column_headings = get_spreadsheet_column_headings_from_template(template)

    return render_template(
        'views/send.html',
        template=template,
        column_headings=list(ascii_uppercase[:len(column_headings)]),
        example=[column_headings,
                 get_example_csv_rows(template)],
        form=form)
Ejemplo n.º 30
0
def send_one_off_step(service_id, template_id, step_index):
    if {'recipient', 'placeholders'} - set(session.keys()):
        return redirect(
            url_for(
                ".send_one_off",
                service_id=service_id,
                template_id=template_id,
            ))

    db_template = current_service.get_template_with_user_permission_or_403(
        template_id, current_user)

    email_reply_to = None
    sms_sender = None
    if db_template['template_type'] == 'email':
        email_reply_to = get_email_reply_to_address_from_session()
    elif db_template['template_type'] == 'sms':
        sms_sender = get_sms_sender_from_session()

    template_values = get_recipient_and_placeholders_from_session(
        db_template['template_type'])

    template = get_template(db_template,
                            current_service,
                            show_recipient=True,
                            letter_preview_url=url_for(
                                'no_cookie.send_test_preview',
                                service_id=service_id,
                                template_id=template_id,
                                filetype='png',
                            ),
                            page_count=get_page_count_for_letter(
                                db_template, values=template_values),
                            email_reply_to=email_reply_to,
                            sms_sender=sms_sender)

    placeholders = fields_to_fill_in(template)

    try:
        current_placeholder = placeholders[step_index]
    except IndexError:
        if all_placeholders_in_session(placeholders):
            return get_notification_check_endpoint(service_id, template)
        return redirect(
            url_for(
                '.send_one_off',
                service_id=service_id,
                template_id=template_id,
            ))

    # if we're in a letter, we should show address block rather than "address line #" or "postcode"
    if template.template_type == 'letter':
        if step_index < len(address_lines_1_to_7_keys):
            return redirect(
                url_for(
                    '.send_one_off_letter_address',
                    service_id=service_id,
                    template_id=template_id,
                ))
        if current_placeholder in Columns(
                PostalAddress('').as_personalisation):
            return redirect(
                url_for(
                    request.endpoint,
                    service_id=service_id,
                    template_id=template_id,
                    step_index=step_index + 1,
                ))

    form = get_placeholder_form_instance(
        current_placeholder,
        dict_to_populate_from=get_normalised_placeholders_from_session(),
        template_type=template.template_type,
        allow_international_phone_numbers=current_service.has_permission(
            'international_sms'),
    )

    if form.validate_on_submit():
        # if it's the first input (phone/email), we store against `recipient` as well, for easier extraction.
        # Only if it's not a letter.
        # And only if we're not on the test route, since that will already have the user's own number set
        if (step_index == 0 and template.template_type != 'letter'):
            session['recipient'] = form.placeholder_value.data

        session['placeholders'][
            current_placeholder] = form.placeholder_value.data

        if all_placeholders_in_session(placeholders):
            return get_notification_check_endpoint(service_id, template)

        return redirect(
            url_for(
                request.endpoint,
                service_id=service_id,
                template_id=template_id,
                step_index=step_index + 1,
            ))

    back_link = get_back_link(service_id, template, step_index, placeholders)

    template.values = template_values
    template.values[current_placeholder] = None

    return render_template(
        'views/send-test.html',
        page_title=get_send_test_page_title(
            template.template_type,
            entering_recipient=not session['recipient'],
            name=template.name,
        ),
        template=template,
        form=form,
        skip_link=get_skip_link(step_index, template),
        back_link=back_link,
        link_to_upload=(request.endpoint == 'main.send_one_off_step'
                        and step_index == 0),
    )