Skip to content

Commit

Permalink
Add prefilter option to context reference property (#1468)
Browse files Browse the repository at this point in the history
* Add prefilter option to context reference property

Implemented a method to set prefilters on the context reference property and created a new ContextgroupFilter class. Updated relevant imports and code sections to support this functionality.

* Fix indentation in value_filter.py

Correct the indentation of property type checks to enhance code readability and maintain consistency. This change ensures proper alignment and structure in the conditional statements.

* Add prefilters to ContextReferencesProperty

Implemented `set_prefilters` method in `ContextReferencesProperty` to support clearing and setting the `context_group` prefilter. Added corresponding unit tests to ensure proper functionality and to handle edge cases, including invalid inputs.

* Remove unnecessary f-string in error message

Refactor the exception raise to eliminate the unnecessary f-string formatting since no variables are being interpolated. This cleanup simplifies the code and ensures better readability.

* Remove ContextGroup filtering and fix typos

Deleted the ContextGroupFilter class including its methods and references to the ContextGroup enum. Corrected typos in comments for clarity.

* Fix indentation in property type filtration

Adjusted indentation to ensure that property types in the filter are correctly and clearly aligned. This enhances readability and maintains consistency in the code formatting structure.

* Refactor docstring to improve clarity

Simplified the docstring of `parse_options` method for better readability. Changed the description to be more concise and removed unnecessary line breaks.

* Remove unused import in test_properties.py

Removed the import of `ContextType` and `ContextReferencesProperty` from `test_properties.py` as they were unused. This change reduces unnecessary code clutter and improves maintainability of the test suite.

---------

Co-authored-by: Jochem Berends <jochem.berends@ke-works.com>
  • Loading branch information
jberends and Jochem Berends authored Nov 26, 2024
1 parent 43be675 commit 9026f67
Show file tree
Hide file tree
Showing 10 changed files with 117 additions and 14 deletions.
7 changes: 5 additions & 2 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
Change Log
==========

v4.15.0 (14NOV24)
UNRELEASED
----------
* :star: Add the possibility to add a prefilter option to the context reference property. It will be stored in the prefilter section of the value options of a the reference property.

v4.15.0 (14NOV24)
-----------------
* :star: We added a `json_load()` method on the `StoredFile` to be compatible with the same interface as the attachment property. (#1485)

v4.14.0 (20SEP24)
Expand Down Expand Up @@ -34,7 +38,6 @@ v4.10.0 (5MAR24)
* :+1: Added python tests for 3.12. (#1389)
* :+1: dependent versions for development: tox (4.12.1), flake8 (7.0.0), jsonschema (4.21.1), importlib-metadata (7.0.1), mypy (1.8.0), pytest (8.1.0), coverage (7.4.3), pre-commit (3.6.2), pytz (2024.1), pytest-xdist (3.5.0), semver (3.0.2), Pillow (10.2.0)


v4.9.0 (28SEP23)
----------------
* :+1: Changed the way we download pdf's from activity where we now provide the `timezone` query param in the request URL with timezone info for a more accurate determination of the display of time information in the pdf taking into account the timezone and timesystem info. For compatability sake we maintain the `offset` query param in the request to support older KE-chain backend versions.
Expand Down
34 changes: 34 additions & 0 deletions pykechain/models/property_reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from pykechain.defaults import PARTS_BATCH_LIMIT
from pykechain.enums import (
ContextGroup,
ScopeReferenceColumns,
StoredFileCategory,
StoredFileClassification,
Expand All @@ -15,6 +16,7 @@
)
from pykechain.models.context import Context
from pykechain.models.form import Form
from pykechain.models.input_checks import check_enum
from pykechain.models.stored_file import StoredFile
from pykechain.models.value_filter import ScopeFilter
from pykechain.models.workflow import Status
Expand Down Expand Up @@ -226,6 +228,38 @@ class ContextReferencesProperty(_ReferencePropertyInScope):

REFERENCED_CLASS = Context

def set_prefilters(
self,
prefilters: Optional = None,
clear: Optional[bool] = False,
context_group: Optional[ContextGroup] = None,
) -> None:
"""
Set pre-filters on the Context reference property.
On the Context only a context_group prefilter can be set to a single ContextGroup.
:param prefilters: Not used
:param clear: whether all existing pre-filters should be cleared. (default = False)
:param context_group: An optional ContextGroup to prefilter on. One single prefilter is
allowed.
:return: None
"""
prefilters_dict = self._options.get("prefilters", dict())
if prefilters:
raise IllegalArgumentError(
"`prefilters` argument is unused. Use `context_group` instead."
)
if clear:
prefilters_dict = dict()
if context_group:
context_group = check_enum(context_group, ContextGroup, "context_group")
prefilters_dict = {"context_group": context_group}

if context_group or clear:
self._options.update({"prefilters": prefilters_dict})

def _retrieve_objects(self, **kwargs) -> List[Context]:
"""
Retrieve a list of Contexts.
Expand Down
31 changes: 19 additions & 12 deletions pykechain/models/value_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,14 @@
import warnings
from abc import abstractmethod
from typing import Any, Dict, List, Optional, Union
from urllib.parse import unquote

from pykechain.enums import Category, FilterType, PropertyType, ScopeStatus
from pykechain.enums import (
Category,
FilterType,
PropertyType,
ScopeStatus,
)
from pykechain.exceptions import IllegalArgumentError, NotFoundError
from pykechain.models.input_checks import (
check_base,
Expand Down Expand Up @@ -75,7 +81,7 @@ def __init__(

self.id = property_model_id
if isinstance(value, str):
self.value = urllib.parse.unquote(value)
self.value = unquote(value)
else:
self.value = value
self.type = filter_type
Expand Down Expand Up @@ -113,9 +119,7 @@ def validate(self, part_model: "Part") -> None:

if prop.category != Category.MODEL:
raise IllegalArgumentError(
'Property value filters can only be set on Property models, received "{}".'.format(
prop
)
f'Property value filters can only be set on Property models, received "{prop}".'
)
else:
property_type = prop.type
Expand Down Expand Up @@ -190,9 +194,10 @@ def validate(self, part_model: "Part") -> None:
@classmethod
def parse_options(cls, options: Dict) -> List["PropertyValueFilter"]:
"""
Convert the dict & string-based definition of a property value filter to a list of PropertyValueFilter objects.
Convert dict and string filters to PropertyValueFilter objects.
:param options: options dict from a multi-reference property or meta dict from a filtered grid widget.
:param options: options dict from a multi-reference property or meta dict from a filtered
grid widget.
:return: list of PropertyValueFilter objects
:rtype list
"""
Expand Down Expand Up @@ -235,7 +240,8 @@ class ScopeFilter(BaseFilter):
:ivar tag: string
"""

# map between KE-chain field and Pykechain attribute, and whether the filter is stored as a list (cs-string)
# map between KE-chain field and Pykechain attribute, and whether the filter is stored as a
# list (cs-string)
MAP = [
("name__icontains", "name", False),
("status__in", "status", False),
Expand Down Expand Up @@ -325,9 +331,10 @@ def __repr__(self):
@classmethod
def parse_options(cls, options: Dict) -> List["ScopeFilter"]:
"""
Convert the dict & string-based definition of a scope filter to a list of ScopeFilter objects.
Convert the dict & string-based definition of a scope filter to a list of ScopeFilter obj.
:param options: options dict from a scope reference property or meta dict from a scopes widget.
:param options: options dict from a scope reference property or meta dict from a scopes
widget.
:return: list of ScopeFilter objects
:rtype list
"""
Expand Down Expand Up @@ -377,8 +384,8 @@ def write_options(cls, filters: List) -> Dict:

if filter_value is not None:
if is_list:
# creata a string with commaseparted prefilters, the first item directly and
# consequent items with a ,
# create a string with comma separted prefilters, the first item directly
# and consequent items with a ,
# TODO: refactor to create a list and then join them with a ','
if field not in prefilters:
prefilters[field] = filter_value
Expand Down
1 change: 1 addition & 0 deletions pykechain/models/widgets/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,7 @@ def _check_prefilters(
:raises IllegalArgumentError: when the type of the input is provided incorrect.
"""
if isinstance(prefilters, dict):
from pykechain.models import Property
property_models: List[Property, str] = prefilters.get(
MetaWidget.PROPERTY_MODELS, []
) # noqa
Expand Down
Loading

0 comments on commit 9026f67

Please sign in to comment.