models.py 15 KB

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