models.py 12 KB

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