models.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. ordering = ['designation', 'mac_address', 'serial']
  94. def give_back(self, storage=None):
  95. self.storage = storage
  96. self.save()
  97. self.loans.running().update(
  98. loan_date_end=timezone.now())
  99. class LoanQuerySet(models.QuerySet):
  100. @staticmethod
  101. def _running_filter():
  102. return (
  103. models.Q(loan_date_end__gt=timezone.now()) |
  104. models.Q(loan_date_end__isnull=True))
  105. def running(self):
  106. return self.filter(self._running_filter())
  107. def finished(self):
  108. return self.exclude(self._running_filter())
  109. class Loan(models.Model):
  110. item = models.ForeignKey(Item, verbose_name='objet', related_name='loans')
  111. user = models.ForeignKey(
  112. settings.AUTH_USER_MODEL, verbose_name='membre',
  113. related_name='loans', null=True, on_delete=models.SET_NULL)
  114. loan_date = models.DateTimeField(verbose_name='date de prêt')
  115. loan_date_end = models.DateTimeField(verbose_name='date de fin de prêt',
  116. null=True, blank=True)
  117. notes = models.TextField(null=True, blank=True)
  118. def __unicode__(self):
  119. return 'prêt de {item} à {user}'.format(
  120. item=self.item, user=self.user)
  121. def get_mac_and_serial(self):
  122. return self.item.get_mac_and_serial()
  123. get_mac_and_serial.short_description = "Adresse MAC / n° de série"
  124. def user_can_close(self, user):
  125. return (not self.item.is_available()) and (self.user == user)
  126. def is_running(self):
  127. return not self.loan_date_end or self.loan_date_end > timezone.now()
  128. is_running.boolean = True
  129. is_running.short_description = 'En cours ?'
  130. class Meta:
  131. verbose_name = 'prêt d’objet'
  132. verbose_name_plural = 'prêts d’objets'
  133. objects = LoanQuerySet().as_manager()
  134. class Storage(models.Model):
  135. name = models.CharField(max_length=100, verbose_name='nom')
  136. notes = models.TextField(
  137. blank=True,
  138. help_text='Lisible par tous les adhérents')
  139. def __unicode__(self):
  140. return self.name
  141. def items_count(self):
  142. return self.items.count()
  143. items_count.short_description = 'Nb. items stockés'
  144. class Meta:
  145. verbose_name = 'lieu de stockage'
  146. verbose_name_plural = 'lieux de stockage'