models.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from django.db import models
  4. from django.db.models import Q
  5. from django.conf import settings
  6. from django.utils import timezone
  7. from .fields import MACAddressField
  8. class ItemType(models.Model):
  9. name = models.CharField(max_length=100, verbose_name='nom')
  10. def __unicode__(self):
  11. return self.name
  12. class Meta:
  13. verbose_name = 'type d’objet'
  14. verbose_name_plural = 'types d’objet'
  15. class ItemQuerySet(models.QuerySet):
  16. def _get_borrowed_pks(self):
  17. return Loan.objects.running().values_list('item', flat=True)
  18. def available(self):
  19. return self.exclude(
  20. pk__in=self._get_borrowed_pks()).exclude(deployed=True)
  21. def borrowed(self):
  22. return self.filter(pk__in=self._get_borrowed_pks())
  23. def deployed(self):
  24. return self.filter(deployed=True)
  25. def unavailable(self):
  26. """ deployed or borrowed
  27. """
  28. return self.filter(
  29. Q(pk__in=self._get_borrowed_pks()) |
  30. Q(deployed=True))
  31. class Item(models.Model):
  32. type = models.ForeignKey(ItemType, verbose_name='type de matériel',
  33. related_name='items')
  34. designation = models.CharField(max_length=100, verbose_name='désignation')
  35. storage = models.ForeignKey(
  36. 'Storage', related_name='items',
  37. verbose_name='Lieu de stockage',
  38. null=True, blank=True,
  39. help_text='Laisser vide si inconnu')
  40. mac_address = MACAddressField(
  41. verbose_name='adresse MAC',
  42. blank=True, null=True, unique=True,
  43. help_text="préférable au n° de série si possible")
  44. serial = models.CharField(
  45. verbose_name='N° de série',
  46. max_length=250, blank=True, null=True, unique=True,
  47. help_text='ou toute autre référence unique')
  48. buy_date = models.DateField(verbose_name='date d’achat' , blank=True , null=True)
  49. owner = models.ForeignKey(
  50. settings.AUTH_USER_MODEL,
  51. verbose_name='Propriétaire',
  52. related_name='items',
  53. null=True, blank=True,
  54. help_text="dans le cas de matériel n'appartenant pas à l'association")
  55. deployed = models.BooleanField(verbose_name='déployé', default=False,
  56. help_text='Cocher si le matériel est en production')
  57. comment = models.TextField(verbose_name='commentaire', blank=True,
  58. null=True)
  59. objects = ItemQuerySet().as_manager()
  60. def __unicode__(self):
  61. return self.designation
  62. def save(self, *args, **kwargs):
  63. # workaround for unique=True, null=True
  64. # see https://code.djangoproject.com/ticket/4136#comment:33
  65. self.mac_address = self.mac_address or None
  66. self.serial = self.serial or None
  67. return super(Item, self).save(*args, **kwargs)
  68. def get_current_loan(self):
  69. """
  70. Returns the current Loan for this Item, if exists, or None.
  71. """
  72. try:
  73. return self.loans.get(loan_date_end__isnull=True)
  74. except Loan.DoesNotExist:
  75. return None
  76. def is_available(self):
  77. """
  78. Returns the status of the Item. If a running loan exists,
  79. or if the item is deployed, returns False (else True).
  80. """
  81. return (not self.deployed) and (not self.loans.running().exists())
  82. is_available.boolean = True
  83. is_available.short_description = 'disponible'
  84. def get_mac_and_serial(self):
  85. mac = self.mac_address
  86. serial = self.serial
  87. if mac and serial:
  88. return "{} / {}".format(mac, serial)
  89. else:
  90. return mac or serial or ''
  91. class Meta:
  92. verbose_name = 'objet'
  93. def give_back(self, storage=None):
  94. self.storage = storage
  95. self.save()
  96. self.loans.running().update(
  97. loan_date_end=timezone.now())
  98. class LoanQuerySet(models.QuerySet):
  99. @staticmethod
  100. def _running_filter():
  101. return (
  102. models.Q(loan_date_end__gt=timezone.now()) |
  103. models.Q(loan_date_end__isnull=True))
  104. def running(self):
  105. return self.filter(self._running_filter())
  106. def finished(self):
  107. return self.exclude(self._running_filter())
  108. class Loan(models.Model):
  109. item = models.ForeignKey(Item, verbose_name='objet', related_name='loans')
  110. user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='membre',
  111. related_name='loans')
  112. loan_date = models.DateTimeField(verbose_name='date de prêt')
  113. loan_date_end = models.DateTimeField(verbose_name='date de fin de prêt',
  114. null=True, blank=True)
  115. notes = models.TextField(null=True, blank=True)
  116. def __unicode__(self):
  117. return 'prêt de {item} à {user}'.format(
  118. item=self.item, user=self.user)
  119. def get_mac_and_serial(self):
  120. return self.item.get_mac_and_serial()
  121. get_mac_and_serial.short_description = "Adresse MAC / n° de série"
  122. def user_can_close(self, user):
  123. return (not self.item.is_available()) and (self.user == user)
  124. def is_running(self):
  125. return not self.loan_date_end or self.loan_date_end > timezone.now()
  126. is_running.boolean = True
  127. is_running.short_description = 'En cours ?'
  128. class Meta:
  129. verbose_name = 'prêt d’objet'
  130. verbose_name_plural = 'prêts d’objets'
  131. objects = LoanQuerySet().as_manager()
  132. class Storage(models.Model):
  133. name = models.CharField(max_length=100, verbose_name='nom')
  134. notes = models.TextField(
  135. blank=True,
  136. help_text='Lisible par tous les adhérents')
  137. def __unicode__(self):
  138. return self.name
  139. def items_count(self):
  140. return self.items.count()
  141. items_count.short_description = 'Nb. items stockés'
  142. class Meta:
  143. verbose_name = 'lieu de stockage'
  144. verbose_name_plural = 'lieux de stockage'