Skip to content

Commit

Permalink
Merge pull request #1171 from Amsterdam/powerbrowser
Browse files Browse the repository at this point in the history
Powerbrowser
  • Loading branch information
remyvdwereld authored Nov 13, 2023
2 parents 809f5cc + 0485181 commit 28202c5
Show file tree
Hide file tree
Showing 6 changed files with 136 additions and 4 deletions.
6 changes: 4 additions & 2 deletions app/apps/health/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ def ready(self):
OpenZaakZaken,
OpenZaakZakenAlfresco,
OpenZaakZakenCatalogus,
PowerBrowser,
Toeristischeverhuur,
)

Expand All @@ -27,10 +28,11 @@ def ready(self):
plugin_dir.register(BRPServiceCheck)
plugin_dir.register(Belastingdienst)
plugin_dir.register(CeleryExecuteTask)
plugin_dir.register(DecosJoinCheck)
plugin_dir.register(KeycloakCheck)
plugin_dir.register(Toeristischeverhuur)
plugin_dir.register(OpenZaakZaken)
plugin_dir.register(OpenZaakZakenAlfresco)
plugin_dir.register(OpenZaakZakenCatalogus)
plugin_dir.register(PowerBrowser)
plugin_dir.register(Toeristischeverhuur)
# plugin_dir.register(VakantieVerhuurRegistratieCheck)
plugin_dir.register(DecosJoinCheck)
16 changes: 16 additions & 0 deletions app/apps/health/health_checks.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import logging

import requests
from apps.permits.api_queries_powerbrowser import PowerbrowserRequest
from config.celery import debug_task
from django.conf import settings
from health_check.backends import BaseHealthCheckBackend
Expand Down Expand Up @@ -274,3 +275,18 @@ def check_status(self):
logger.info(
"Connection established. Toeristischeverhuur.nl API connection is healthy."
)


class PowerBrowser(BaseHealthCheckBackend):
"""
Tests an authenticated request to PowerBrowser for B&B permits
"""

def check_status(self):
try:
response = PowerbrowserRequest().get_vergunningen_with_bag_id(
settings.BAG_ID_AMSTEL_1
)
assert response, "Could not reach PowerBrowser"
except Exception as e:
self.add_error(ServiceUnavailable("Failed"), e)
57 changes: 57 additions & 0 deletions app/apps/permits/api_queries_powerbrowser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import logging
import os

import requests
from django.conf import settings

logger = logging.getLogger(__name__)


class PowerbrowserRequest:
def __init__(self):
self.base_url = settings.POWERBROWSER_BASE_URL
self.api_key = settings.POWERBROWSER_API_KEY

def get_vergunningen_with_bag_id(self, bag_id):
bearer_token = self._get_powerbrowser_bearer_token()
vergunningen = self._get_powerbrowser_vergunningen(bearer_token, bag_id)
self._logout_from_powerbrowser(bearer_token)
return vergunningen

def _get_powerbrowser_bearer_token(self):
json = {"apiKey": self.api_key}
url = os.path.join(self.base_url, "token")
response = self._perform_api_call(url, json=json)
bearer_token = response.text
return bearer_token

def _perform_api_call(self, url, json=None, bearer_token=None, method="post"):
headers = {"Authorization": f"Bearer {bearer_token}"} if bearer_token else {}
response = getattr(requests, method)(
url=url,
json=json,
headers=headers,
timeout=(2, 5),
)
logger.info(f"Called url {response.url} with method {method.upper()}")
response.raise_for_status()
return response

def _logout_from_powerbrowser(self, bearer_token):
url = os.path.join(self.base_url, "token")
self._perform_api_call(url, bearer_token=bearer_token, method="delete")

def _get_powerbrowser_vergunningen(self, bearer_token, bag_id):
json = {
"reportFileName": "D:\\Genetics\\PowerForms\\Overzichten\\Wonen\\Zakentop.gov",
"parameters": [
{
"name": "BAG_ID",
"type": "string",
"value": {"stringValue": f"{bag_id}"},
}
],
}
url = os.path.join(self.base_url, "report/runsavedreport")
response = self._perform_api_call(url, json=json, bearer_token=bearer_token)
return response.json()
37 changes: 35 additions & 2 deletions app/apps/permits/mixins.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
import logging
from datetime import datetime

