Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conditional monitoring #57

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion api/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,17 @@
User = get_user_model()


@pytest.fixture()
def api_client():
return APIClient()


@pytest.fixture()
def auth_client():
user = User.objects.create(
email='[email protected]',
is_active=True
is_active=True,
auto_enable_monitoring=True,
)
token = Token.objects.create(user=user)
return APIClient(
Expand Down
24 changes: 20 additions & 4 deletions api/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
import json

import pytest
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.utils import timezone
from freezegun import freeze_time
from requests.exceptions import HTTPError
from rest_framework import status
from rest_framework.authtoken.models import Token

from company.constants import MonitoringStatusChoices
from company.models import ChangeRequest, Company
Expand Down Expand Up @@ -77,11 +79,17 @@ def test_api_with_bad_query(self, auth_client):
}
assert response.json() == expected_response

def test_query_duns_number_updates_local_db_and_monitoring_is_enabled(
@pytest.mark.parametrize('enable_monitoring,monitoring_status', [
(True, MonitoringStatusChoices.pending.name),
(False, MonitoringStatusChoices.not_enabled.name),
])
def test_query_duns_number_updates_local_db(
self,
auth_client,
api_client,
mocker,
company_list_api_response_json,
enable_monitoring,
monitoring_status
):
company_input_data = json.loads(company_list_api_response_json)
company_input_data['searchCandidates'].pop()
Expand All @@ -92,17 +100,25 @@ def test_query_duns_number_updates_local_db_and_monitoring_is_enabled(
mock_api_request.return_value.json.return_value = company_input_data

assert Company.objects.count() == 0
response = auth_client.post(

user = get_user_model().objects.create(
email='[email protected]',
is_active=True,
auto_enable_monitoring=enable_monitoring,
)
token = Token.objects.create(user=user)
response = api_client.post(
reverse('api:company-search'),
{'duns_number': company_input_data['searchCandidates'][0]['organization']['duns']},
HTTP_AUTHORIZATION=f'Token {token.key}'
)

assert Company.objects.count() == 1
assert response.status_code == 200
company = Company.objects.first()
result_data = response.json()
assert company.duns_number == result_data['results'][0]['duns_number']
assert company.monitoring_status == MonitoringStatusChoices.pending.name
assert company.monitoring_status == monitoring_status


class TestCompanyUpdateView:
Expand Down
5 changes: 4 additions & 1 deletion api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ def post(self, request):
serialiser.is_valid(raise_exception=True)

try:
data = company_list_search(serialiser.data, update_local=True)
data = company_list_search(
serialiser.data,
update_local=True,
enable_monitoring=request.user.auto_enable_monitoring)
except HTTPError as ex:
error_detail = ex.response.json()['error']
return Response(error_detail, status=ex.response.status_code)
Expand Down
6 changes: 3 additions & 3 deletions dnb_direct_plus/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@

from requests.exceptions import HTTPError

from dnb_direct_plus.tasks import update_company_and_enable_monitoring
from dnb_direct_plus.tasks import update_company_from_api_data


DNB_COMPANY_SEARCH_ENDPOINT = '/v1/search/companyList'


def company_list_search(query, update_local=False):
def company_list_search(query, update_local=False, enable_monitoring=False):
"""
Perform a DNB Direct+ company search list api call

Expand Down Expand Up @@ -39,7 +39,7 @@ def company_list_search(query, update_local=False):

# update the local company record and enable monitoring
if update_local and 'duns_number' in query and len(results) == 1:
update_company_and_enable_monitoring(response_data['searchCandidates'][0])
update_company_from_api_data(response_data['searchCandidates'][0], enable_monitoring=enable_monitoring)

return {
'total_matches': response_data.get('candidatesMatchedQuantity', 0),
Expand Down
10 changes: 7 additions & 3 deletions dnb_direct_plus/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,12 @@


@shared_task
def update_company_and_enable_monitoring(api_data):
"""Create or update the company entry and set monitoring_status to 'pending' if not already enabled"""
def update_company_from_api_data(api_data, enable_monitoring=False):
"""
Create or update the company entry from DNB API data.
if `enable_monitoring` is `True` then set `monitoring_status` to 'pending',
if monitoring has not already been enabled for this company
"""

duns_number = api_data["organization"]["duns"]

Expand All @@ -23,4 +27,4 @@ def update_company_and_enable_monitoring(api_data):
except Company.DoesNotExist:
company = Company()

update_company_from_source(company, api_data, timezone.now(), enable_monitoring=True)
update_company_from_source(company, api_data, timezone.now(), enable_monitoring=enable_monitoring)
19 changes: 14 additions & 5 deletions dnb_direct_plus/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
from company.models import Company


@pytest.mark.django_db
pytestmark = pytest.mark.django_db


def test_company_list_search(mocker, company_list_api_response_json):

company_input_data = json.loads(company_list_api_response_json)
Expand Down Expand Up @@ -37,8 +39,13 @@ def test_company_list_search(mocker, company_list_api_response_json):
assert extract_company_data(input_data) == expected


@pytest.mark.django_db
def test_company_list_search_detail_query_company_data_is_saved(mocker, company_list_api_response_json):
@pytest.mark.parametrize('enable_monitoring,monitoring_status', [
(True, MonitoringStatusChoices.pending.name),
(False, MonitoringStatusChoices.not_enabled.name),
])
def test_company_list_search_detail_query_company_data_is_saved(mocker,
company_list_api_response_json,
enable_monitoring, monitoring_status):

company_input_data = json.loads(company_list_api_response_json)

Expand All @@ -51,11 +58,13 @@ def test_company_list_search_detail_query_company_data_is_saved(mocker, company_

assert Company.objects.count() == 0

output = company_list_search({'duns_number': 'hello world',}, update_local=True)
output = company_list_search(
{'duns_number': 'hello world',}, update_local=True, enable_monitoring=enable_monitoring)

assert Company.objects.count() == 1

company = Company.objects.first()

assert company.duns_number == output['results'][0]['duns_number']
assert company.monitoring_status == MonitoringStatusChoices.pending.name

assert company.monitoring_status == monitoring_status
4 changes: 1 addition & 3 deletions dnb_direct_plus/tests/test_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@
from ..models import MonitoringFileRecord


pytestmark = [
pytest.mark.django_db
]
pytestmark = pytest.mark.django_db


class TestProcessMonitoringData:
Expand Down
18 changes: 18 additions & 0 deletions user/migrations/0002_user_monitor_companies.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 2.2.10 on 2020-03-27 15:19

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('user', '0001_squashed_0002_auto_20190417_0813'),
]

operations = [
migrations.AddField(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should their be a data migration that follows this which ensures that monitoring is enabled for the Data Hub user?

model_name='user',
name='auto_enable_monitoring',
field=models.BooleanField(default=False, help_text='Automatically register companies for live updates when queried via the API; NOTE: this option should only be enabled for data-hub.', verbose_name='auto enable monitoring'),
),
]
6 changes: 6 additions & 0 deletions user/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ class User(AbstractUser):
username = None

email = models.EmailField(_('email address'), unique=True)
auto_enable_monitoring = models.BooleanField(
_('auto enable company monitoring'),
help_text=_('Automatically register companies for live updates when queried via the API; '
'NOTE: this option should only be enabled for data-hub.'),
default=False,
)

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
Expand Down