models.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. from django.conf import settings
  2. from django.core.exceptions import ValidationError
  3. from django.db import models
  4. from .validators import less_than_one
  5. class AbstractItem(models.Model):
  6. name = models.CharField(max_length=130)
  7. description = models.TextField(blank=True)
  8. def __str__(self):
  9. return self.name
  10. class Meta:
  11. abstract = True
  12. class Cost(AbstractItem):
  13. """ A monthtly cost we have to pay
  14. """
  15. price = models.PositiveIntegerField(help_text="Coût mensuel")
  16. class Meta:
  17. verbose_name = 'Coût'
  18. def used(self):
  19. sharing_costs = CostUse.objects.filter(resource=self)
  20. existing_uses_sum = sum(
  21. sharing_costs.values_list('share', flat=True))
  22. return existing_uses_sum
  23. class Good(AbstractItem):
  24. """ A good, which replacement is provisioned
  25. """
  26. price = models.PositiveIntegerField()
  27. provisioning_duration = models.DurationField(
  28. choices=settings.PROVISIONING_DURATIONS)
  29. class Meta:
  30. verbose_name = 'Bien'
  31. class AbstractUse(models.Model):
  32. share = models.FloatField(validators=[less_than_one])
  33. service = models.ForeignKey('Service')
  34. class Meta:
  35. abstract = True
  36. def clean(self):
  37. if hasattr(self, 'resource'):
  38. if (self.resource.used() + self.share) > 1:
  39. raise ValidationError(
  40. "Cannot use more than 100% of {})".format(self.resource))
  41. class CostUse(AbstractUse):
  42. resource = models.ForeignKey(Cost)
  43. class GoodUse(AbstractUse):
  44. resource = models.ForeignKey(Good)
  45. class Service(AbstractItem):
  46. """ A service we sell
  47. (considered monthly)
  48. """
  49. costs = models.ManyToManyField(
  50. Cost,
  51. through=CostUse,
  52. related_name='using_services')
  53. goods = models.ManyToManyField(
  54. Good,
  55. through=GoodUse,
  56. related_name='using_services')
  57. # services = models.ManyToMany('Service') #TODO