from apps.permits.api_queries_decos_join import DecosJoinRequest
from apps.permits.serializers import DecosSerializer
from apps.permits.api_queries_powerbrowser import PowerbrowserRequest
from apps.permits.serializers import DecosSerializer, PowerbrowserSerializer
from apps.users.permissions import rest_permission_classes_for_ton
from drf_spectacular.utils import extend_schema
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response

logger = logging.getLogger(__name__)


class PermitDetailsMixin:
@extend_schema(
description="Get permit details based on bag id",
description="Get Decos permit details based on bag id",
responses={200: DecosSerializer()},
)
@action(
Expand All @@ -28,3 +33,31 @@ def permit_details(self, request, bag_id, dt=None):
if serializer.is_valid():
return Response(serializer.data)
return Response(serializer.initial_data)

@extend_schema(
description="Get PowerBrowser permit details based on bag id",
responses={200: PowerbrowserSerializer()},
)
@action(
detail=True,
url_name="permit details PowerBrowser",
url_path="permits-powerbrowser",
permission_classes=rest_permission_classes_for_ton(),
)
def get_bb_permit_details(self, request, bag_id):
try:
response = PowerbrowserRequest().get_vergunningen_with_bag_id(bag_id)
serializer = PowerbrowserSerializer(data=response, many=True)
if serializer.is_valid():
deserialized_data = serializer.validated_data
return Response(deserialized_data, status=status.HTTP_200_OK)
else:
return Response(
{"Failed to serialize permits": serializer.errors},
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
except Exception as e:
logger.error(
f"Failed to fetch permits Powerbrowser for bag id {bag_id}: {e}"
)
return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST)
13 changes: 13 additions & 0 deletions app/apps/permits/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,16 @@ class PermitSerializer(serializers.Serializer):
class DecosSerializer(serializers.Serializer):
permits = PermitSerializer(many=True)
decos_folders = serializers.DictField(allow_null=True)


class PowerbrowserSerializer(serializers.Serializer):
baG_ID = serializers.CharField()
product = serializers.CharField()
kenmerk = serializers.CharField(allow_null=True)
muT_DAT = serializers.DateTimeField()
status = serializers.CharField()
resultaat = serializers.CharField(allow_null=True)
startdatum = serializers.DateTimeField()
einddatum = serializers.DateTimeField(allow_null=True)
vergunninghouder = serializers.CharField(allow_null=True)
initator = serializers.CharField(allow_null=True)
11 changes: 11 additions & 0 deletions app/config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,11 @@
"BAG_API_VERBLIJFSOBJECT_URL",
"https://api.data.amsterdam.nl/bag/v1.1/verblijfsobject/",
)
# Bag_id of Amstel 1 for testing purposes.
BAG_ID_AMSTEL_1 = os.getenv(
"BAG_ID_AMSTEL_1",
"0363010012143319",
)
BELASTING_API_URL = os.getenv(
"BELASTING_API_URL",
"https://api-acc.belastingen.centric.eu/bel/inn/afne/vora/v1/vorderingenidentificatienummer/",
Expand Down Expand Up @@ -434,6 +439,12 @@
DECOS_JOIN_BOOK_KNOWN_BAG_OBJECTS = "90642DCCC2DB46469657C3D0DF0B1ED7"
USE_DECOS_MOCK_DATA = os.getenv("USE_DECOS_MOCK_DATA", False) == "True"

# Powerbrowser for permits
POWERBROWSER_BASE_URL = os.getenv(
"POWERBROWSER_BASE_URL", "https://accgemeenteamsterdamvth.moverheid.nl/api/"
)
POWERBROWSER_API_KEY = os.getenv("POWERBROWSER_API_KEY")

# TOP Connection settings
SECRET_KEY_AZA_TOP = os.getenv("SECRET_KEY_AZA_TOP")
TOP_API_URL = os.getenv("TOP_API_URL")
Expand Down

0 comments on commit 28202c5

Please sign in to comment.