class SavedAddressSerializer(serializers.ModelSerializer): role = EnumField(SavedAddressRole) status = EnumField(SavedAddressStatus) address = AddressSerializer() class Meta: model = SavedAddress exclude = ()
class OrderSerializer(serializers.ModelSerializer): payment_status = EnumField(PaymentStatus) shipping_status = EnumField(ShippingStatus) billing_address = AddressSerializer() shipping_address = AddressSerializer() lines = OrderLineSerializer(many=True) class Meta: model = Order exclude = ()
class EventSerializer(EnumSupportSerializerMixin, serializers.ModelSerializer): action = serializers.PrimaryKeyRelatedField(queryset=Action.objects.all()) event_type = EnumField(enum=enums.EventType) class Meta: model = Event fields = ["event_type", "action"]
class GDPRPersonContactSerializer(ContactSerializer): gender = EnumField(Gender) user = UserSerializer() log_entries = PersonContactLogEntrySerializer(many=True) company_memberships = GDPRCompanyContactSerializer(many=True) class Meta: model = PersonContact exclude = ("polymorphic_ctype", )
class ActionSerializer(SubscriberSerializerMixin, EnumSupportSerializerMixin, serializers.ModelSerializer): action = serializers.PrimaryKeyRelatedField(read_only=True, required=False) sms_opt_in_subscriber = serializers.BooleanField(required=False) initial_events = serializers.ListField(child=EnumField( enum=enums.EventType)) def __init__(self, instance=None, data=empty, **kwargs) -> None: self.incomplete = kwargs.pop("incomplete", False) super().__init__(instance=instance, data=data, **kwargs) def create(self, validated_data: Dict[(str, Any)]) -> "Model": validated_data["action"] = Action.objects.create( visible_to_subscriber=self.request_subscriber( ).plan_has_data_access()) return super().create(validated_data) @tracer.wrap() def run_validation(self, *args, **kwargs): return super().run_validation(*args, **kwargs) def get_field_names(self, declared_fields: Mapping[(str, serializers.Field)], info: "FieldInfo") -> List[str]: # There are 5 possible Meta attributes for fields in ActionSerializers, # "minimum_necessary_fields", "nationally_required_fields", "optional_fields", # "fields", and "exclude" minimum_necessary_fields = getattr(self.Meta, "minimum_necessary_fields", []) nationally_required_fields = getattr(self.Meta, "nationally_required_fields", []) optional_fields = getattr(self.Meta, "optional_fields", []) standard_fields = getattr(self.Meta, "fields", []) # Return a deduplicated list of all fields return list( set(minimum_necessary_fields + nationally_required_fields + optional_fields + standard_fields + ["initial_events"])) def get_fields(self) -> "collections.OrderedDict[str, serializers.Field]": initial_fields = super().get_fields() fields = collections.OrderedDict() for key, value in initial_fields.items(): if key in getattr(self.Meta, "minimum_necessary_fields", []): value.required = True # type: ignore[attr-defined] elif not self.incomplete and key in getattr( self.Meta, "nationally_required_fields", []): value.required = True # type: ignore[attr-defined] else: value.required = False # type: ignore[attr-defined] fields[key] = value return fields
class StatusSerializer(EnumSupportSerializerMixin, serializers.ModelSerializer): status = EnumField(enum=enums.TurnoutActionStatus, required=True) class Meta: model = Registration fields = ("status",) def validate_status(self, value): if not value == enums.TurnoutActionStatus.OVR_REFERRED: raise serializers.ValidationError( f"Registration status can only be {enums.TurnoutActionStatus.OVR_REFERRED.value}" ) return value
def get(self, request, **kwargs): last_span = models.Downtime.objects.order_by("-start").first() last_updated = cache.get("tweetdb:last_update") if last_updated: last_updated = datetime.datetime.fromtimestamp(last_updated) last_updated = DateTimeField().to_representation(last_updated) return Response( { "status": EnumField(models.Status, ints_as_names=True).to_representation(last_span.get_latest_status()), "last_span": serializers.DowntimeSerializer(last_span).data, "last_updated": last_updated, } )
class OrderLineSerializer(serializers.ModelSerializer): type = EnumField(OrderLineType) class Meta: model = OrderLine exclude = ()
class ContactLogEntrySerializer(serializers.ModelSerializer): kind = EnumField(LogEntryKind) class Meta: model = ContactGroupLogEntry exclude = ()
class GatewayCallbackSerializer(serializers.Serializer): fax_id = serializers.UUIDField(required=True) status = EnumField(enum=enums.FaxStatus, required=True) message = serializers.CharField(required=True) timestamp = TimestampField(required=True)
class ExternalRegistrationSerializer( EnumSupportSerializerMixin, serializers.ModelSerializer ): title = EnumField(required=False, enum=enums.PersonTitle) first_name = serializers.CharField(required=True, max_length=256) middle_name = serializers.CharField(required=False, max_length=256) last_name = serializers.CharField(required=True, max_length=256) suffix = serializers.CharField(required=False, max_length=256) date_of_birth = serializers.DateField(required=True, input_formats=["iso-8601"]) email = serializers.EmailField(required=True, max_length=256) phone = PhoneNumberField(required=False) address1 = serializers.CharField(required=True, max_length=256) address2 = serializers.CharField(required=False, max_length=256) city = serializers.CharField(required=True, max_length=256) state = serializers.ChoiceField( choices=STATES, validators=[state_code_validator], required=True, source="state_id", ) zipcode = serializers.CharField(validators=[zip_validator], required=True) sms_opt_in = RequiredBooleanField( required=True, validators=[must_be_true_validator] ) sms_opt_in_subscriber = RequiredBooleanField( required=False, validators=[must_be_true_validator] ) def validate(self, data): """ To guarantee our ability to maintain backwards-compatibility, we reject extra fields -- we don't want someone to be passing, e.g., "previous_name" (which we would ignore), and then run into issues if we add a field with that name with different validation requirements than their assumptions. """ if hasattr(self, "initial_data"): unknown_keys = set(self.initial_data.keys()) - set(self.fields.keys()) if unknown_keys: raise ValidationError("Got unknown fields: {}".format(unknown_keys)) if ( data.get("state_id").lower() == "tn" and data.get("title") == enums.PersonTitle.MX ): raise ValidationError("Tennesee does not allow a title of Mx.") return data def create(self, validated_data): validated_data["action"] = Action.objects.create() validated_data["subscriber"] = self.request_subscriber(validated_data) validated_data["gender"] = self.guess_gender_from_title(validated_data) validated_data["status"] = enums.TurnoutActionStatus.INCOMPLETE return super().create(validated_data) def request_subscriber(self, data): return self.context.get("request").auth.subscriber def guess_gender_from_title(self, data): if data.get("title"): return data.get("title").guess_registration_gender() else: return None class Meta: model = Registration fields = ( "title", "first_name", "middle_name", "last_name", "suffix", "date_of_birth", "email", "phone", "address1", "address2", "city", "state", "zipcode", "sms_opt_in", "sms_opt_in_subscriber", "subscriber", "gender", "status", )