models.py 15 KB

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