models.py 15 KB

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