def view_letter_notification_as_preview(service_id, notification_id, filetype):

    if filetype not in ('pdf', 'png'):
        abort(404)
    notification = notification_api_client.get_notification(
        service_id, str(notification_id))
    try:
        if notification['status'] == "validation-failed":
            preview = notification_api_client.get_notification_letter_preview_with_overlay(
                service_id,
                notification_id,
                filetype,
                page=request.args.get('page'))
        else:
            preview = notification_api_client.get_notification_letter_preview(
                service_id,
                notification_id,
                filetype,
                page=request.args.get('page'))

        display_file = base64.b64decode(preview['content'])
    except APIError:
        display_file = get_preview_error_image()

    return display_file
def get_user_number(service_id, notification_id):
    try:
        user_number = service_api_client.get_inbound_sms_by_id(service_id, notification_id)['user_number']
    except HTTPError as e:
        if e.status_code != 404:
            raise
        user_number = notification_api_client.get_notification(service_id, notification_id)['to']
    return format_phone_number_human_readable(user_number)
def get_service_verify_reply_to_address_partials(service_id, notification_id):
    form = ServiceReplyToEmailForm()
    first_email_address = current_service.count_email_reply_to_addresses == 0
    notification = notification_api_client.get_notification(
        current_app.config["NOTIFY_SERVICE_ID"], notification_id)
    replace = request.args.get('replace', False)
    replace = False if replace == "False" else replace
    existing_is_default = False
    if replace:
        existing = current_service.get_email_reply_to_address(replace)
        existing_is_default = existing['is_default']
    verification_status = "pending"
    is_default = True if (request.args.get('is_default', False)
                          == "True") else False
    if notification["status"] in DELIVERED_STATUSES:
        verification_status = "success"
        if notification["to"] not in [
                i["email_address"]
                for i in current_service.email_reply_to_addresses
        ]:
            if replace:
                service_api_client.update_reply_to_email_address(
                    current_service.id,
                    replace,
                    email_address=notification["to"],
                    is_default=is_default)
            else:
                service_api_client.add_reply_to_email_address(
                    current_service.id,
                    email_address=notification["to"],
                    is_default=is_default)
    seconds_since_sending = (
        utc_string_to_aware_gmt_datetime(datetime.utcnow().isoformat()) -
        utc_string_to_aware_gmt_datetime(notification['created_at'])).seconds
    if notification["status"] in FAILURE_STATUSES or (
            notification["status"] in SENDING_STATUSES
            and seconds_since_sending >
            current_app.config['REPLY_TO_EMAIL_ADDRESS_VALIDATION_TIMEOUT']):
        verification_status = "failure"
        form.email_address.data = notification['to']
        form.is_default.data = is_default
    return {
        'status':
        render_template(
            'views/service-settings/email-reply-to/_verify-updates.html',
            reply_to_email_address=notification["to"],
            service_id=current_service.id,
            notification_id=notification_id,
            verification_status=verification_status,
            is_default=is_default,
            existing_is_default=existing_is_default,
            form=form,
            first_email_address=first_email_address,
            replace=replace),
        'stop':
        0 if verification_status == "pending" else 1
    }
Example #4
0
def view_notification(service_id, notification_id):
    notification = notification_api_client.get_notification(
        service_id, str(notification_id))
    notification['template'].update(
        {'reply_to_text': notification['reply_to_text']})

    if notification['template']['is_precompiled_letter']:
        file_contents = view_letter_notification_as_preview(
            service_id, notification_id, "pdf")
        page_count = pdf_page_count(io.BytesIO(file_contents))
    else:
        page_count = get_page_count_for_letter(notification['template'])

    template = get_template(
        notification['template'],
        current_service,
        letter_preview_url=url_for(
            '.view_letter_notification_as_preview',
            service_id=service_id,
            notification_id=notification_id,
            filetype='png',
        ),
        page_count=page_count,
        show_recipient=True,
        redact_missing_personalisation=True,
    )
    template.values = get_all_personalisation_from_notification(notification)
    if notification['job']:
        job = job_api_client.get_job(service_id,
                                     notification['job']['id'])['data']
    else:
        job = None

    return render_template(
        'views/notifications/notification.html',
        finished=(notification['status']
                  in (DELIVERED_STATUSES + FAILURE_STATUSES)),
        uploaded_file_name='Report',
        template=template,
        job=job,
        updates_url=url_for(".view_notification_updates",
                            service_id=service_id,
                            notification_id=notification['id'],
                            status=request.args.get('status'),
                            help=get_help_argument()),
        partials=get_single_notification_partials(notification),
        created_by=notification.get('created_by'),
        created_at=notification['created_at'],
        help=get_help_argument(),
        estimated_letter_delivery_date=get_letter_timings(
            notification['created_at']).earliest_delivery,
        notification_id=notification['id'],
        can_receive_inbound=(current_service.has_permission('inbound_sms')),
        is_precompiled_letter=notification['template']
        ['is_precompiled_letter'])
