models.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import datetime
  4. import logging
  5. import uuid
  6. import re
  7. from decimal import Decimal
  8. from dateutil.relativedelta import relativedelta
  9. from django.conf import settings
  10. from django.db import models, transaction
  11. from django.utils import timezone
  12. from django.utils.encoding import python_2_unicode_compatible
  13. from django.dispatch import receiver
  14. from django.db.models.signals import post_save
  15. from django.core.exceptions import ValidationError
  16. from django.core.urlresolvers import reverse
  17. from coin.offers.models import OfferSubscription
  18. from coin.members.models import Member
  19. from coin.html2pdf import render_as_pdf
  20. from coin.utils import private_files_storage, start_of_month, end_of_month, \
  21. postgresql_regexp, send_templated_email
  22. from coin.isp_database.context_processors import branding
  23. from coin.isp_database.models import ISPInfo
  24. accounting_log = logging.getLogger("coin.billing")
  25. def invoice_pdf_filename(instance, filename):
  26. """Nom et chemin du fichier pdf à stocker pour les factures"""
  27. member_id = instance.member.id if instance.member else 0
  28. return 'invoices/%d_%s_%s.pdf' % (member_id,
  29. instance.number,
  30. uuid.uuid4())
  31. @python_2_unicode_compatible
  32. class InvoiceNumber:
  33. """ Logic and validation of invoice numbers
  34. Defines invoice numbers serie in a way that is legal in france.
  35. https://www.service-public.fr/professionnels-entreprises/vosdroits/F23208#fiche-item-3
  36. Our format is YYYY-MM-XXXXXX
  37. - YYYY the year of the bill
  38. - MM month of the bill
  39. - XXXXXX a per-month sequence
  40. """
  41. RE_INVOICE_NUMBER = re.compile(
  42. r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<index>\d{6})')
  43. def __init__(self, date, index):
  44. self.date = date
  45. self.index = index
  46. def get_next(self):
  47. return InvoiceNumber(self.date, self.index + 1)
  48. def __str__(self):
  49. return '{:%Y-%m}-{:0>6}'.format(self.date, self.index)
  50. @classmethod
  51. def parse(cls, string):
  52. m = cls.RE_INVOICE_NUMBER.match(string)
  53. if not m:
  54. raise ValueError('Not a valid invoice number: "{}"'.format(string))
  55. return cls(
  56. datetime.date(
  57. year=int(m.group('year')),
  58. month=int(m.group('month')),
  59. day=1),
  60. int(m.group('index')))
  61. @staticmethod
  62. def time_sequence_filter(date, field_name='date'):
  63. """ Build queryset filter to be used to get the invoices from the
  64. numbering sequence of a given date.
  65. :param field_name: the invoice field name to filter on.
  66. :type date: datetime
  67. :rtype: dict
  68. """
  69. return {'{}__month'.format(field_name): date.month}
  70. class InvoiceQuerySet(models.QuerySet):
  71. def get_next_invoice_number(self, date):
  72. last_invoice_number_str = self._get_last_invoice_number(date)
  73. if last_invoice_number_str is None:
  74. # It's the first bill of the month
  75. invoice_number = InvoiceNumber(date, 1)
  76. else:
  77. invoice_number = InvoiceNumber.parse(last_invoice_number_str).get_next()
  78. return str(invoice_number)
  79. def _get_last_invoice_number(self, date):
  80. same_seq_filter = InvoiceNumber.time_sequence_filter(date)
  81. return self.filter(**same_seq_filter).with_valid_number().aggregate(
  82. models.Max('number'))['number__max']
  83. def with_valid_number(self):
  84. """ Excludes previous numbering schemes or draft invoices
  85. """
  86. return self.filter(number__regex=postgresql_regexp(
  87. InvoiceNumber.RE_INVOICE_NUMBER))
  88. class Invoice(models.Model):
  89. INVOICES_STATUS_CHOICES = (
  90. ('open', 'À payer'),
  91. ('closed', 'Réglée'),
  92. ('trouble', 'Litige')
  93. )
  94. validated = models.BooleanField(default=False, verbose_name='validée',
  95. help_text='Once validated, a PDF is generated'
  96. ' and the invoice cannot be modified')
  97. number = models.CharField(max_length=25,
  98. unique=True,
  99. verbose_name='numéro')
  100. status = models.CharField(max_length=50, choices=INVOICES_STATUS_CHOICES,
  101. default='open',
  102. verbose_name='statut')
  103. date = models.DateField(
  104. default=datetime.date.today, null=True, verbose_name='date',
  105. help_text='Cette date sera définie à la date de validation dans la facture finale')
  106. date_due = models.DateField(
  107. null=True, blank=True,
  108. verbose_name="date d'échéance de paiement",
  109. help_text='Le délai de paiement sera fixé à {} jours à la validation si laissé vide'.format(settings.PAYMENT_DELAY))
  110. member = models.ForeignKey(Member, null=True, blank=True, default=None,
  111. related_name='invoices',
  112. verbose_name='membre',
  113. on_delete=models.SET_NULL)
  114. pdf = models.FileField(storage=private_files_storage,
  115. upload_to=invoice_pdf_filename,
  116. null=True, blank=True,
  117. verbose_name='PDF')
  118. amount_paid = models.DecimalField(max_digits=5,
  119. decimal_places=2,
  120. default=0,
  121. verbose_name='montant payé')
  122. date_last_reminder_email = models.DateTimeField(null=True, blank=True,
  123. verbose_name="Date du dernier email de relance envoyé")
  124. def save(self, *args, **kwargs):
  125. # First save to get a PK
  126. super(Invoice, self).save(*args, **kwargs)
  127. # Then use that pk to build draft invoice number
  128. if not self.validated and self.pk and not self.number:
  129. self.number = 'DRAFT-{}'.format(self.pk)
  130. self.save()
  131. def amount(self):
  132. """
  133. Calcul le montant de la facture
  134. en fonction des éléments de détails
  135. """
  136. total = Decimal('0.0')
  137. for detail in self.details.all():
  138. total += detail.total()
  139. return total.quantize(Decimal('0.01'))
  140. amount.short_description = 'Montant'
  141. def amount_before_tax(self):
  142. total = Decimal('0.0')
  143. for detail in self.details.all():
  144. total += detail.amount
  145. return total.quantize(Decimal('0.01'))
  146. amount_before_tax.short_description = 'Montant HT'
  147. def amount_paid(self):
  148. """
  149. Calcul le montant payé de la facture en fonction des éléments
  150. de paiements
  151. """
  152. total = Decimal('0.0')
  153. for payment in self.payments.all():
  154. total += payment.amount
  155. return total.quantize(Decimal('0.01'))
  156. amount_paid.short_description = 'Montant payé'
  157. def amount_remaining_to_pay(self):
  158. """
  159. Calcul le montant restant à payer
  160. """
  161. return self.amount() - self.amount_paid
  162. amount_remaining_to_pay.short_description = 'Reste à payer'
  163. def has_owner(self, username):
  164. """
  165. Check if passed username (ex gmajax) is owner of the invoice
  166. """
  167. return (self.member and self.member.username == username)
  168. def generate_pdf(self):
  169. """
  170. Make and store a pdf file for the invoice
  171. """
  172. context = {"invoice": self}
  173. context.update(branding(None))
  174. pdf_file = render_as_pdf('billing/invoice_pdf.html', context)
  175. self.pdf.save('%s.pdf' % self.number, pdf_file)
  176. @transaction.atomic
  177. def validate(self):
  178. """
  179. Switch invoice to validate mode. This set to False the draft field
  180. and generate the pdf
  181. """
  182. self.date = datetime.date.today()
  183. if not self.date_due:
  184. self.date_due = self.date + datetime.timedelta(days=settings.PAYMENT_DELAY)
  185. old_number = self.number
  186. self.number = Invoice.objects.get_next_invoice_number(self.date)
  187. self.validated = True
  188. self.save()
  189. self.generate_pdf()
  190. accounting_log.info("Draft invoice %s validated as invoice %s. "
  191. "(Total amount : %f ; Member : %s)"
  192. % (old_number, self.number, self.amount(), self.member))
  193. assert self.pdf_exists()
  194. if self.member is not None:
  195. update_accounting_for_member(self.member)
  196. def pdf_exists(self):
  197. return (self.validated
  198. and bool(self.pdf)
  199. and private_files_storage.exists(self.pdf.name))
  200. def get_absolute_url(self):
  201. return reverse('billing:invoice', args=[self.number])
  202. def __unicode__(self):
  203. return '#%s %0.2f€ %s' % (self.number, self.amount(), self.date_due)
  204. def reminder_needed(self):
  205. # If there's no member, there's nobody to be reminded
  206. if self.member is None:
  207. return False
  208. # If bill is close or not validated yet, nope
  209. if self.status != 'open' or not self.validated:
  210. return False
  211. # If bill is not at least one month old, nope
  212. if self.date_due >= timezone.now()+relativedelta(weeks=-4):
  213. return False
  214. # If a reminder has been recently sent, nope
  215. if (self.date_last_reminder_email
  216. and (self.date_last_reminder_email
  217. >= timezone.now() + relativedelta(weeks=-3))):
  218. return False
  219. return True
  220. def send_reminder(self, auto=False):
  221. """ Envoie un courrier pour rappeler à un abonné qu'une facture est
  222. en attente de paiement
  223. :param bill: id of the bill to remind
  224. :param auto: is it an auto email? (changes slightly template content)
  225. """
  226. if not self.reminder_needed():
  227. return False
  228. accounting_log.info("Sending reminder email to %s to pay invoice %s"
  229. % (str(self.member), str(self.number)))
  230. isp_info = ISPInfo.objects.first()
  231. kwargs = {}
  232. # Il peut ne pas y avir d'ISPInfo, ou bien pas d'administrative_email
  233. if isp_info and isp_info.administrative_email:
  234. kwargs['from_email'] = isp_info.administrative_email
  235. # Si le dernier courriel de relance a été envoyé il y a moins de trois
  236. # semaines, n'envoi pas un nouveau courriel
  237. send_templated_email(
  238. to=self.member.email,
  239. subject_template='billing/emails/reminder_for_unpaid_bill.txt',
  240. body_template='billing/emails/reminder_for_unpaid_bill.html',
  241. context={'member': self.member, 'branding': isp_info,
  242. 'membership_info_url': settings.MEMBER_MEMBERSHIP_INFO_URL,
  243. 'today': datetime.date.today,
  244. 'auto_sent': auto},
  245. **kwargs)
  246. # Sauvegarde en base la date du dernier envoi de mail de relance
  247. self.date_last_call_for_membership_fees_email = timezone.now()
  248. self.save()
  249. return True
  250. class Meta:
  251. verbose_name = 'facture'
  252. objects = InvoiceQuerySet().as_manager()
  253. class InvoiceDetail(models.Model):
  254. label = models.CharField(max_length=100)
  255. amount = models.DecimalField(max_digits=5, decimal_places=2,
  256. verbose_name='montant')
  257. quantity = models.DecimalField(null=True, verbose_name='quantité',
  258. default=1.0, decimal_places=2, max_digits=4)
  259. tax = models.DecimalField(null=True, default=0.0, decimal_places=2,
  260. max_digits=4, verbose_name='TVA',
  261. help_text='en %')
  262. invoice = models.ForeignKey(Invoice, verbose_name='facture',
  263. related_name='details')
  264. offersubscription = models.ForeignKey(OfferSubscription, null=True,
  265. blank=True, default=None,
  266. verbose_name='abonnement')
  267. period_from = models.DateField(
  268. default=start_of_month,
  269. null=True,
  270. blank=True,
  271. verbose_name='début de période',
  272. help_text='Date de début de période sur laquelle est facturé cet item')
  273. period_to = models.DateField(
  274. default=end_of_month,
  275. null=True,
  276. blank=True,
  277. verbose_name='fin de période',
  278. help_text='Date de fin de période sur laquelle est facturé cet item')
  279. def __unicode__(self):
  280. return self.label
  281. def total(self):
  282. """Calcul le total"""
  283. return (self.amount * (self.tax / Decimal('100.0') +
  284. Decimal('1.0')) *
  285. self.quantity).quantize(Decimal('0.01'))
  286. class Meta:
  287. verbose_name = 'détail de facture'
  288. class Payment(models.Model):
  289. PAYMENT_MEAN_CHOICES = (
  290. ('cash', 'Espèces'),
  291. ('check', 'Chèque'),
  292. ('transfer', 'Virement'),
  293. ('other', 'Autre')
  294. )
  295. member = models.ForeignKey(Member, null=True, blank=True, default=None,
  296. related_name='payments',
  297. verbose_name='membre',
  298. on_delete=models.SET_NULL)
  299. payment_mean = models.CharField(max_length=100, null=True,
  300. default='transfer',
  301. choices=PAYMENT_MEAN_CHOICES,
  302. verbose_name='moyen de paiement')
  303. amount = models.DecimalField(max_digits=5, decimal_places=2, null=True,
  304. verbose_name='montant')
  305. date = models.DateField(default=datetime.date.today)
  306. invoice = models.ForeignKey(Invoice, verbose_name='facture associée', null=True,
  307. blank=True, related_name='payments')
  308. amount_already_allocated = models.DecimalField(max_digits=5,
  309. decimal_places=2,
  310. null=True, blank=True, default=0.0,
  311. verbose_name='montant déjà alloué')
  312. label = models.CharField(max_length=500,
  313. null=True, blank=True, default="",
  314. verbose_name='libellé')
  315. def save(self, *args, **kwargs):
  316. # Only if no amount already allocated...
  317. if self.amount_already_allocated == 0:
  318. # If there's a linked invoice and no member defined
  319. if self.invoice and not self.member:
  320. # Automatically set member to invoice's member
  321. self.member = self.invoice.member
  322. super(Payment, self).save(*args, **kwargs)
  323. def clean(self):
  324. # Only if no amount already allocated...
  325. if self.amount_already_allocated == 0:
  326. # If there's a linked invoice and this payment would pay more than
  327. # the remaining amount needed to pay the invoice...
  328. if self.invoice and self.amount > self.invoice.amount_remaining_to_pay():
  329. raise ValidationError("This payment would pay more than the invoice's remaining to pay")
  330. def amount_not_allocated(self):
  331. return self.amount - self.amount_already_allocated
  332. @transaction.atomic
  333. def allocate_to_invoice(self, invoice):
  334. amount_can_pay = self.amount_not_allocated()
  335. amount_to_pay = invoice.amount_remaining_to_pay()
  336. amount_to_allocate = min(amount_can_pay, amount_to_pay)
  337. accounting_log.info("Allocating %f from payment %s to invoice %s"
  338. % (float(amount_to_allocate), str(self.date),
  339. invoice.number))
  340. self.amount_already_allocated += amount_to_allocate
  341. invoice.amount_paid += amount_to_allocate
  342. # Close invoice if relevant
  343. if (invoice.amount_remaining_to_pay() <= 0) and (invoice.status == "open"):
  344. accounting_log.info("Invoice %s has been paid and is now closed"
  345. % invoice.number)
  346. invoice.status = "closed"
  347. invoice.save()
  348. self.save()
  349. def __unicode__(self):
  350. if self.member is not None:
  351. return 'Paiment de %0.2f€ le %s par %s' \
  352. % (self.amount, str(self.date), self.member)
  353. else:
  354. return 'Paiment de %0.2f€ le %s' \
  355. % (self.amount, str(self.date))
  356. class Meta:
  357. verbose_name = 'paiement'
  358. def get_active_payment_and_invoices(member):
  359. # Fetch relevant and active payments / invoices
  360. # and sort then by chronological order : olders first, newers last.
  361. this_member_invoices = [i for i in member.invoices.filter(validated=True).order_by("date")]
  362. this_member_payments = [p for p in member.payments.order_by("date")]
  363. # TODO / FIXME ^^^ maybe also consider only 'opened' invoices (i.e. not
  364. # conflict / trouble invoices)
  365. active_payments = [p for p in this_member_payments if p.amount_not_allocated() > 0]
  366. active_invoices = [p for p in this_member_invoices if p.amount_remaining_to_pay() > 0]
  367. return active_payments, active_invoices
  368. def update_accounting_for_member(member):
  369. """
  370. Met à jour le status des factures, des paiements et le solde du compte
  371. d'un utilisateur
  372. """
  373. accounting_log.info("Updating accounting for member %s ..."
  374. % str(member))
  375. accounting_log.info("Member %s current balance is %f ..."
  376. % (str(member), float(member.balance)))
  377. reconcile_invoices_and_payments(member)
  378. this_member_invoices = [i for i in member.invoices.filter(validated=True).order_by("date")]
  379. this_member_payments = [p for p in member.payments.order_by("date")]
  380. member.balance = compute_balance(this_member_invoices,
  381. this_member_payments)
  382. member.save()
  383. accounting_log.info("Member %s new balance is %f"
  384. % (str(member), float(member.balance)))
  385. def reconcile_invoices_and_payments(member):
  386. """
  387. Rapproche des factures et des paiements qui sont actifs (paiement non alloué
  388. ou factures non entièrement payées) automatiquement.
  389. """
  390. active_payments, active_invoices = get_active_payment_and_invoices(member)
  391. if active_payments == []:
  392. accounting_log.info("(No active payment for %s. No invoice/payment "
  393. "reconciliation needed.)."
  394. % str(member))
  395. return
  396. elif active_invoices == []:
  397. accounting_log.info("(No active invoice for %s. No invoice/payment "
  398. "reconciliation needed.)."
  399. % str(member))
  400. return
  401. accounting_log.info("Initiating reconciliation between "
  402. "invoice and payments for %s" % str(member))
  403. while active_payments != [] and active_invoices != []:
  404. # Only consider the oldest active payment and the oldest active invoice
  405. p = active_payments[0]
  406. # If this payment is to be allocated for a specific invoice...
  407. if p.invoice:
  408. # Assert that the invoice is still 'active'
  409. assert p.invoice in active_invoices
  410. i = p.invoice
  411. accounting_log.info("Payment is to be allocated specifically to " \
  412. "invoice %s" % str(i.number))
  413. else:
  414. i = active_invoices[0]
  415. # TODO : should add an assert that the ammount not allocated / remaining to
  416. # pay is lower before and after calling the allocate_to_invoice
  417. p.allocate_to_invoice(i)
  418. active_payments, active_invoices = get_active_payment_and_invoices(member)
  419. if active_payments == []:
  420. accounting_log.info("No more active payment. Nothing to reconcile anymore.")
  421. elif active_invoices == []:
  422. accounting_log.info("No more active invoice. Nothing to reconcile anymore.")
  423. return
  424. def compute_balance(invoices, payments):
  425. active_payments = [p for p in payments if p.amount_not_allocated() > 0]
  426. active_invoices = [i for i in invoices if i.amount_remaining_to_pay() > 0]
  427. s = 0
  428. s -= sum([i.amount_remaining_to_pay() for i in active_invoices])
  429. s += sum([p.amount_not_allocated() for p in active_payments])
  430. return s
  431. @receiver(post_save, sender=Payment)
  432. @disable_for_loaddata
  433. def payment_changed(sender, instance, created, **kwargs):
  434. if created:
  435. accounting_log.info("Adding payment %s (Date: %s, Member: %s, Amount: %s, Label: %s)."
  436. % (instance.pk, instance.date, instance.member,
  437. instance.amount, instance.label.encode('utf-8')))
  438. else:
  439. accounting_log.info("Updating payment %s (Date: %s, Member: %s, Amount: %s, Label: %s, Allocated: %s)."
  440. % (instance.pk, instance.date, instance.member,
  441. instance.amount, instance.label.encode('utf-8'),
  442. instance.amount_already_allocated))
  443. # If this payment is related to a member, update the accounting for
  444. # this member
  445. if (created or instance.amount_not_allocated != 0) \
  446. and (instance.member is not None):
  447. update_accounting_for_member(instance.member)
  448. @receiver(post_save, sender=Invoice)
  449. @disable_for_loaddata
  450. def invoice_changed(sender, instance, created, **kwargs):
  451. if created:
  452. accounting_log.info("Creating draft invoice %s (Member: %s)."
  453. % ('DRAFT-{}'.format(instance.pk), instance.member))
  454. else:
  455. if not instance.validated:
  456. accounting_log.info("Updating draft invoice %s (Member: %s)."
  457. % (instance.number, instance.member))
  458. else:
  459. accounting_log.info("Updating invoice %s (Member: %s, Total amount: %s, Amount paid: %s)."
  460. % (instance.number, instance.member, instance.amount(), instance.amount_paid ))
  461. def test_accounting_update():
  462. Member.objects.all().delete()
  463. Payment.objects.all().delete()
  464. Invoice.objects.all().delete()
  465. johndoe = Member.objects.create(username="johndoe",
  466. first_name="John",
  467. last_name="Doe",
  468. email="johndoe@yolo.test")
  469. johndoe.set_password("trololo")
  470. # First facture
  471. invoice = Invoice.objects.create(number="1337",
  472. member=johndoe)
  473. InvoiceDetail.objects.create(label="superservice",
  474. amount="15.0",
  475. invoice=invoice)
  476. invoice.validate()
  477. # Second facture
  478. invoice2 = Invoice.objects.create(number="42",
  479. member=johndoe)
  480. InvoiceDetail.objects.create(label="superservice",
  481. amount="42",
  482. invoice=invoice2)
  483. invoice2.validate()
  484. # Payment
  485. payment = Payment.objects.create(amount=20,
  486. member=johndoe)
  487. Member.objects.all().delete()
  488. Payment.objects.all().delete()
  489. Invoice.objects.all().delete()