Skip to content

Commit

Permalink
✨ Allow object relation to bijdrage zaken based on label filtering
Browse files Browse the repository at this point in the history
  • Loading branch information
damm89 committed Oct 16, 2024
1 parent 39023c3 commit 6ed960b
Show file tree
Hide file tree
Showing 4 changed files with 172 additions and 41 deletions.
42 changes: 38 additions & 4 deletions src/bptl/work_units/zgw/objects/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@

from djangorestframework_camel_case.settings import api_settings
from djangorestframework_camel_case.util import camelize
from zgw_consumers.concurrent import parallel

from bptl.core.utils import fetch_next_url_pagination
from bptl.tasks.base import check_variable
from bptl.tasks.models import BaseTask
from bptl.work_units.zgw.utils import get_paginated_results

from .client import get_objects_client, get_objecttypes_client
from .client import ObjectsClient, get_objects_client, get_objecttypes_client
from .models import MetaObjectTypesConfig

logger = logging.getLogger(__name__)
Expand All @@ -30,13 +32,45 @@ def fetch_objecttype(task: BaseTask, url: str) -> Dict:
return client.get(path)


def fetch_objecttypes(task: BaseTask, query_params: dict = dict) -> List[dict]:
def fetch_objecttypes(task: BaseTask, query_params: dict = dict) -> List[Dict]:
client = get_objecttypes_client(task)
return client.get("objecttypes", params=query_params)
objecttypes = get_paginated_results(
client, "objecttypes", query_params=query_params
)
return objecttypes


def fetch_object(
object_url: str,
client: Optional[ObjectsClient] = None,
task: Optional[BaseTask] = None,
) -> Dict:
if not client and not task:
raise RuntimeError(
"fetch_object requires one of keyword arguments client or task."
)

if task:
client = get_objects_client(task)

return client.get(
path=object_url.split(client.api_root)[-1], operation="object_read"
)


def fetch_objects(task: BaseTask, objects: List[str]) -> List[Dict]:
client = get_objects_client(task)

def _fetch_object(object_url):
return fetch_object(client, object_url)

with parallel() as executor:
objects = list(executor.map(_fetch_object, objects))
return objects