Example #5
0
def get_user_number(service_id, notification_id):
    try:
        number = service_api_client.get_inbound_sms_by_id(
            service_id, notification_id)['user_number']
    except HTTPError:
        notification = notification_api_client.get_notification(
            service_id, notification_id)

        number = notification['normalised_to']

        # For old records normalised_to may be empty or it may be stored in the
        # old format (without storing the leading plus sign). If this is the
        # case, use the to field instead and create the E.164 format on the fly.
        if not number or not number.startswith('+'):
            number = notification['to']

    return try_validate_and_format_phone_number(number)
def view_letter_notification_as_preview(service_id, notification_id, filetype):

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

    notification = notification_api_client.get_notification(service_id, notification_id)
    notification['template'].update({'reply_to_text': notification['reply_to_text']})

    template = get_template(
        notification['template'],
        current_service,
        letter_preview_url=url_for(
            '.view_letter_notification_as_preview',
            service_id=service_id,
            notification_id=notification_id,
            filetype='png',
        ),
    )

    template.values = notification['personalisation']

    return TemplatePreview.from_utils_template(template, filetype, page=request.args.get('page'))
Example #7
0
def get_user_number(service_id, notification_id):
    try:
        number_e164 = service_api_client.get_inbound_sms_by_id(
            service_id, notification_id)['user_number']
    except HTTPError:
        notification = notification_api_client.get_notification(
            service_id, notification_id)

        number_e164 = notification['normalised_to']

        # For old records normalised_to may be empty or it may be stored in the
        # old format (without storing the leading plus sign). If this is the
        # case, use the to field instead and create the E.164 format on the fly.
        if not number_e164 or not number_e164.startswith('+'):
            try:
                number_e164 = validate_and_format_phone_number_and_allow_international(
                    notification['to'])
            except Exception:
                return notification['to']

    number = e164_to_phone_number(number_e164)

    return format_phone_number_human_readable(number)
Example #8
0
def view_notification_updates(service_id, notification_id):
    return jsonify(**get_single_notification_partials(
        notification_api_client.get_notification(service_id, notification_id)))
def view_notification(service_id, notification_id):
    notification = notification_api_client.get_notification(
        service_id, str(notification_id))
    notification['template'].update(
        {'reply_to_text': notification['reply_to_text']})

    personalisation = get_all_personalisation_from_notification(notification)

    if notification['template']['is_precompiled_letter']:
        try:
            file_contents = view_letter_notification_as_preview(
                service_id, notification_id, "pdf")
            page_count = pdf_page_count(io.BytesIO(file_contents))
        except PdfReadError:
            return render_template(
                'views/notifications/invalid_precompiled_letter.html',
                created_at=notification['created_at'])
    else:
        page_count = get_page_count_for_letter(notification['template'],
                                               values=personalisation)

    if notification.get('postage'):
        notification['template']['postage'] = notification['postage']
    template = get_template(
        notification['template'],
        current_service,
        letter_preview_url=url_for(
            '.view_letter_notification_as_preview',
            service_id=service_id,
            notification_id=notification_id,
            filetype='png',
        ),
        page_count=page_count,
        show_recipient=True,
        redact_missing_personalisation=True,
    )
    template.values = personalisation
    if notification['job']:
        job = job_api_client.get_job(service_id,
                                     notification['job']['id'])['data']
    else:
        job = None

    letter_print_day = get_letter_printing_statement(
        notification['status'], notification['created_at'])

    notification_created = parser.parse(
        notification['created_at']).replace(tzinfo=None)

    show_cancel_button = notification['notification_type'] == 'letter' and \
        letter_can_be_cancelled(notification['status'], notification_created)

    if get_help_argument() or request.args.get('help') == '0':
        # help=0 is set when you’ve just sent a notification. We
        # only want to show the back link when you’ve navigated to a
        # notification, not when you’ve just sent it.
        back_link = None
    elif request.args.get('from_job'):
        back_link = url_for(
            'main.view_job',
            service_id=current_service.id,
            job_id=request.args.get('from_job'),
        )
    else:
        back_link = url_for(
            'main.view_notifications',
            service_id=current_service.id,
            message_type=template.template_type,
            status='sending,delivered,failed',
        )

    return render_template(
        'views/notifications/notification.html',
        finished=(notification['status']
                  in (DELIVERED_STATUSES + FAILURE_STATUSES)),
        notification_status=notification['status'],
        uploaded_file_name='Report',
        template=template,
        job=job,
        updates_url=url_for(".view_notification_updates",
                            service_id=service_id,
                            notification_id=notification['id'],
                            status=request.args.get('status'),
                            help=get_help_argument()),
        partials=get_single_notification_partials(notification),
        created_by=notification.get('created_by'),
        created_at=notification['created_at'],
        updated_at=notification['updated_at'],
        help=get_help_argument(),
        estimated_letter_delivery_date=get_letter_timings(
            notification['created_at'],
            postage=notification['postage']).earliest_delivery,
        notification_id=notification['id'],
        postage=notification['postage'],
        can_receive_inbound=(current_service.has_permission('inbound_sms')),
        is_precompiled_letter=notification['template']
        ['is_precompiled_letter'],
        letter_print_day=letter_print_day,
        show_cancel_button=show_cancel_button,
        sent_with_test_key=(notification.get('key_type') == KEY_TYPE_TEST),
        back_link=back_link,
    )
