Exemplo n.º 1
0
def send_complaint_to_vanotify(self, complaint_id: str,
                               complaint_template_name: str) -> None:
    from app.service.sender import send_notification_to_service_users
    complaint = fetch_complaint_by_id(complaint_id).one()

    try:
        send_notification_to_service_users(
            service_id=current_app.config['NOTIFY_SERVICE_ID'],
            template_id=current_app.config['EMAIL_COMPLAINT_TEMPLATE_ID'],
            personalisation={
                'notification_id':
                str(complaint.notification_id),
                'service_name':
                complaint.service.name,
                'template_name':
                complaint_template_name,
                'complaint_id':
                str(complaint.id),
                'complaint_type':
                complaint.complaint_type,
                'complaint_date':
                complaint.complaint_date.strftime(DATETIME_FORMAT)
            },
        )
        current_app.logger.info(
            f'Successfully sent complaint email to va-notify. notification_id: {complaint.notification_id}'
        )

    except Exception as e:
        current_app.logger.exception(
            f'Problem sending complaint to va-notify for notification {complaint.notification_id}: {e}'
        )
Exemplo n.º 2
0
def test_send_notification_to_service_users_sends_to_active_users_only(
        notify_db, notify_db_session, mocker):
    mocker.patch("app.service.sender.send_notification_to_queue")

    create_notify_service(notify_db, notify_db_session)

    first_active_user = create_user(email="*****@*****.**", state="active")
    second_active_user = create_user(email="*****@*****.**", state="active")
    pending_user = create_user(email="*****@*****.**", state="pending")
    service = create_sample_service(notify_db,
                                    notify_db_session,
                                    user=first_active_user)
    dao_add_user_to_service(service, second_active_user)
    dao_add_user_to_service(service, pending_user)
    template = create_template(service, template_type=EMAIL_TYPE)

    send_notification_to_service_users(service_id=service.id,
                                       template_id=template.id)
    notifications = Notification.query.all()
    notifications_recipients = [
        notification.to for notification in notifications
    ]

    assert Notification.query.count() == 2
    assert pending_user.email_address not in notifications_recipients
    assert first_active_user.email_address in notifications_recipients
    assert second_active_user.email_address in notifications_recipients
Exemplo n.º 3
0
def update_service(service_id):
    req_json = request.get_json()

    fetched_service = dao_fetch_service_by_id(service_id)
    # Capture the status change here as Marshmallow changes this later
    service_going_live = fetched_service.restricted and not req_json.get(
        'restricted', True)
    current_data = dict(service_schema.dump(fetched_service).data.items())
    current_data.update(request.get_json())

    service = service_schema.load(current_data).data

    if 'email_branding' in req_json:
        email_branding_id = req_json['email_branding']
        service.email_branding = None if not email_branding_id else EmailBranding.query.get(
            email_branding_id)
    if 'letter_branding' in req_json:
        letter_branding_id = req_json['letter_branding']
        service.letter_branding = None if not letter_branding_id else LetterBranding.query.get(
            letter_branding_id)
    dao_update_service(service)

    if service_going_live:
        send_notification_to_service_users(
            service_id=service_id,
            template_id=current_app.config['SERVICE_NOW_LIVE_TEMPLATE_ID'],
            personalisation={
                'service_name': current_data['name'],
                'message_limit': '{:,}'.format(current_data['message_limit'])
            },
            include_user_fields=['name'])

    return jsonify(data=service_schema.dump(fetched_service).data), 200
