models.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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, 'rapport de transparence'),
  21. (TYPE_PLAN, 'estimation ou étude'),
  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 = "Matériel ou Frais d'accès"
  150. verbose_name_plural = "Matériels ou Frais d'accès"
  151. class AbstractUse(models.Model):
  152. share = models.FloatField()
  153. service = models.ForeignKey('Service')
  154. class Meta:
  155. abstract = True
  156. def __str__(self):
  157. return str(self.resource)
  158. def clean(self):
  159. if hasattr(self, 'resource'):
  160. usage = self.resource.used(except_by=self.service) + self.share
  161. if usage > self.resource.total_capacity:
  162. raise ValidationError(
  163. "Cannot use more than 100% of {})".format(self.resource))
  164. def real_share(self):
  165. """The share, + wasted space share
  166. Taking into account that the unused space is
  167. wasted and has to be divided among actual users
  168. """
  169. return (
  170. self.share +
  171. (self.share/self.resource.used())*self.resource.unused()
  172. )
  173. def unit_share(self):
  174. if self.service.subscriptions_count == 0:
  175. return 0
  176. else:
  177. return self.share/self.service.subscriptions_count
  178. return
  179. def unit_real_share(self):
  180. if self.service.subscriptions_count == 0:
  181. return 0
  182. else:
  183. return self.real_share()/self.service.subscriptions_count
  184. def value_share(self):
  185. return (
  186. self.resource.price
  187. * self.real_share()
  188. / self.resource.total_capacity
  189. )
  190. def unit_value_share(self):
  191. if self.service.subscriptions_count == 0:
  192. return 0
  193. else:
  194. return self.value_share()/self.service.subscriptions_count
  195. class CostUse(AbstractUse):
  196. resource = models.ForeignKey(Cost)
  197. class Meta:
  198. verbose_name = 'Coût mensuel associé'
  199. verbose_name_plural = 'Coûts mensuels associés'
  200. def cost_share(self):
  201. return (
  202. self.real_share() / self.resource.total_capacity
  203. * self.resource.price
  204. )
  205. def unit_cost_share(self):
  206. subscriptions_count = self.service.subscriptions_count
  207. if subscriptions_count == 0:
  208. return 0
  209. else:
  210. return self.cost_share()/self.service.subscriptions_count
  211. class GoodUse(AbstractUse):
  212. resource = models.ForeignKey(Good)
  213. class Meta:
  214. verbose_name = "Matériel ou frais d'accès utilisé"
  215. verbose_name_plural = "Matériels et frais d'accès utilisés"
  216. def monthly_provision_share(self):
  217. return (
  218. self.real_share()
  219. * self.resource.monthly_provision()
  220. / self.resource.total_capacity)
  221. def unit_monthly_provision_share(self):
  222. subscriptions_count = self.service.subscriptions_count
  223. monthly_share = self.monthly_provision_share()
  224. if subscriptions_count == 0:
  225. return 0
  226. else:
  227. return monthly_share/subscriptions_count
  228. class Service(AbstractResource):
  229. """ A service we sell
  230. (considered monthly)
  231. """
  232. costs = models.ManyToManyField(
  233. Cost,
  234. through=CostUse,
  235. related_name='using_services',
  236. verbose_name='coûts mensuels associés')
  237. goods = models.ManyToManyField(
  238. Good,
  239. through=GoodUse,
  240. related_name='using_services',
  241. verbose_name="matériels et frais d'accès utilisés")
  242. subscriptions_count = models.PositiveIntegerField(
  243. "Nombre d'abonnements",
  244. default=0)
  245. reusable = models.BooleanField(
  246. default=False,
  247. help_text="Peut-être utilisé par d'autres services")
  248. @property
  249. def price(self):
  250. return self.get_prices()['total_recurring_price']
  251. def save(self, *args, **kwargs):
  252. if self.reusable:
  253. self.capacity_unit = self.UNIT_SERVICE
  254. self.total_capacity = self.subscriptions_count
  255. return super().save(*args, **kwargs)
  256. def get_absolute_url(self):
  257. return reverse('detail-service', kwargs={'pk': self.pk})
  258. def get_use_class(self):
  259. return ServiceUse
  260. def get_prices(self):
  261. costs_uses = CostUse.objects.filter(service=self)
  262. goods_uses = GoodUse.objects.filter(service=self)
  263. services_uses = ServiceUse.objects.filter(service=self)
  264. total_recurring_price = sum(chain(
  265. (i.monthly_provision_share() for i in goods_uses),
  266. (i.cost_share() for i in costs_uses),
  267. (i.cost_share() for i in services_uses)
  268. ))
  269. total_goods_value_share = sum(
  270. (i.value_share() for i in chain(goods_uses, services_uses)))
  271. if self.subscriptions_count == 0:
  272. unit_recurring_price = 0
  273. unit_goods_value_share = 0
  274. else:
  275. unit_recurring_price = \
  276. total_recurring_price/self.subscriptions_count
  277. unit_goods_value_share = \
  278. total_goods_value_share/self.subscriptions_count
  279. unit_staggered_goods_share = \
  280. unit_goods_value_share/settings.SETUP_COST_STAGGERING_MONTHS
  281. return {
  282. 'total_recurring_price': total_recurring_price,
  283. 'total_goods_value_share': total_goods_value_share,
  284. 'unit_goods_value_share': unit_goods_value_share,
  285. 'unit_recurring_price': unit_recurring_price,
  286. 'unit_staggered_goods_share': unit_staggered_goods_share,
  287. 'unit_consolidated_cost': (
  288. unit_staggered_goods_share + unit_recurring_price),
  289. }
  290. def validate_reusable_service(v):
  291. if not Service.objects.get(pk=v).reusable:
  292. raise ValidationError('{} is not a reusable service'.format(v))
  293. class ServiceUse(AbstractUse):
  294. class Meta:
  295. verbose_name = 'service utilisé'
  296. verbose_name_plural = 'services utilisés'
  297. resource = models.ForeignKey(
  298. Service, related_name='dependent_services',
  299. limit_choices_to={'reusable': True},
  300. validators=[validate_reusable_service])
  301. def cost_share(self):
  302. return (
  303. self.share / self.resource.total_capacity
  304. * self.resource.price
  305. )
  306. def unit_cost_share(self):
  307. subscriptions_count = self.service.subscriptions_count
  308. if subscriptions_count == 0:
  309. return 0
  310. else:
  311. return self.cost_share()/self.service.subscriptions_count
  312. def value_share(self):
  313. return self.share*self.resource.get_prices()['unit_goods_value_share']
  314. def clean(self):
  315. """ Checks for cycles in service using services
  316. """
  317. start_resource = self.resource
  318. def crawl(service):
  319. for use in service.dependent_services.all():
  320. if use.service == start_resource:
  321. raise ValidationError(
  322. 'Cycle detected in services using services')
  323. else:
  324. crawl(use.service)
  325. crawl(self.service)