Skip to content

Commit

Permalink
Merge pull request #952 from maykinmedia/fix/2014-retrieve-rsin
Browse files Browse the repository at this point in the history
🐛 [#2014] Fix retrieval of RSIN for KVK after login
  • Loading branch information
stevenbal authored Jan 15, 2024
2 parents ebdd91f + 587b6dc commit 940dc33
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 40 deletions.
17 changes: 8 additions & 9 deletions src/open_inwoner/kvk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ def _request(self, endpoint: str, params: dict) -> dict:
def search_endpoint(self):
return self._urljoin(self.config.api_root, "zoeken")

@cached_property
def basisprofielen_endpoint(self):
return self._urljoin(self.config.api_root, "basisprofielen")

def search(self, **kwargs) -> dict:
"""
Generic call to the 'Zoeken' endpoint of the KvK API
Expand Down Expand Up @@ -107,18 +111,13 @@ def get_all_company_branches(self, kvk: str, **kwargs) -> list[Optional[dict]]:
return self.search(**kwargs).get("resultaten", [])

def retrieve_rsin_with_kvk(self, kvk, **kwargs) -> Optional[str]:
company_data = self.get_company_headquarters(kvk, **kwargs)
basisprofiel = self._request(
f"{self.basisprofielen_endpoint}/{kvk}", params=kwargs
)

if not company_data:
if not basisprofiel:
return None

basisprofiel_link = None
for link in company_data["links"]:
if link["rel"] == "basisprofiel":
basisprofiel_link = link["href"]
break

basisprofiel = self._request(basisprofiel_link, {})
try:
rsin = basisprofiel["_embedded"]["eigenaar"]["rsin"]
except KeyError:
Expand Down
26 changes: 13 additions & 13 deletions src/open_inwoner/kvk/signals.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,36 @@
import logging

from django.db.models.signals import pre_save
from django.contrib.auth.signals import user_logged_in
from django.dispatch import receiver
from django.utils.translation import gettext as _

from open_inwoner.accounts.choices import LoginTypeChoices
from open_inwoner.accounts.models import User
from open_inwoner.utils.logentry import system_action

from .client import KvKClient

logger = logging.getLogger(__name__)


@receiver(pre_save, sender=User)
def on_kvk_change(instance, **kwargs):
@receiver(user_logged_in)
def on_kvk_change(sender, user, request, *args, **kwargs):
if (
instance.kvk
and instance.is_prepopulated is False
and instance.login_type == LoginTypeChoices.eherkenning
and not instance.rsin
user.kvk
and user.is_prepopulated is False
and user.login_type == LoginTypeChoices.eherkenning
and not user.rsin
):
system_action(
_("Retrieving data from KvK API based on KVK number"),
content_object=instance,
content_object=user,
)

client = KvKClient()
rsin = client.retrieve_rsin_with_kvk(instance.kvk)
rsin = client.retrieve_rsin_with_kvk(user.kvk)

if rsin:
system_action(_("data was retrieved from KvK API"), content_object=instance)
system_action(_("data was retrieved from KvK API"), content_object=user)

instance.rsin = rsin
instance.is_prepopulated = True
user.rsin = rsin
user.is_prepopulated = True
user.save()
34 changes: 16 additions & 18 deletions src/open_inwoner/kvk/tests/test_signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,15 @@ def setUpTestData(cls):
def test_signal_updates_users_data_when_logged_in_via_eherkenning(self, m):
m.get(
self.kvk_client._build_url(
self.kvk_client.search_endpoint, {"kvkNummer": "69599084"}
f"{self.kvk_client.basisprofielen_endpoint}/69599084",
),
json=mocks.simple,
)
m.get(
mocks.simple["resultaten"][0]["links"][0]["href"],
json=mocks.basisprofiel_detail,
)

user = UserModel.eherkenning_objects.eherkenning_create("69599084")

self.client.force_login(user=user)

user.refresh_from_db()

self.assertEqual(user.rsin, "857587973")
Expand All @@ -65,7 +63,7 @@ def test_user_is_not_updated_when_not_logged_in_via_eherkenning(self, m):
def test_empty_response_from_kvk(self, m):
m.get(
self.kvk_client._build_url(
self.kvk_client.search_endpoint, {"kvkNummer": "69599084"}
f"{self.kvk_client.basisprofielen_endpoint}/69599084",
),
json=mocks.empty,
)
Expand All @@ -80,7 +78,7 @@ def test_empty_response_from_kvk(self, m):
def test_user_is_not_updated_when_http_404(self, m):
m.get(
self.kvk_client._build_url(
self.kvk_client.search_endpoint, {"kvkNummer": "69599084"}
f"{self.kvk_client.basisprofielen_endpoint}/69599084",
),
status_code=404,
)
Expand All @@ -94,7 +92,7 @@ def test_user_is_not_updated_when_http_404(self, m):
def test_user_is_not_updated_when_http_500(self, m):
m.get(
self.kvk_client._build_url(
self.kvk_client.search_endpoint, {"kvkNummer": "69599084"}
f"{self.kvk_client.basisprofielen_endpoint}/69599084",
),
status_code=500,
)
Expand All @@ -121,12 +119,8 @@ def setUpTestData(cls):
def test_signal_updates_logging(self, m):
m.get(
self.kvk_client._build_url(
self.kvk_client.search_endpoint, {"kvkNummer": "69599084"}
f"{self.kvk_client.basisprofielen_endpoint}/69599084",
),
json=mocks.simple,
)
m.get(
mocks.simple["resultaten"][0]["links"][0]["href"],
json=mocks.basisprofiel_detail,
)

Expand All @@ -136,7 +130,9 @@ def test_signal_updates_logging(self, m):
user.kvk = "69599084"
user.save()

log_entry = TimelineLog.objects.filter(object_id=user.id)[1]
self.client.force_login(user=user)

log_entry = TimelineLog.objects.filter(object_id=user.id)[2]

self.assertEquals(
log_entry.timestamp.strftime("%m/%d/%Y, %H:%M:%S"), "10/18/2021, 13:00:00"
Expand All @@ -156,18 +152,20 @@ def test_signal_updates_logging(self, m):
def test_single_entry_is_logged_when_there_is_an_error(self, m):
m.get(
self.kvk_client._build_url(
self.kvk_client.search_endpoint, {"kvkNummer": "69599084"}
f"{self.kvk_client.basisprofielen_endpoint}/69599084",
),
json=mocks.simple,
status_code=500,
)
m.get(mocks.simple["resultaten"][0]["links"][0]["href"], status_code=500)

user = UserFactory(
first_name="", last_name="", login_type=LoginTypeChoices.eherkenning
)
user.kvk = "69599084"
user.save()

self.client.force_login(user=user)

log_entries = TimelineLog.objects.count()

self.assertEqual(log_entries, 1)
# Login message + message to attempt KvK data retrieval
self.assertEqual(log_entries, 2)

0 comments on commit 940dc33

Please sign in to comment.