models.py 15 KB

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