Exemplo n.º 4
0
def warn_about_daily_message_limit(service, messages_sent):
    nearing_daily_message_limit = messages_sent >= NEAR_DAILY_LIMIT_PERCENTAGE * service.message_limit
    over_daily_message_limit = messages_sent >= service.message_limit

    current_time = datetime.utcnow().isoformat()
    cache_expiration = int(timedelta(days=1).total_seconds())

    # Send a warning when reaching 80% of the daily limit
    if nearing_daily_message_limit:
        cache_key = near_daily_limit_cache_key(service.id)
        if not redis_store.get(cache_key):
            redis_store.set(cache_key, current_time, ex=cache_expiration)
            send_notification_to_service_users(
                service_id=service.id,
                template_id=current_app.config["NEAR_DAILY_LIMIT_TEMPLATE_ID"],
                personalisation={
                    "service_name":
                    service.name,
                    "contact_url":
                    f"{current_app.config['ADMIN_BASE_URL']}/contact",
                    "message_limit_en":
                    "{:,}".format(service.message_limit),
                    "message_limit_fr":
                    "{:,}".format(service.message_limit).replace(",", " "),
                },
                include_user_fields=["name"],
            )

    # Send a warning when reaching the daily message limit
    if over_daily_message_limit:
        cache_key = over_daily_limit_cache_key(service.id)
        if not redis_store.get(cache_key):
            redis_store.set(cache_key, current_time, ex=cache_expiration)
            send_notification_to_service_users(
                service_id=service.id,
                template_id=current_app.
                config["REACHED_DAILY_LIMIT_TEMPLATE_ID"],
                personalisation={
                    "service_name":
                    service.name,
                    "contact_url":
                    f"{current_app.config['ADMIN_BASE_URL']}/contact",
                    "message_limit_en":
                    "{:,}".format(service.message_limit),
                    "message_limit_fr":
                    "{:,}".format(service.message_limit).replace(",", " "),
                },
                include_user_fields=["name"],
            )

        current_app.logger.info(
            "service {} has been rate limited for daily use sent {} limit {}".
            format(service.id, int(messages_sent), service.message_limit))
        if service.restricted:
            raise TrialServiceTooManyRequestsError(service.message_limit)
        else:
            raise LiveServiceTooManyRequestsError(service.message_limit)
def test_send_notification_to_service_users_sends_to_queue(
        notify_db, notify_db_session, sample_service, mocker):
    send_mock = mocker.patch('app.service.sender.send_notification_to_queue')

    create_notify_service(notify_db, notify_db_session)
    template = create_template(sample_service, template_type=EMAIL_TYPE)
    send_notification_to_service_users(service_id=sample_service.id,
                                       template_id=template.id)

    assert send_mock.called
    assert send_mock.call_count == 1
Exemplo n.º 6
0
def _warn_service_users_about_message_limit_changed(service_id, data):
    send_notification_to_service_users(
        service_id=service_id,
        template_id=current_app.config["DAILY_LIMIT_UPDATED_TEMPLATE_ID"],
        personalisation={
            "service_name":
            data["name"],
            "message_limit_en":
            "{:,}".format(data["message_limit"]),
            "message_limit_fr":
            "{:,}".format(data["message_limit"]).replace(",", " "),
        },
        include_user_fields=["name"],
    )
Exemplo n.º 7
0
def update_service(service_id):
    req_json = request.get_json()
    fetched_service = dao_fetch_service_by_id(service_id)
    # Capture the status change here as Marshmallow changes this later
    service_going_live = fetched_service.restricted and not req_json.get('restricted', True)
    service_go_live_requested = 'go_live_user' in req_json
    current_data = dict(service_schema.dump(fetched_service).data.items())
    current_data.update(request.get_json())

    service = service_schema.load(current_data).data

    if 'email_branding' in req_json:
        email_branding_id = req_json['email_branding']
        service.email_branding = None if not email_branding_id else EmailBranding.query.get(email_branding_id)
    if 'letter_branding' in req_json:
        letter_branding_id = req_json['letter_branding']
        service.letter_branding = None if not letter_branding_id else LetterBranding.query.get(letter_branding_id)
    dao_update_service(service)

    if service_go_live_requested:
        template = dao_get_template_by_id(current_app.config['NOTIFY_ADMIN_OF_GO_LIVE_REQUEST_TEMPLATE_ID'])
        service_url = "{}/services/{}".format(current_app.config['ADMIN_BASE_URL'], str(service.id))
        saved_notification = persist_notification(
            template_id=template.id,
            template_version=template.version,
            recipient=get_or_build_support_email_address(),
            service=template.service,
            personalisation={
                'service_name': service.name,
                'service_dashboard_url': service_url
            },
            notification_type=EMAIL_TYPE,
            api_key_id=None,
            key_type=KEY_TYPE_NORMAL,
            reply_to_text=get_or_build_support_email_address()
        )
        send_notification_to_queue(saved_notification, research_mode=False, queue=QueueNames.NOTIFY)

    if service_going_live:
        send_notification_to_service_users(
            service_id=service_id,
            template_id=current_app.config['SERVICE_NOW_LIVE_TEMPLATE_ID'],
            personalisation={
                'service_name': current_data['name'],
                'message_limit': '{:,}'.format(current_data['message_limit'])
            },
            include_user_fields=['name']
        )

    return jsonify(data=service_schema.dump(fetched_service).data), 200
