models.py 13 KB

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