2023-10-20 09:30:11 +02:00
|
|
|
from rest_framework import serializers
|
|
|
|
|
|
|
|
|
|
from apps.labels.models import AssociatedLabel, LabelKeyCache, LabelValueCache
|
|
|
|
|
from apps.labels.utils import is_labels_feature_enabled
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class LabelKeySerializer(serializers.ModelSerializer):
|
|
|
|
|
id = serializers.CharField()
|
2024-02-20 14:42:51 +08:00
|
|
|
prescribed = serializers.BooleanField(default=False)
|
2023-10-20 09:30:11 +02:00
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
|
model = LabelKeyCache
|
|
|
|
|
fields = (
|
|
|
|
|
"id",
|
|
|
|
|
"name",
|
2024-02-20 14:42:51 +08:00
|
|
|
"prescribed",
|
2023-10-20 09:30:11 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class LabelValueSerializer(serializers.ModelSerializer):
|
|
|
|
|
id = serializers.CharField()
|
2024-02-20 14:42:51 +08:00
|
|
|
prescribed = serializers.BooleanField(default=False)
|
2023-10-20 09:30:11 +02:00
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
|
model = LabelValueCache
|
|
|
|
|
fields = (
|
|
|
|
|
"id",
|
|
|
|
|
"name",
|
2024-02-20 14:42:51 +08:00
|
|
|
"prescribed",
|
2023-10-20 09:30:11 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2024-02-20 14:42:51 +08:00
|
|
|
class LabelPairSerializer(serializers.Serializer):
|
2023-10-20 09:30:11 +02:00
|
|
|
key = LabelKeySerializer()
|
|
|
|
|
value = LabelValueSerializer()
|
|
|
|
|
|
|
|
|
|
|
2024-02-20 14:42:51 +08:00
|
|
|
class LabelOptionSerializer(serializers.Serializer):
|
2023-10-20 09:30:11 +02:00
|
|
|
key = LabelKeySerializer()
|
|
|
|
|
values = LabelValueSerializer(many=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class LabelReprSerializer(serializers.Serializer):
|
|
|
|
|
name = serializers.CharField()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class LabelsSerializerMixin(serializers.Serializer):
|
2024-02-20 14:42:51 +08:00
|
|
|
labels = LabelPairSerializer(many=True, required=False)
|
2023-10-20 09:30:11 +02:00
|
|
|
|
|
|
|
|
def validate_labels(self, labels):
|
|
|
|
|
if labels:
|
|
|
|
|
keys = {label["key"]["id"] for label in labels}
|
|
|
|
|
if len(keys) != len(labels):
|
|
|
|
|
raise serializers.ValidationError(detail="Duplicate label key")
|
|
|
|
|
return labels
|
|
|
|
|
|
|
|
|
|
def update_labels_association_if_needed(self, labels, instance, organization):
|
|
|
|
|
if labels is not None and is_labels_feature_enabled(organization):
|
|
|
|
|
AssociatedLabel.update_association(labels, instance, organization)
|