models.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. import datetime
  2. from itertools import chain
  3. from django.conf import settings
  4. from django.core.exceptions import ValidationError
  5. from django.core.urlresolvers import reverse
  6. from django.db import models, transaction
  7. import markdown
  8. class Document(models.Model):
  9. """ A document is a scenario or a record from facts, on 1 month.
  10. """
  11. TYPE_FACT = 'fact'
  12. TYPE_PLAN = 'plan'
  13. name = models.CharField('Nom', max_length=130)
  14. comment = models.TextField(
  15. 'commentaire',
  16. blank=True, help_text="Texte brut ou markdown")
  17. comment_html = models.TextField(blank=True, editable=False)
  18. date = models.DateField(default=datetime.datetime.now)
  19. type = models.CharField(max_length=10, choices=(
  20. (TYPE_FACT, 'rapports de transparence'),
  21. (TYPE_PLAN, 'scénario/estimation'),
  22. ))
  23. def __str__(self):
  24. return self.name
  25. def save(self, *args, **kwargs):
  26. self.comment_html = markdown.markdown(self.comment)
  27. super().save(*args, **kwargs)
  28. def get_absolute_url(self):
  29. return reverse('detail-document', kwargs={'pk': self.pk})
  30. def copy(self):
  31. """ Deep copy and saving of a document
  32. All related resources are copied.
  33. """
  34. with transaction.atomic():
  35. new_doc = Document.objects.get(pk=self.pk)
  36. new_doc.pk = None
  37. new_doc.name = 'COPIE DE {}'.format(new_doc.name)
  38. new_doc.save()
  39. new_services, new_costs, new_goods = {}, {}, {}
  40. to_copy = (
  41. (self.service_set, new_services),
  42. (self.good_set, new_goods),
  43. (self.cost_set, new_costs),
  44. )
  45. for qs, index in to_copy:
  46. for item in qs.all():
  47. old_pk = item.pk
  48. item.pk = None
  49. item.document = new_doc
  50. item.save()
  51. index[old_pk] = item
  52. to_reproduce = (
  53. (ServiceUse, new_services),
  54. (GoodUse, new_goods),
  55. (CostUse, new_costs),
  56. )
  57. for Klass, index in to_reproduce:
  58. src_qs = Klass.objects.filter(service__document=self)
  59. for use in src_qs.all():
  60. use.pk = None
  61. use.service = new_services[use.service.pk]
  62. use.resource = index[use.resource.pk]
  63. use.save()
  64. return new_doc
  65. class AbstractItem(models.Model):
  66. name = models.CharField('Nom', max_length=130)
  67. description = models.TextField('description', blank=True)
  68. description_html = models.TextField(blank=True)
  69. document = models.ForeignKey(Document)
  70. def __str__(self):
  71. return self.name
  72. def save(self, *args, **kwargs):
  73. self.description_html = markdown.markdown(self.description)
  74. super().save(*args, **kwargs)
  75. class Meta:
  76. abstract = True
  77. class AbstractResource(AbstractItem):
  78. UNIT_AMP = 'a'
  79. UNIT_MBPS = 'mbps'
  80. UNIT_U = 'u'
  81. UNIT_IPV4 = 'ipv4'
  82. UNIT_ETHERNET_PORT = 'eth'
  83. UNIT_SERVICE = 'services'
  84. capacity_unit = models.CharField(
  85. 'unité',
  86. max_length=10,
  87. choices=(
  88. (UNIT_AMP, 'A'),
  89. (UNIT_MBPS, 'Mbps'),
  90. (UNIT_U, 'U'),
  91. (UNIT_IPV4, 'IPv4'),
  92. (UNIT_ETHERNET_PORT, 'ports'),
  93. (UNIT_SERVICE, 'abonnement'),
  94. ),
  95. blank=True,
  96. help_text="unité de capacité (si applicable)",
  97. )
  98. total_capacity = models.FloatField(
  99. 'Capacité totale',
  100. default=1,
  101. help_text="Laisser à 1 si non divisible")
  102. class Meta:
  103. abstract = True
  104. def get_use_class(self):
  105. raise NotImplemented
  106. def used(self, except_by=None):
  107. """ Return the used fraction of an item
  108. :type: Service
  109. :param except_by: exclude this service from the math
  110. :rtype: float
  111. """
  112. sharing_costs = self.get_use_class().objects.filter(resource=self)
  113. if except_by:
  114. sharing_costs = sharing_costs.exclude(service=except_by)
  115. existing_uses_sum = sum(
  116. sharing_costs.values_list('share', flat=True))
  117. return existing_uses_sum
  118. def used_fraction(self, *args, **kwargs):
  119. return self.used(*args, **kwargs)/self.total_capacity
  120. def unused(self):
  121. return self.total_capacity-self.used()
  122. def __str__(self):
  123. if self.capacity_unit == '':
  124. return self.name
  125. else:
  126. return '{} {:.0f} {}'.format(
  127. self.name, self.total_capacity,
  128. self.get_capacity_unit_display())
  129. class Cost(AbstractResource):
  130. """ A monthtly cost we have to pay
  131. """
  132. price = models.FloatField("Coût mensuel")
  133. def get_use_class(self):
  134. return CostUse
  135. class Meta:
  136. verbose_name = 'Coût mensuel'
  137. class Good(AbstractResource):
  138. """ A good, which replacement is provisioned
  139. """
  140. price = models.FloatField("Prix d'achat")
  141. provisioning_duration = models.DurationField(
  142. "Durée d'amortissement",
  143. choices=settings.PROVISIONING_DURATIONS)
  144. def get_use_class(self):
  145. return GoodUse
  146. def monthly_provision(self):
  147. return self.price/self.provisioning_duration.days*(365.25/12)
  148. class Meta:
  149. verbose_name = 'Bien'
  150. class AbstractUse(models.Model):
  151. share = models.FloatField()
  152. service = models.ForeignKey('Service')
  153. class Meta:
  154. abstract = True
  155. def __str__(self):
  156. return str(self.resource)
  157. def clean(self):
  158. if hasattr(self, 'resource'):
  159. usage = self.resource.used(except_by=self.service) + self.share
  160. if usage > self.resource.total_capacity:
  161. raise ValidationError(
  162. "Cannot use more than 100% of {})".format(self.resource))
  163. def real_share(self):
  164. """The share, + wasted space share
  165. Taking into account that the unused space is
  166. wasted and has to be divided among actual users
  167. """
  168. return (
  169. self.share +
  170. (self.share/self.resource.used())*self.resource.unused()
  171. )
  172. def unit_share(self):
  173. if self.service.subscriptions_count == 0:
  174. return 0
  175. else:
  176. return self.share/self.service.subscriptions_count
  177. return
  178. def unit_real_share(self):
  179. if self.service.subscriptions_count == 0:
  180. return 0
  181. else:
  182. return self.real_share()/self.service.subscriptions_count
  183. def value_share(self):
  184. return (
  185. self.resource.price
  186. * self.real_share()
  187. / self.resource.total_capacity
  188. )
  189. def unit_value_share(self):
  190. if self.service.subscriptions_count == 0:
  191. return 0
  192. else:
  193. return self.value_share()/self.service.subscriptions_count
  194. class CostUse(AbstractUse):
  195. resource = models.ForeignKey(Cost)
  196. class Meta:
  197. verbose_name = 'Coût mensuel associé'
  198. verbose_name_plural = 'Coûts mensuels associés'
  199. def cost_share(self):
  200. return (
  201. self.real_share() / self.resource.total_capacity
  202. * self.resource.price
  203. )
  204. def unit_cost_share(self):
  205. subscriptions_count = self.service.subscriptions_count
  206. if subscriptions_count == 0:
  207. return 0
  208. else:
  209. return self.cost_share()/self.service.subscriptions_count
  210. class GoodUse(AbstractUse):
  211. resource = models.ForeignKey(Good)
  212. class Meta:
  213. verbose_name = "Matériel ou frais d'accès utilisé"
  214. verbose_name_plural = "Matériels et frais d'accès utilisés"
  215. def monthly_provision_share(self):
  216. return (
  217. self.real_share()
  218. * self.resource.monthly_provision()
  219. / self.resource.total_capacity)
  220. def unit_monthly_provision_share(self):
  221. subscriptions_count = self.service.subscriptions_count
  222. monthly_share = self.monthly_provision_share()
  223. if subscriptions_count == 0:
  224. return 0
  225. else:
  226. return monthly_share/subscriptions_count
  227. class Service(AbstractResource):
  228. """ A service we sell
  229. (considered monthly)
  230. """
  231. costs = models.ManyToManyField(
  232. Cost,
  233. through=CostUse,
  234. related_name='using_services',
  235. verbose_name='coûts mensuels associés')
  236. goods = models.ManyToManyField(
  237. Good,
  238. through=GoodUse,
  239. related_name='using_services',
  240. verbose_name="matériels et frais d'accès utilisés")
  241. subscriptions_count = models.PositiveIntegerField(
  242. "Nombre d'abonnements",
  243. default=0)
  244. reusable = models.BooleanField(
  245. default=False,
  246. help_text="Peut-être utilisé par d'autres services")
  247. @property
  248. def price(self):
  249. return self.get_prices()['total_recurring_price']
  250. def save(self, *args, **kwargs):
  251. if self.reusable:
  252. self.capacity_unit = self.UNIT_SERVICE
  253. self.total_capacity = self.subscriptions_count
  254. return super().save(*args, **kwargs)
  255. def get_absolute_url(self):
  256. return reverse('detail-service', kwargs={'pk': self.pk})
  257. def get_use_class(self):
  258. return ServiceUse
  259. def get_prices(self):
  260. costs_uses = CostUse.objects.filter(service=self)
  261. goods_uses = GoodUse.objects.filter(service=self)
  262. services_uses = ServiceUse.objects.filter(service=self)
  263. total_recurring_price = sum(chain(
  264. (i.monthly_provision_share() for i in goods_uses),
  265. (i.cost_share() for i in costs_uses),
  266. (i.cost_share() for i in services_uses)
  267. ))
  268. total_goods_value_share = sum(
  269. (i.value_share() for i in chain(goods_uses, services_uses)))
  270. if self.subscriptions_count == 0:
  271. unit_recurring_price = 0
  272. unit_goods_value_share = 0
  273. else:
  274. unit_recurring_price = \
  275. total_recurring_price/self.subscriptions_count
  276. unit_goods_value_share = \
  277. total_goods_value_share/self.subscriptions_count
  278. unit_staggered_goods_share = \
  279. unit_goods_value_share/settings.SETUP_COST_STAGGERING_MONTHS
  280. return {
  281. 'total_recurring_price': total_recurring_price,
  282. 'total_goods_value_share': total_goods_value_share,
  283. 'unit_goods_value_share': unit_goods_value_share,
  284. 'unit_recurring_price': unit_recurring_price,
  285. 'unit_staggered_goods_share': unit_staggered_goods_share,
  286. 'unit_consolidated_cost': (
  287. unit_staggered_goods_share + unit_recurring_price),
  288. }
  289. def validate_reusable_service(v):
  290. if not Service.objects.get(pk=v).reusable:
  291. raise ValidationError('{} is not a reusable service'.format(v))
  292. class ServiceUse(AbstractUse):
  293. class Meta:
  294. verbose_name = 'service utilisé'
  295. verbose_name_plural = 'services utilisés'
  296. resource = models.ForeignKey(
  297. Service, related_name='dependent_services',
  298. limit_choices_to={'reusable': True},
  299. validators=[validate_reusable_service])
  300. def cost_share(self):
  301. return (
  302. self.share / self.resource.total_capacity
  303. * self.resource.price
  304. )
  305. def unit_cost_share(self):
  306. subscriptions_count = self.service.subscriptions_count
  307. if subscriptions_count == 0:
  308. return 0
  309. else:
  310. return self.cost_share()/self.service.subscriptions_count
  311. def value_share(self):
  312. return self.share*self.resource.get_prices()['unit_goods_value_share']
  313. def clean(self):
  314. """ Checks for cycles in service using services
  315. """
  316. start_resource = self.resource
  317. def crawl(service):
  318. for use in service.dependent_services.all():
  319. if use.service == start_resource:
  320. raise ValidationError(
  321. 'Cycle detected in services using services')
  322. else:
  323. crawl(use.service)
  324. crawl(self.service)