serializers.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from django.core.exceptions import SuspiciousOperation
  2. from rest_framework import serializers
  3. from rest_framework.serializers import ModelSerializer
  4. from djstripe.models import Plan, Customer, Product
  5. from organizations_ext.models import OrganizationUserRole
  6. from .rest_framework.serializers import (
  7. SubscriptionSerializer as BaseSubscriptionSerializer,
  8. )
  9. class BaseProductSerializer(ModelSerializer):
  10. class Meta:
  11. model = Product
  12. fields = ("id", "name", "description", "type", "metadata")
  13. class PlanSerializer(ModelSerializer):
  14. product = BaseProductSerializer()
  15. class Meta:
  16. model = Plan
  17. fields = ("id", "nickname", "amount", "metadata", "product")
  18. class ProductSerializer(BaseProductSerializer):
  19. plans = PlanSerializer(many=True, source="plan_set")
  20. class Meta(BaseProductSerializer.Meta):
  21. fields = ("id", "name", "description", "type", "plans", "metadata")
  22. class SubscriptionSerializer(BaseSubscriptionSerializer):
  23. plan = PlanSerializer(read_only=True)
  24. class OrganizationPrimaryKeySerializer(serializers.PrimaryKeyRelatedField):
  25. def get_queryset(self):
  26. user = self.context["request"].user
  27. return user.organizations_ext_organization.filter(
  28. organization_users__role=OrganizationUserRole.OWNER
  29. )
  30. class OrganizationSelectSerializer(serializers.Serializer):
  31. """ Organization in which user is owner of """
  32. organization = OrganizationPrimaryKeySerializer()
  33. class PlanForOrganizationSerializer(OrganizationSelectSerializer):
  34. plan = serializers.SlugRelatedField(queryset=Plan.objects.all(), slug_field="id")
  35. class CreateSubscriptionSerializer(PlanForOrganizationSerializer):
  36. """A serializer used to create a Subscription. Only works with free plans. """
  37. subscription = SubscriptionSerializer(read_only=True)
  38. def create(self, data):
  39. organization = data["organization"]
  40. plan = data["plan"]
  41. if plan.amount != 0.0:
  42. raise SuspiciousOperation(
  43. "Cannot subscribe to non-free plan without payment"
  44. )
  45. customer, _ = Customer.get_or_create(subscriber=organization)
  46. subscription = customer.subscribe(items=[{"plan": plan}])
  47. return {
  48. "plan": plan,
  49. "organization": organization,
  50. "subscription": subscription,
  51. }