models.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import datetime
  4. import random
  5. import uuid
  6. import os
  7. import re
  8. from decimal import Decimal
  9. from django.db import models, transaction
  10. from django.db.models.signals import post_save
  11. from django.dispatch import receiver
  12. from django.utils.encoding import python_2_unicode_compatible
  13. from coin.offers.models import OfferSubscription
  14. from coin.members.models import Member
  15. from coin.html2pdf import render_as_pdf
  16. from coin.utils import private_files_storage, start_of_month, end_of_month, \
  17. disable_for_loaddata, postgresql_regexp
  18. from coin.isp_database.context_processors import branding
  19. def invoice_pdf_filename(instance, filename):
  20. """Nom et chemin du fichier pdf à stocker pour les factures"""
  21. member_id = instance.member.id if instance.member else 0
  22. return 'invoices/%d_%s_%s.pdf' % (member_id,
  23. instance.number,
  24. uuid.uuid4())
  25. @python_2_unicode_compatible
  26. class InvoiceNumber:
  27. """ Logic and validation of invoice numbers
  28. Defines invoice numbers serie in a way that is legal in france.
  29. https://www.service-public.fr/professionnels-entreprises/vosdroits/F23208#fiche-item-3
  30. Our format is YYYY-MM-XXXXXX
  31. - YYYY the year of the bill
  32. - MM month of the bill
  33. - XXXXXX a per-month sequence
  34. """
  35. RE_INVOICE_NUMBER = re.compile(
  36. r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<index>\d{6})')
  37. def __init__(self, date, index):
  38. self.date = date
  39. self.index = index
  40. def get_next(self):
  41. return InvoiceNumber(self.date, self.index + 1)
  42. def __str__(self):
  43. return '{:%Y-%m}-{:0>6}'.format(self.date, self.index)
  44. @classmethod
  45. def parse(cls, string):
  46. m = cls.RE_INVOICE_NUMBER.match(string)
  47. if not m:
  48. raise ValueError('Not a valid invoice number: "{}"'.format(string))
  49. return cls(
  50. datetime.date(
  51. year=int(m.group('year')),
  52. month=int(m.group('month')),
  53. day=1),
  54. int(m.group('index')))
  55. @staticmethod
  56. def time_sequence_filter(date, field_name='date'):
  57. """ Build queryset filter to be used to get the invoices from the
  58. numbering sequence of a given date.
  59. :param field_name: the invoice field name to filter on.
  60. :type date: datetime
  61. :rtype: dict
  62. """
  63. return {'{}__month'.format(field_name): date.month}
  64. class InvoiceQuerySet(models.QuerySet):
  65. def get_next_invoice_number(self, date):
  66. last_invoice_number_str = self._get_last_invoice_number(date)
  67. if last_invoice_number_str is None:
  68. # It's the first bill of the month
  69. invoice_number = InvoiceNumber(date, 1)
  70. else:
  71. invoice_number = InvoiceNumber.parse(last_invoice_number_str).get_next()
  72. return str(invoice_number)
  73. def _get_last_invoice_number(self, date):
  74. same_seq_filter = InvoiceNumber.time_sequence_filter(date)
  75. return self.filter(**same_seq_filter).with_valid_number().aggregate(
  76. models.Max('number'))['number__max']
  77. def with_valid_number(self):
  78. """ Excludes previous numbering schemes or draft invoices
  79. """
  80. return self.filter(number__regex=postgresql_regexp(
  81. InvoiceNumber.RE_INVOICE_NUMBER))
  82. class Invoice(models.Model):
  83. INVOICES_STATUS_CHOICES = (
  84. ('open', 'A payer'),
  85. ('closed', 'Reglée'),
  86. ('trouble', 'Litige')
  87. )
  88. validated = models.BooleanField(default=False, verbose_name='validée',
  89. help_text='Once validated, a PDF is generated'
  90. ' and the invoice cannot be modified')
  91. number = models.CharField(max_length=25,
  92. unique=True,
  93. verbose_name='numéro')
  94. status = models.CharField(max_length=50, choices=INVOICES_STATUS_CHOICES,
  95. default='open',
  96. verbose_name='statut')
  97. date = models.DateField(
  98. default=datetime.date.today, null=True, verbose_name='date',
  99. help_text='Cette date sera définie à la date de validation dans la facture finale')
  100. date_due = models.DateField(
  101. default=end_of_month,
  102. null=True,
  103. verbose_name="date d'échéance de paiement")
  104. member = models.ForeignKey(Member, null=True, blank=True, default=None,
  105. related_name='invoices',
  106. verbose_name='membre',
  107. on_delete=models.SET_NULL)
  108. pdf = models.FileField(storage=private_files_storage,
  109. upload_to=invoice_pdf_filename,
  110. null=True, blank=True,
  111. verbose_name='PDF')
  112. def save(self, *args, **kwargs):
  113. # First save to get a PK
  114. super(Invoice, self).save(*args, **kwargs)
  115. # Then use that pk to build draft invoice number
  116. if not self.validated and self.pk and not self.number:
  117. self.number = 'DRAFT-{}'.format(self.pk)
  118. self.save()
  119. def amount(self):
  120. """
  121. Calcul le montant de la facture
  122. en fonction des éléments de détails
  123. """
  124. total = Decimal('0.0')
  125. for detail in self.details.all():
  126. total += detail.total()
  127. return total.quantize(Decimal('0.01'))
  128. amount.short_description = 'Montant'
  129. def amount_before_tax(self):
  130. total = Decimal('0.0')
  131. for detail in self.details.all():
  132. total += detail.amount
  133. return total.quantize(Decimal('0.01'))
  134. amount.short_description = 'Montant HT'
  135. def amount_paid(self):
  136. """
  137. Calcul le montant payé de la facture en fonction des éléments
  138. de paiements
  139. """
  140. total = Decimal('0.0')
  141. for payment in self.payments.all():
  142. total += payment.amount
  143. return total.quantize(Decimal('0.01'))
  144. amount_paid.short_description = 'Montant payé'
  145. def amount_remaining_to_pay(self):
  146. """
  147. Calcul le montant restant à payer
  148. """
  149. return self.amount() - self.amount_paid()
  150. amount_remaining_to_pay.short_description = 'Reste à payer'
  151. def has_owner(self, username):
  152. """
  153. Check if passed username (ex gmajax) is owner of the invoice
  154. """
  155. return (self.member and self.member.username == username)
  156. def generate_pdf(self):
  157. """
  158. Make and store a pdf file for the invoice
  159. """
  160. context = {"invoice": self}
  161. context.update(branding(None))
  162. pdf_file = render_as_pdf('billing/invoice_pdf.html', context)
  163. self.pdf.save('%s.pdf' % self.number, pdf_file)
  164. @transaction.atomic
  165. def validate(self):
  166. """
  167. Switch invoice to validate mode. This set to False the draft field
  168. and generate the pdf
  169. """
  170. self.date = datetime.date.today()
  171. self.number = Invoice.objects.get_next_invoice_number(self.date)
  172. self.validated = True
  173. self.save()
  174. self.generate_pdf()
  175. assert self.pdf_exists()
  176. def pdf_exists(self):
  177. return (self.validated
  178. and bool(self.pdf)
  179. and private_files_storage.exists(self.pdf.name))
  180. def get_absolute_url(self):
  181. from django.core.urlresolvers import reverse
  182. return reverse('billing:invoice', args=[self.number])
  183. def __unicode__(self):
  184. return '#%s %0.2f€ %s' % (self.number, self.amount(), self.date_due)
  185. class Meta:
  186. verbose_name = 'facture'
  187. objects = InvoiceQuerySet().as_manager()
  188. class InvoiceDetail(models.Model):
  189. label = models.CharField(max_length=100)
  190. amount = models.DecimalField(max_digits=5, decimal_places=2,
  191. verbose_name='montant')
  192. quantity = models.DecimalField(null=True, verbose_name='quantité',
  193. default=1.0, decimal_places=2, max_digits=4)
  194. tax = models.DecimalField(null=True, default=0.0, decimal_places=2,
  195. max_digits=4, verbose_name='TVA',
  196. help_text='en %')
  197. invoice = models.ForeignKey(Invoice, verbose_name='facture',
  198. related_name='details')
  199. offersubscription = models.ForeignKey(OfferSubscription, null=True,
  200. blank=True, default=None,
  201. verbose_name='abonnement')
  202. period_from = models.DateField(
  203. default=start_of_month,
  204. null=True,
  205. blank=True,
  206. verbose_name='début de période',
  207. help_text='Date de début de période sur laquelle est facturé cet item')
  208. period_to = models.DateField(
  209. default=end_of_month,
  210. null=True,
  211. blank=True,
  212. verbose_name='fin de période',
  213. help_text='Date de fin de période sur laquelle est facturé cet item')
  214. def __unicode__(self):
  215. return self.label
  216. def total(self):
  217. """Calcul le total"""
  218. return (self.amount * (self.tax / Decimal('100.0') +
  219. Decimal('1.0')) *
  220. self.quantity).quantize(Decimal('0.01'))
  221. class Meta:
  222. verbose_name = 'détail de facture'
  223. class Payment(models.Model):
  224. PAYMENT_MEAN_CHOICES = (
  225. ('cash', 'Espèces'),
  226. ('check', 'Chèque'),
  227. ('transfer', 'Virement'),
  228. ('other', 'Autre')
  229. )
  230. payment_mean = models.CharField(max_length=100, null=True,
  231. default='transfer',
  232. choices=PAYMENT_MEAN_CHOICES,
  233. verbose_name='moyen de paiement')
  234. amount = models.DecimalField(max_digits=5, decimal_places=2, null=True,
  235. verbose_name='montant')
  236. date = models.DateField(default=datetime.date.today)
  237. invoice = models.ForeignKey(Invoice, verbose_name='facture',
  238. related_name='payments')
  239. def __unicode__(self):
  240. return 'Paiment de %0.2f€' % self.amount
  241. class Meta:
  242. verbose_name = 'paiement'
  243. @receiver(post_save, sender=Payment)
  244. @disable_for_loaddata
  245. def set_invoice_as_paid_if_needed(sender, instance, **kwargs):
  246. """
  247. Lorsqu'un paiement est enregistré, vérifie si la facture est alors
  248. complétement payée. Dans ce cas elle passe en réglée
  249. """
  250. if (instance.invoice.amount_paid >= instance.invoice.amount and
  251. instance.invoice.status == 'open'):
  252. instance.invoice.status = 'closed'
  253. instance.invoice.save()