Exemplo n.º 8
0
def _warn_services_users_about_going_live(service_id, data):
    send_notification_to_service_users(
        service_id=service_id,
        template_id=current_app.config["SERVICE_NOW_LIVE_TEMPLATE_ID"],
        personalisation={
            "service_name":
            data["name"],
            "contact_us_url":
            f"{current_app.config['ADMIN_BASE_URL']}/contact",
            "signin_url":
            f"{current_app.config['ADMIN_BASE_URL']}/sign-in",
            "message_limit_en":
            "{:,}".format(data["message_limit"]),
            "message_limit_fr":
            "{:,}".format(data["message_limit"]).replace(",", " "),
        },
        include_user_fields=["name"],
    )
def test_send_notification_to_service_users_includes_user_fields_in_personalisation(
        notify_db, notify_db_session, sample_service, mocker):
    persist_mock = mocker.patch('app.service.sender.persist_notification')
    mocker.patch('app.service.sender.send_notification_to_queue')

    create_notify_service(notify_db, notify_db_session)
    user = sample_service.users[0]

    template = create_template(sample_service, template_type=EMAIL_TYPE)
    send_notification_to_service_users(
        service_id=sample_service.id,
        template_id=template.id,
        include_user_fields=['name', 'email_address', 'state'])

    persist_call = persist_mock.call_args_list[0][1]

    assert len(persist_mock.call_args_list) == 1
    assert persist_call['personalisation'] == {
        'name': user.name,
        'email_address': user.email_address,
        'state': user.state,
    }
def test_send_notification_to_service_users_persists_notifications_correctly(
        notify_db, notify_db_session, notification_type, sample_service,
        mocker):
    mocker.patch('app.service.sender.send_notification_to_queue')

    notify_service, _ = create_notify_service(notify_db, notify_db_session)
    user = sample_service.users[0]
    template = create_template(sample_service, template_type=notification_type)
    send_notification_to_service_users(service_id=sample_service.id,
                                       template_id=template.id)
    to = user.email_address if notification_type == EMAIL_TYPE else user.mobile_number

    notification = Notification.query.one()

    assert Notification.query.count() == 1
    assert notification.to == to
    assert str(
        notification.service_id) == current_app.config['NOTIFY_SERVICE_ID']
    assert notification.template.id == template.id
    assert notification.template.template_type == notification_type
    assert notification.notification_type == notification_type
    assert notification.reply_to_text == notify_service.get_default_reply_to_email_address(
    )
Exemplo n.º 11
0
def test_send_notification_to_service_users_includes_user_fields_in_personalisation(
        notify_db, notify_db_session, sample_user, mocker):
    persist_mock = mocker.patch("app.service.sender.persist_notification")
    mocker.patch("app.service.sender.send_notification_to_queue")

    create_notify_service(notify_db, notify_db_session)
    service = create_sample_service(notify_db,
                                    notify_db_session,
                                    user=sample_user)
    template = create_template(service, template_type=EMAIL_TYPE)
    send_notification_to_service_users(
        service_id=service.id,
        template_id=template.id,
        include_user_fields=["name", "email_address", "state"],
    )

    persist_call = persist_mock.call_args_list[0][1]

    assert len(persist_mock.call_args_list) == 1
    assert persist_call["personalisation"] == {
        "name": sample_user.name,
        "email_address": sample_user.email_address,
        "state": sample_user.state,
    }