2021-12-22 09:35:32 +00:00
|
|
|
from rest_framework import serializers
|
|
|
|
from perms.models import Action
|
2022-01-13 10:32:12 +00:00
|
|
|
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
2022-03-11 11:28:00 +00:00
|
|
|
from rest_framework.fields import empty
|
2021-12-22 09:35:32 +00:00
|
|
|
|
2022-01-13 10:32:12 +00:00
|
|
|
__all__ = ['ActionsDisplayField', 'ActionsField', 'BasePermissionSerializer']
|
2021-12-22 09:35:32 +00:00
|
|
|
|
|
|
|
|
|
|
|
class ActionsField(serializers.MultipleChoiceField):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
kwargs['choices'] = Action.CHOICES
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
2022-03-11 11:28:00 +00:00
|
|
|
def run_validation(self, data=empty):
|
2022-03-15 10:22:13 +00:00
|
|
|
data = super(ActionsField, self).run_validation(data)
|
2022-03-11 11:28:00 +00:00
|
|
|
if isinstance(data, list):
|
|
|
|
data = Action.choices_to_value(value=data)
|
|
|
|
return data
|
|
|
|
|
2021-12-22 09:35:32 +00:00
|
|
|
def to_representation(self, value):
|
|
|
|
return Action.value_to_choices(value)
|
|
|
|
|
|
|
|
def to_internal_value(self, data):
|
|
|
|
if data is None:
|
|
|
|
return data
|
|
|
|
return Action.choices_to_value(data)
|
|
|
|
|
|
|
|
|
|
|
|
class ActionsDisplayField(ActionsField):
|
|
|
|
def to_representation(self, value):
|
|
|
|
values = super().to_representation(value)
|
|
|
|
choices = dict(Action.CHOICES)
|
|
|
|
return [choices.get(i) for i in values]
|
|
|
|
|
2022-01-13 10:32:12 +00:00
|
|
|
|
|
|
|
class BasePermissionSerializer(BulkOrgResourceModelSerializer):
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
self.set_actions_field()
|
|
|
|
|
|
|
|
def set_actions_field(self):
|
|
|
|
actions = self.fields.get('actions')
|
|
|
|
if not actions:
|
|
|
|
return
|
|
|
|
choices = actions._choices
|
|
|
|
choices = self._filter_actions_choices(choices)
|
|
|
|
actions._choices = choices
|
|
|
|
actions.default = list(choices.keys())
|
|
|
|
|
|
|
|
def _filter_actions_choices(self, choices):
|
|
|
|
return choices
|