def update_object_record_data(
task, object: Dict, data: Dict, username: Optional[str] = None
task: BaseTask, object: Dict, data: Dict, username: Optional[str] = None
) -> Dict:
client = get_objects_client(task)
new_data = {
Expand Down
102 changes: 98 additions & 4 deletions src/bptl/work_units/zgw/objects/tasks.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import datetime
import logging
from typing import Dict
from typing import Dict, List

from zgw_consumers.concurrent import parallel
from zgw_consumers.constants import APITypes
Expand All @@ -15,6 +15,8 @@
fetch_checklist,
fetch_checklist_objecttype,
fetch_checklisttype,
fetch_objects,
fetch_objecttypes,
get_review_request,
get_reviews_for_review_request,
update_review_request,
Expand All @@ -23,6 +25,86 @@
logger = logging.getLogger(__name__)


###################################################
# Objects #
###################################################


@register
@require_objects_service
@require_objecttypes_service
def filter_zaakobjects_on_objecttype_label(task: BaseTask) -> List[Dict]:
"""
Filter objects through a label value of the objecttype of the objects.
In the task binding, the service with alias ``objects``, ``objecttypes`` and ``zrc`` must be connected, so that
this task knows which endpoints to contact.
**Required process variables**
* ``zaakObjects`` list[str]]: a list of ZAAKOBJECTs to be filtered.
* ``label`` [str]: a value to be filtered on. If value is not found - object is filtered out.
**Sets the process variables**
* ``filteredObjects`` [list[str]]: a list of JSONs:
.. code-block:: json
[
{
"objectUrl" [str]: URL-reference,
"objectType" [str]: URL-reference,
"objectTypeOverige" [str]: <description>,
"relatieomschrijving" [str]: <description>
},
]
"""

variables = task.get_variables()
zaakobjects = check_variable(variables, "zaakObjects", empty_allowed=True)
if not zaakobjects:
return dict()

label = check_variable(variables, "label", empty_allowed=True)

# fetch objecttypes to be filtered on
object_types = fetch_objecttypes(
task,
)
object_types = [
ot["url"]
for ot in object_types
if ot.get("labels", {}).get("filter", "") == label
]
if not object_types:
return dict()

objects = fetch_objects(
task, list({zo["object"] for zo in zaakobjects if zo.get("object", None)})
)

# filter objects
objects = {obj["url"]: obj for obj in objects if obj["type"] in object_types}

# filter zaakobjects
filtered_objects = []
for zo in zaakobjects:
if object := objects.get(zo["object"]):
filtered_objects.append(
{
"objectUrl": object["url"],
"objectType": object["type"],
"objectTypeOverige": zo.get("objectTypeOverige", ""),
"relatieomschrijving": zo.get("relatieomschrijving", ""),
}
)

return filtered_objects


###################################################
# Checklists #
###################################################
Expand All @@ -37,6 +119,9 @@ class InitializeChecklistTask(ZGWWorkUnit):
"""
Creates an empty CHECKLIST for ZAAK if CHECKLISTTYPE for ZAAKTYPE exists.
In the task binding, the service with alias ``objects``, ``objecttypes``, ``zrc`` and ``ztc`` must be connected, so that
this task knows which endpoints to contact.
**Required process variables**
* ``zaakUrl`` [str]: URL-reference of the ZAAK in Open Zaak.
* ``catalogusDomein`` [str]: `domein` of the CATALOGUS in Open Zaak OR ``zaaktypeCatalogus`` [str]: URL-reference of CATALOGUS in CATALOGUS of Open Zaak.
Expand Down Expand Up @@ -149,7 +234,7 @@ def get_approval_status(task: BaseTask) -> dict:
from the review session. If all reviewers approve, the result is positive. If any
rejections are present, the result is negative.
In the task binding, the service with alias ``kownsl`` must be connected, so that
In the task binding, the service with alias ``objects`` and ``objecttypes`` must be connected, so that
this task knows which endpoints to contact.
**Required process variables**
Expand Down Expand Up @@ -183,7 +268,7 @@ def get_review_response_status(task: BaseTask) -> dict:
Get the reviewers who have not yet responded to a review request so that
a reminder email can be sent to them if they exist.
In the task binding, the service with alias ``kownsl`` must be connected, so that
In the task binding, the service with alias ``objects`` and ``objecttypes`` must be connected, so that
this task knows which endpoints to contact.
**Required process variables**
Expand Down Expand Up @@ -243,7 +328,7 @@ def get_review_request_start_process_information(task: BaseTask) -> dict:
- the username of the requester,
- and finally, the review type.
In the task binding, the service with alias ``kownsl`` must be connected, so that
In the task binding, the service with alias ``objects`` and ``objecttypes`` must be connected, so that
this task knows which endpoints to contact.
**Required process variables**
Expand Down Expand Up @@ -296,6 +381,9 @@ def set_review_request_metadata(task: BaseTask) -> dict:
Metadata is a set of arbitrary key-value labels, allowing you to attach extra data
required for your process routing/handling.
In the task binding, the service with alias ``objects`` and ``objecttypes`` must be connected, so that
this task knows which endpoints to contact.
**Required process variables**
* ``kownslReviewRequestId`` [str]: the identifier of the Kownsl review request.
Expand Down Expand Up @@ -325,6 +413,9 @@ def get_approval_toelichtingen(task: BaseTask) -> dict:
"""
Get the "toelichtingen" of all reviewers that responded to the review request.
In the task binding, the service with alias ``objects`` and ``objecttypes`` must be connected, so that
this task knows which endpoints to contact.
**Required process variables**
* ``kownslReviewRequestId`` [str]: the identifier of the Kownsl review request.
Expand Down Expand Up @@ -356,6 +447,9 @@ def lock_review_request(task: BaseTask) -> dict:
"""
Lock review request after all reviews have been given.
In the task binding, the service with alias ``objects`` and ``objecttypes`` must be connected, so that
this task knows which endpoints to contact.
**Required process variables**
* ``kownslReviewRequestId`` [str]: the identifier of the Kownsl review request.
Expand Down
57 changes: 30 additions & 27 deletions src/bptl/work_units/zgw/tasks/zaak_relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,42 +413,45 @@ def perform(self) -> Optional[dict]:
return {"zaakRelaties": relevante_andere_zaken}


# @register
# @require_zrc
# class FetchZaakObjectRelaties(ZGWWorkUnit):
# """
# Fetch all ZAAKOBJECTs for ZAAK that are not `meta` objecttypes.
@register
@require_zrc
class FetchObjectRelaties(ZGWWorkUnit):
"""
Fetch all OBJECTs for ZAAK.
# **Required process variables**
**Required process variables**
# * ``zaakUrl`` [str]: URL-reference of ZAAK.
# * ``bptlAppId`` [str]: the application ID of the app that caused this task to be executed.
# The app-specific credentials will be used for the API calls.
* ``zaakUrl`` [str]: URL-reference of ZAAK.
* ``bptlAppId`` [str]: the application ID of the app that caused this task to be executed.
The app-specific credentials will be used for the API calls.
# **Sets the process variables**
**Sets the process variables**
# * ``zaakObjectUrls`` list[str]: A list of ZAAKOBJECTs.
* ``zaakObjects`` list[dict[str,str]]: A list of ZAAKOBJECTs, with their objecttypes and objectTypeOverige and relatieomschrijving attributes.
# """
# # get vars
# variables = self.task.get_variables()
"""

def perform(self) -> Optional[dict]:
# get vars
variables = self.task.get_variables()

# zaak_url = variables.get("hoofdZaakUrl")
# if not zaak_url:
# logger.info("No 'hoofdZaakUrl' provided, skipping task execution.")
# return
zaak_url = variables.get("hoofdZaakUrl")
if not zaak_url:
logger.info("No 'hoofdZaakUrl' provided, skipping task execution.")
return

# # prep clients
# zrc_client = self.get_client(APITypes.zrc)
# prep clients
zrc_client = self.get_client(APITypes.zrc)

# headers = get_nlx_headers(variables)
# zaakobjecten = get_paginated_results(
# client,
# "zaakobject",
# query_params={"zaak": zaak_url},
# )
headers = get_nlx_headers(variables)
zaakobjecten = get_paginated_results(
zrc_client,
"zaakobject",
query_params={"zaak": zaak_url},
request_headers=headers,
)

# return {}
return {"zaakObjects": zaakobjecten}


@register
Expand Down
12 changes: 6 additions & 6 deletions src/bptl/work_units/zgw/tests/test_task_bijdrage_zaak.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,9 @@ def test_relateer_zaak_empty_bijdrage_aard_omgekeerde_richting(self, m):
},
)

self.fetched_task.variables["aardRelatieOmgekeerdeRichting"] = (
serialize_variable("")
)
self.fetched_task.variables[
"aardRelatieOmgekeerdeRichting"
] = serialize_variable("")
self.fetched_task.save()
task = RelateerZaak(self.fetched_task)

Expand Down Expand Up @@ -198,9 +198,9 @@ def test_relateer_zaak_bijdrage_aard_omgekeerde_richting_invalid(self, m):
},
)

self.fetched_task.variables["aardRelatieOmgekeerdeRichting"] = (
serialize_variable("niks")
)
self.fetched_task.variables[
"aardRelatieOmgekeerdeRichting"
] = serialize_variable("niks")
self.fetched_task.save()
task = RelateerZaak(self.fetched_task)

Expand Down

0 comments on commit 6ed960b

Please sign in to comment.