def view_notification(service_id, notification_id):
    notification = notification_api_client.get_notification(service_id, str(notification_id))
    notification["template"].update({"reply_to_text": notification["reply_to_text"]})

    personalisation = get_all_personalisation_from_notification(notification)

    if notification["template"]["is_precompiled_letter"]:
        try:
            file_contents = view_letter_notification_as_preview(service_id, notification_id, "pdf")
            page_count = pdf_page_count(io.BytesIO(file_contents))
        except PdfReadError:
            return render_template(
                "views/notifications/invalid_precompiled_letter.html",
                created_at=notification["created_at"],
            )
    else:
        page_count = get_page_count_for_letter(notification["template"], values=personalisation)

    if notification.get("postage"):
        notification["template"]["postage"] = notification["postage"]
    template = get_template(
        notification["template"],
        current_service,
        letter_preview_url=url_for(
            ".view_letter_notification_as_preview",
            service_id=service_id,
            notification_id=notification_id,
            filetype="png",
        ),
        page_count=page_count,
        show_recipient=True,
        redact_missing_personalisation=True,
    )
    template.values = personalisation
    if notification["job"]:
        job = job_api_client.get_job(service_id, notification["job"]["id"])["data"]
    else:
        job = None

    letter_print_day = get_letter_printing_statement(notification["status"], notification["created_at"])

    notification_created = parser.parse(notification["created_at"]).replace(tzinfo=None)

    show_cancel_button = notification["notification_type"] == "letter" and letter_can_be_cancelled(
        notification["status"], notification_created
    )

    if get_help_argument() or request.args.get("help") == "0":
        # help=0 is set when you’ve just sent a notification. We
        # only want to show the back link when you’ve navigated to a
        # notification, not when you’ve just sent it.
        back_link = None
    elif request.args.get("from_job"):
        back_link = url_for(
            "main.view_job",
            service_id=current_service.id,
            job_id=request.args.get("from_job"),
        )
    else:
        back_link = url_for(
            "main.view_notifications",
            service_id=current_service.id,
            message_type=template.template_type,
            status="sending,delivered,failed",
        )

    return render_template(
        "views/notifications/notification.html",
        finished=(notification["status"] in (DELIVERED_STATUSES + FAILURE_STATUSES)),
        notification_status=notification["status"],
        uploaded_file_name="Report",
        template=template,
        job=job,
        updates_url=url_for(
            ".view_notification_updates",
            service_id=service_id,
            notification_id=notification["id"],
            status=request.args.get("status"),
            help=get_help_argument(),
        ),
        partials=get_single_notification_partials(notification),
        created_by=notification.get("created_by"),
        created_at=notification["created_at"],
        updated_at=notification["updated_at"],
        help=get_help_argument(),
        estimated_letter_delivery_date=get_letter_timings(
            notification["created_at"], postage=notification["postage"]
        ).earliest_delivery,
        notification_id=notification["id"],
        postage=notification["postage"],
        can_receive_inbound=(current_service.has_permission("inbound_sms")),
        is_precompiled_letter=notification["template"]["is_precompiled_letter"],
        letter_print_day=letter_print_day,
        show_cancel_button=show_cancel_button,
        sent_with_test_key=(notification.get("key_type") == KEY_TYPE_TEST),
        back_link=back_link,
        just_sent=request.args.get("just_sent"),
        attachments=get_attachments(notification, "attach").values(),
    )