def persist_notification(*,
                         template_id,
                         template_version,
                         recipient=None,
                         service,
                         personalisation,
                         notification_type,
                         api_key_id,
                         key_type,
                         created_at=None,
                         job_id=None,
                         job_row_number=None,
                         reference=None,
                         client_reference=None,
                         notification_id=None,
                         simulated=False,
                         created_by_id=None,
                         status=NOTIFICATION_CREATED,
                         reply_to_text=None,
                         billable_units=None,
                         postage=None,
                         template_postage=None,
                         recipient_identifier=None):
    notification_created_at = created_at or datetime.utcnow()
    if not notification_id:
        notification_id = uuid.uuid4()
    notification = Notification(id=notification_id,
                                template_id=template_id,
                                template_version=template_version,
                                to=recipient,
                                service_id=service.id,
                                service=service,
                                personalisation=personalisation,
                                notification_type=notification_type,
                                api_key_id=api_key_id,
                                key_type=key_type,
                                created_at=notification_created_at,
                                job_id=job_id,
                                job_row_number=job_row_number,
                                client_reference=client_reference,
                                reference=reference,
                                created_by_id=created_by_id,
                                status=status,
                                reply_to_text=reply_to_text,
                                billable_units=billable_units)
    if accept_recipient_identifiers_enabled() and recipient_identifier:
        _recipient_identifier = RecipientIdentifier(
            notification_id=notification_id,
            id_type=recipient_identifier['id_type'],
            id_value=recipient_identifier['id_value'])
        notification.recipient_identifiers.set(_recipient_identifier)

    if notification_type == SMS_TYPE and notification.to:
        formatted_recipient = validate_and_format_phone_number(
            recipient, international=True)
        recipient_info = get_international_phone_info(formatted_recipient)
        notification.normalised_to = formatted_recipient
        notification.international = recipient_info.international
        notification.phone_prefix = recipient_info.country_prefix
        notification.rate_multiplier = recipient_info.billable_units
    elif notification_type == EMAIL_TYPE and notification.to:
        notification.normalised_to = format_email_address(notification.to)
    elif notification_type == LETTER_TYPE:
        notification.postage = postage or template_postage

    # if simulated create a Notification model to return but do not persist the Notification to the dB
    if not simulated:
        dao_create_notification(notification)
        if key_type != KEY_TYPE_TEST:
            if redis_store.get(redis.daily_limit_cache_key(service.id)):
                redis_store.incr(redis.daily_limit_cache_key(service.id))

        current_app.logger.info("{} {} created at {}".format(
            notification_type, notification_id, notification_created_at))
    return notification
def test_accept_recipient_identifiers_flag(mocker, enabled_string,
                                           enabled_boolean):
    mocker.patch.dict(os.environ,
                      {'ACCEPT_RECIPIENT_IDENTIFIERS_ENABLED': enabled_string})
    assert accept_recipient_identifiers_enabled() == enabled_boolean
def post_notification(notification_type):
    try:
        request_json = request.get_json()
    except werkzeug.exceptions.BadRequest as e:
        raise BadRequestError(message="Error decoding arguments: {}".format(
            e.description),
                              status_code=400)

    if notification_type == EMAIL_TYPE:
        form = validate(request_json, post_email_request)
    elif notification_type == SMS_TYPE:
        form = validate(request_json, post_sms_request)
    elif notification_type == LETTER_TYPE:
        form = validate(request_json, post_letter_request)
    else:
        abort(404)

    check_service_has_permission(notification_type,
                                 authenticated_service.permissions)

    scheduled_for = form.get("scheduled_for", None)

    check_service_can_schedule_notification(authenticated_service.permissions,
                                            scheduled_for)

    check_rate_limiting(authenticated_service, api_user)

    template, template_with_content = validate_template(
        form['template_id'],
        form.get('personalisation', {}),
        authenticated_service,
        notification_type,
    )

    reply_to = get_reply_to_text(notification_type, form, template)

    if notification_type == LETTER_TYPE:
        notification = process_letter_notification(letter_data=form,
                                                   api_key=api_user,
                                                   template=template,
                                                   reply_to_text=reply_to)
    else:
        if 'email_address' in form or 'phone_number' in form:
            notification = process_sms_or_email_notification(
                form=form,
                notification_type=notification_type,
                api_key=api_user,
                template=template,
                service=authenticated_service,
                reply_to_text=reply_to)
        else:
            if accept_recipient_identifiers_enabled():
                notification = process_notification_with_recipient_identifier(
                    form=form,
                    notification_type=notification_type,
                    api_key=api_user,
                    template=template,
                    service=authenticated_service,
                    reply_to_text=reply_to)
            else:
                current_app.logger.debug(
                    "Sending a notification without contact information is not implemented."
                )
                return jsonify(result='error', message="Not Implemented"), 501

        template_with_content.values = notification.personalisation

    if notification_type == SMS_TYPE:
        create_resp_partial = functools.partial(
            create_post_sms_response_from_notification, from_number=reply_to)
    elif notification_type == EMAIL_TYPE:
        create_resp_partial = functools.partial(
            create_post_email_response_from_notification,
            subject=template_with_content.subject)
    elif notification_type == LETTER_TYPE:
        create_resp_partial = functools.partial(
            create_post_letter_response_from_notification,
            subject=template_with_content.subject,
        )

    resp = create_resp_partial(notification=notification,
                               content=str(template_with_content),
                               url_root=request.url_root,
                               scheduled_for=scheduled_for)
    return jsonify(resp), 201