models.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. amount_paid = models.DecimalField(max_digits=5, decimal_places=2, default=0,
  113. verbose_name='montant payé')
  114. def save(self, *args, **kwargs):
  115. # First save to get a PK
  116. super(Invoice, self).save(*args, **kwargs)
  117. # Then use that pk to build draft invoice number
  118. if not self.validated and self.pk and not self.number:
  119. self.number = 'DRAFT-{}'.format(self.pk)
  120. self.save()
  121. def amount(self):
  122. """
  123. Calcul le montant de la facture
  124. en fonction des éléments de détails
  125. """
  126. total = Decimal('0.0')
  127. for detail in self.details.all():
  128. total += detail.total()
  129. return total.quantize(Decimal('0.01'))
  130. amount.short_description = 'Montant'
  131. def amount_remaining_to_pay(self):
  132. """
  133. Calcul le montant restant à payer
  134. """
  135. return self.amount() - self.amount_paid
  136. amount_remaining_to_pay.short_description = 'Reste à payer'
  137. def has_owner(self, username):
  138. """
  139. Check if passed username (ex gmajax) is owner of the invoice
  140. """
  141. return (self.member and self.member.username == username)
  142. def generate_pdf(self):
  143. """
  144. Make and store a pdf file for the invoice
  145. """
  146. context = {"invoice": self}
  147. context.update(branding(None))
  148. pdf_file = render_as_pdf('billing/invoice_pdf.html', context)
  149. self.pdf.save('%s.pdf' % self.number, pdf_file)
  150. @transaction.atomic
  151. def validate(self):
  152. """
  153. Switch invoice to validate mode. This set to False the draft field
  154. and generate the pdf
  155. """
  156. self.date = datetime.date.today()
  157. self.number = Invoice.objects.get_next_invoice_number(self.date)
  158. self.validated = True
  159. self.save()
  160. self.generate_pdf()
  161. assert self.pdf_exists()
  162. update_accounting_for_member(self.member)
  163. def pdf_exists(self):
  164. return (self.validated
  165. and bool(self.pdf)
  166. and private_files_storage.exists(self.pdf.name))
  167. def get_absolute_url(self):
  168. from django.core.urlresolvers import reverse
  169. return reverse('billing:invoice', args=[self.number])
  170. def __unicode__(self):
  171. return '#%s %0.2f€ %s' % (self.number, self.amount(), self.date_due)
  172. class Meta:
  173. verbose_name = 'facture'
  174. objects = InvoiceQuerySet().as_manager()
  175. class InvoiceDetail(models.Model):
  176. label = models.CharField(max_length=100)
  177. amount = models.DecimalField(max_digits=5, decimal_places=2,
  178. verbose_name='montant')
  179. quantity = models.DecimalField(null=True, verbose_name='quantité',
  180. default=1.0, decimal_places=2, max_digits=4)
  181. tax = models.DecimalField(null=True, default=0.0, decimal_places=2,
  182. max_digits=4, verbose_name='TVA',
  183. help_text='en %')
  184. invoice = models.ForeignKey(Invoice, verbose_name='facture',
  185. related_name='details')
  186. offersubscription = models.ForeignKey(OfferSubscription, null=True,
  187. blank=True, default=None,
  188. verbose_name='abonnement')
  189. period_from = models.DateField(
  190. default=start_of_month,
  191. null=True,
  192. blank=True,
  193. verbose_name='début de période',
  194. help_text='Date de début de période sur laquelle est facturé cet item')
  195. period_to = models.DateField(
  196. default=end_of_month,
  197. null=True,
  198. blank=True,
  199. verbose_name='fin de période',
  200. help_text='Date de fin de période sur laquelle est facturé cet item')
  201. def __unicode__(self):
  202. return self.label
  203. def total(self):
  204. """Calcul le total"""
  205. return (self.amount * (self.tax / Decimal('100.0') +
  206. Decimal('1.0')) *
  207. self.quantity).quantize(Decimal('0.01'))
  208. class Meta:
  209. verbose_name = 'détail de facture'
  210. class Payment(models.Model):
  211. PAYMENT_MEAN_CHOICES = (
  212. ('cash', 'Espèces'),
  213. ('check', 'Chèque'),
  214. ('transfer', 'Virement'),
  215. ('other', 'Autre')
  216. )
  217. member = models.ForeignKey(Member, null=True, blank=True, default=None,
  218. related_name='payments',
  219. verbose_name='membre',
  220. on_delete=models.SET_NULL)
  221. payment_mean = models.CharField(max_length=100, null=True,
  222. default='transfer',
  223. choices=PAYMENT_MEAN_CHOICES,
  224. verbose_name='moyen de paiement')
  225. amount = models.DecimalField(max_digits=5, decimal_places=2, null=True,
  226. verbose_name='montant')
  227. date = models.DateField(default=datetime.date.today)
  228. invoice = models.ForeignKey(Invoice, verbose_name='facture', null=True,
  229. blank=True, related_name='payments')
  230. amount_already_allocated = models.DecimalField(max_digits=5,
  231. decimal_places=2,
  232. null=True, blank=True, default=0.0,
  233. verbose_name='montant déjà alloué')
  234. label_from_bank = models.CharField(max_length=500,
  235. null=True, blank=True, default="",
  236. verbose_name='libellé du virement récuppéré via la banque')
  237. def save(self, *args, **kwargs):
  238. super(Payment, self).save(*args, **kwargs)
  239. # If this payment is related to a member, update the accounting for
  240. # this member
  241. if self.member != None:
  242. update_accounting_for_member(self.member)
  243. def amount_not_allocated(self):
  244. return self.amount - self.amount_already_allocated
  245. @transaction.atomic
  246. def allocate_to_invoice(self, invoice):
  247. amount_can_pay = self.amount_not_allocated()
  248. amount_to_pay = invoice.amount_remaining_to_pay()
  249. amount_to_allocate = min(amount_can_pay, amount_to_pay)
  250. print "Payment "+str(self.date)+" allocating "+str(amount_to_allocate)+" to invoice "+invoice.number
  251. self.amount_already_allocated += amount_to_allocate
  252. invoice.amount_paid += amount_to_allocate
  253. # Close invoice if relevant
  254. if (invoice.amount_remaining_to_pay() <= 0) and (invoice.status == "open"):
  255. invoice.status = "closed"
  256. invoice.save()
  257. self.save()
  258. def __unicode__(self):
  259. return 'Paiment de %0.2f€ le %s' % (self.amount, str(self.date))
  260. class Meta:
  261. verbose_name = 'paiement'
  262. def update_accounting_for_member(member):
  263. """
  264. Met à jour le status des factures, des paiements et le solde du compte
  265. d'un utilisateur
  266. """
  267. print "Member "+str(member)+" currently has a balance of "+str(member.balance)
  268. # Fetch relevant and active payments / invoices
  269. # and sort then by chronological order : olders first, newers last.
  270. this_member_invoices = [i for i in member.invoices.filter(validated=True)
  271. .order_by("date")]
  272. this_member_payments = [p for p in member.payments.order_by("date")]
  273. # TODO / FIXME ^^^ maybe also consider only 'opened' invoices (i.e. not
  274. # conflict / trouble invoices)
  275. number_of_active_payments = len([p for p in this_member_payments if p.amount_not_allocated() > 0])
  276. number_of_active_invoices = len([p for p in this_member_invoices if p.amount_remaining_to_pay() > 0])
  277. if (number_of_active_payments == 0):
  278. print "No active payment for "+str(member)+". Nothing to do."
  279. elif (number_of_active_invoices == 0):
  280. print "No active invoice for "+str(member)+". Nothing to do."
  281. else:
  282. print "Initiating reconciliation between invoice and payments for user "+str(member)+"."
  283. reconcile_invoices_and_payments(this_member_invoices, this_member_payments)
  284. member.balance = compute_balance(this_member_invoices, this_member_payments)
  285. member.save()
  286. print " "
  287. print "Member "+str(member)+" new balance is "+str(member.balance)
  288. print " "
  289. def reconcile_invoices_and_payments(invoices, payments):
  290. """
  291. Rapproche des factures et des paiements qui sont actifs (paiement non alloué
  292. ou factures non entièrement payées) automatiquement.
  293. Retourne la balance restante (positive si 'trop payé', négative si factures
  294. restantes à payer)
  295. """
  296. active_payments = [p for p in payments if p.amount_not_allocated() > 0]
  297. active_invoices = [i for i in invoices if i.amount_remaining_to_pay() > 0]
  298. #print "Active payment, invoices"
  299. #print active_payments
  300. #print active_invoices
  301. if (len(active_payments) == 0):
  302. print "No more active payment. Nothing to reconcile anymore."
  303. return
  304. if (len(active_invoices) == 0):
  305. print "No more active invoice. Nothing to reconcile anymore."
  306. return
  307. # Only consider the oldest active payment and the oldest active invoice
  308. p = active_payments[0]
  309. i = active_invoices[0]
  310. # TODO : should add an assert that the ammount not allocated / remaining to
  311. # pay is lower before and after calling the allocate_to_invoice
  312. p.allocate_to_invoice(i)
  313. # Reconcicle next payment / invoice
  314. reconcile_invoices_and_payments(invoices, payments)
  315. def compute_balance(invoices, payments):
  316. active_payments = [p for p in payments if p.amount_not_allocated() > 0]
  317. active_invoices = [i for i in invoices if i.amount_remaining_to_pay() > 0]
  318. s = 0
  319. s -= sum([ i.amount_remaining_to_pay() for i in active_invoices ])
  320. s += sum([ p.amount_not_allocated() for p in active_payments ])
  321. return s
  322. def test_accounting_update():
  323. Member.objects.all().delete()
  324. Payment.objects.all().delete()
  325. Invoice.objects.all().delete()
  326. johndoe = Member.objects.create(username="johndoe",
  327. first_name="John",
  328. last_name="Doe",
  329. email="johndoe@yolo.test")
  330. johndoe.set_password("trololo")
  331. # First facture
  332. invoice = Invoice.objects.create(number="1337",
  333. member=johndoe)
  334. InvoiceDetail.objects.create(label="superservice",
  335. amount="15.0",
  336. invoice=invoice)
  337. invoice.validate()
  338. # Second facture
  339. invoice2 = Invoice.objects.create(number="42",
  340. member=johndoe)
  341. InvoiceDetail.objects.create(label="superservice",
  342. amount="42",
  343. invoice=invoice2)
  344. invoice2.validate()
  345. # Payment
  346. payment = Payment.objects.create(amount=20,
  347. member=johndoe)
  348. Member.objects.all().delete()
  349. Payment.objects.all().delete()
  350. Invoice.objects.all().delete()