models.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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', 'A payer'),
  91. ('closed', 'Reglé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. default=end_of_month,
  108. null=True,
  109. verbose_name="date d'échéance de paiement")
  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_remaining_to_pay(self):
  142. """
  143. Calcul le montant restant à payer
  144. """
  145. return self.amount() - self.amount_paid
  146. amount_remaining_to_pay.short_description = 'Reste à payer'
  147. def has_owner(self, username):
  148. """
  149. Check if passed username (ex gmajax) is owner of the invoice
  150. """
  151. return (self.member and self.member.username == username)
  152. def generate_pdf(self):
  153. """
  154. Make and store a pdf file for the invoice
  155. """
  156. context = {"invoice": self}
  157. context.update(branding(None))
  158. pdf_file = render_as_pdf('billing/invoice_pdf.html', context)
  159. self.pdf.save('%s.pdf' % self.number, pdf_file)
  160. @transaction.atomic
  161. def validate(self):
  162. """
  163. Switch invoice to validate mode. This set to False the draft field
  164. and generate the pdf
  165. """
  166. self.date = datetime.date.today()
  167. old_number = self.number
  168. self.number = Invoice.objects.get_next_invoice_number(self.date)
  169. self.validated = True
  170. self.save()
  171. self.generate_pdf()
  172. accounting_log.info("Draft invoice %s validated as invoice %s. "
  173. "(Total amount : %f ; Member : %s)"
  174. % (old_number, self.number, self.amount(), self.member))
  175. assert self.pdf_exists()
  176. if self.member is not None:
  177. update_accounting_for_member(self.member)
  178. def pdf_exists(self):
  179. return (self.validated
  180. and bool(self.pdf)
  181. and private_files_storage.exists(self.pdf.name))
  182. def get_absolute_url(self):
  183. return reverse('billing:invoice', args=[self.number])
  184. def __unicode__(self):
  185. return '#%s %0.2f€ %s' % (self.number, self.amount(), self.date_due)
  186. def reminder_needed(self):
  187. # If there's no member, there's nobody to be reminded
  188. if self.member is None:
  189. return False
  190. # If bill is close or not validated yet, nope
  191. if self.status != 'open' or not self.validated:
  192. return False
  193. # If bill is not at least one month old, nope
  194. if self.date_due >= timezone.now()+relativedelta(weeks=-4):
  195. return False
  196. # If a reminder has been recently sent, nope
  197. if (self.date_last_reminder_email
  198. and (self.date_last_reminder_email
  199. >= timezone.now() + relativedelta(weeks=-3))):
  200. return False
  201. return True
  202. def send_reminder(self, auto=False):
  203. """ Envoie un courrier pour rappeler à un abonné qu'une facture est
  204. en attente de paiement
  205. :param bill: id of the bill to remind
  206. :param auto: is it an auto email? (changes slightly template content)
  207. """
  208. if not self.reminder_needed():
  209. return False
  210. accounting_log.info("Sending reminder email to %s to pay invoice %s"
  211. % (str(self.member), str(self.number)))
  212. isp_info = ISPInfo.objects.first()
  213. kwargs = {}
  214. # Il peut ne pas y avir d'ISPInfo, ou bien pas d'administrative_email
  215. if isp_info and isp_info.administrative_email:
  216. kwargs['from_email'] = isp_info.administrative_email
  217. # Si le dernier courriel de relance a été envoyé il y a moins de trois
  218. # semaines, n'envoi pas un nouveau courriel
  219. send_templated_email(
  220. to=self.member.email,
  221. subject_template='billing/emails/reminder_for_unpaid_bill.txt',
  222. body_template='billing/emails/reminder_for_unpaid_bill.html',
  223. context={'member': self.member, 'branding': isp_info,
  224. 'membership_info_url': settings.MEMBER_MEMBERSHIP_INFO_URL,
  225. 'today': datetime.date.today,
  226. 'auto_sent': auto},
  227. **kwargs)
  228. # Sauvegarde en base la date du dernier envoi de mail de relance
  229. self.date_last_reminder_email = timezone.now()
  230. self.save()
  231. return True
  232. class Meta:
  233. verbose_name = 'facture'
  234. objects = InvoiceQuerySet().as_manager()
  235. class InvoiceDetail(models.Model):
  236. label = models.CharField(max_length=100)
  237. amount = models.DecimalField(max_digits=5, decimal_places=2,
  238. verbose_name='montant')
  239. quantity = models.DecimalField(null=True, verbose_name='quantité',
  240. default=1.0, decimal_places=2, max_digits=4)
  241. tax = models.DecimalField(null=True, default=0.0, decimal_places=2,
  242. max_digits=4, verbose_name='TVA',
  243. help_text='en %')
  244. invoice = models.ForeignKey(Invoice, verbose_name='facture',
  245. related_name='details')
  246. offersubscription = models.ForeignKey(OfferSubscription, null=True,
  247. blank=True, default=None,
  248. verbose_name='abonnement')
  249. period_from = models.DateField(
  250. default=start_of_month,
  251. null=True,
  252. blank=True,
  253. verbose_name='début de période',
  254. help_text='Date de début de période sur laquelle est facturé cet item')
  255. period_to = models.DateField(
  256. default=end_of_month,
  257. null=True,
  258. blank=True,
  259. verbose_name='fin de période',
  260. help_text='Date de fin de période sur laquelle est facturé cet item')
  261. def __unicode__(self):
  262. return self.label
  263. def total(self):
  264. """Calcul le total"""
  265. return (self.amount * (self.tax / Decimal('100.0') +
  266. Decimal('1.0')) *
  267. self.quantity).quantize(Decimal('0.01'))
  268. class Meta:
  269. verbose_name = 'détail de facture'
  270. class Payment(models.Model):
  271. PAYMENT_MEAN_CHOICES = (
  272. ('cash', 'Espèces'),
  273. ('check', 'Chèque'),
  274. ('transfer', 'Virement'),
  275. ('other', 'Autre')
  276. )
  277. member = models.ForeignKey(Member, null=True, blank=True, default=None,
  278. related_name='payments',
  279. verbose_name='membre',
  280. on_delete=models.SET_NULL)
  281. payment_mean = models.CharField(max_length=100, null=True,
  282. default='transfer',
  283. choices=PAYMENT_MEAN_CHOICES,
  284. verbose_name='moyen de paiement')
  285. amount = models.DecimalField(max_digits=5, decimal_places=2, null=True,
  286. verbose_name='montant')
  287. date = models.DateField(default=datetime.date.today)
  288. invoice = models.ForeignKey(Invoice, verbose_name='facture associée', null=True,
  289. blank=True, related_name='payments')
  290. amount_already_allocated = models.DecimalField(max_digits=5,
  291. decimal_places=2,
  292. null=True, blank=True, default=0.0,
  293. verbose_name='montant déjà alloué')
  294. label = models.CharField(max_length=500,
  295. null=True, blank=True, default="",
  296. verbose_name='libellé')
  297. def save(self, *args, **kwargs):
  298. # Only if no amount already allocated...
  299. if self.amount_already_allocated == 0:
  300. # If there's a linked invoice and no member defined
  301. if self.invoice and not self.member:
  302. # Automatically set member to invoice's member
  303. self.member = self.invoice.member
  304. super(Payment, self).save(*args, **kwargs)
  305. def clean(self):
  306. # Only if no amount already allocated...
  307. if self.amount_already_allocated == 0:
  308. # If there's a linked invoice and this payment would pay more than
  309. # the remaining amount needed to pay the invoice...
  310. if self.invoice and self.amount > self.invoice.amount_remaining_to_pay():
  311. raise ValidationError("This payment would pay more than the invoice's remaining to pay")
  312. def amount_not_allocated(self):
  313. return self.amount - self.amount_already_allocated
  314. @transaction.atomic
  315. def allocate_to_invoice(self, invoice):
  316. amount_can_pay = self.amount_not_allocated()
  317. amount_to_pay = invoice.amount_remaining_to_pay()
  318. amount_to_allocate = min(amount_can_pay, amount_to_pay)
  319. accounting_log.info("Allocating %f from payment %s to invoice %s"
  320. % (float(amount_to_allocate), str(self.date),
  321. invoice.number))
  322. self.amount_already_allocated += amount_to_allocate
  323. invoice.amount_paid += amount_to_allocate
  324. # Close invoice if relevant
  325. if (invoice.amount_remaining_to_pay() <= 0) and (invoice.status == "open"):
  326. accounting_log.info("Invoice %s has been paid and is now closed"
  327. % invoice.number)
  328. invoice.status = "closed"
  329. invoice.save()
  330. self.save()
  331. def __unicode__(self):
  332. if self.member is not None:
  333. return 'Paiment de %0.2f€ le %s par %s' \
  334. % (self.amount, str(self.date), self.member)
  335. else:
  336. return 'Paiment de %0.2f€ le %s' \
  337. % (self.amount, str(self.date))
  338. class Meta:
  339. verbose_name = 'paiement'
  340. def get_active_payment_and_invoices(member):
  341. # Fetch relevant and active payments / invoices
  342. # and sort then by chronological order : olders first, newers last.
  343. this_member_invoices = [i for i in member.invoices.filter(validated=True).order_by("date")]
  344. this_member_payments = [p for p in member.payments.order_by("date")]
  345. # TODO / FIXME ^^^ maybe also consider only 'opened' invoices (i.e. not
  346. # conflict / trouble invoices)
  347. active_payments = [p for p in this_member_payments if p.amount_not_allocated() > 0]
  348. active_invoices = [p for p in this_member_invoices if p.amount_remaining_to_pay() > 0]
  349. return active_payments, active_invoices
  350. def update_accounting_for_member(member):
  351. """
  352. Met à jour le status des factures, des paiements et le solde du compte
  353. d'un utilisateur
  354. """
  355. accounting_log.info("Updating accounting for member %s ..."
  356. % str(member))
  357. accounting_log.info("Member %s current balance is %f ..."
  358. % (str(member), float(member.balance)))
  359. reconcile_invoices_and_payments(member)
  360. this_member_invoices = [i for i in member.invoices.filter(validated=True).order_by("date")]
  361. this_member_payments = [p for p in member.payments.order_by("date")]
  362. member.balance = compute_balance(this_member_invoices,
  363. this_member_payments)
  364. member.save()
  365. accounting_log.info("Member %s new balance is %f"
  366. % (str(member), float(member.balance)))
  367. def reconcile_invoices_and_payments(member):
  368. """
  369. Rapproche des factures et des paiements qui sont actifs (paiement non alloué
  370. ou factures non entièrement payées) automatiquement.
  371. """
  372. active_payments, active_invoices = get_active_payment_and_invoices(member)
  373. if active_payments == []:
  374. accounting_log.info("(No active payment for %s. No invoice/payment "
  375. "reconciliation needed.)."
  376. % str(member))
  377. return
  378. elif active_invoices == []:
  379. accounting_log.info("(No active invoice for %s. No invoice/payment "
  380. "reconciliation needed.)."
  381. % str(member))
  382. return
  383. accounting_log.info("Initiating reconciliation between "
  384. "invoice and payments for %s" % str(member))
  385. while active_payments != [] and active_invoices != []:
  386. # Only consider the oldest active payment and the oldest active invoice
  387. p = active_payments[0]
  388. # If this payment is to be allocated for a specific invoice...
  389. if p.invoice:
  390. # Assert that the invoice is still 'active'
  391. assert p.invoice in active_invoices
  392. i = p.invoice
  393. accounting_log.info("Payment is to be allocated specifically to " \
  394. "invoice %s" % str(i.number))
  395. else:
  396. i = active_invoices[0]
  397. # TODO : should add an assert that the ammount not allocated / remaining to
  398. # pay is lower before and after calling the allocate_to_invoice
  399. p.allocate_to_invoice(i)
  400. active_payments, active_invoices = get_active_payment_and_invoices(member)
  401. if active_payments == []:
  402. accounting_log.info("No more active payment. Nothing to reconcile anymore.")
  403. elif active_invoices == []:
  404. accounting_log.info("No more active invoice. Nothing to reconcile anymore.")
  405. return
  406. def compute_balance(invoices, payments):
  407. active_payments = [p for p in payments if p.amount_not_allocated() > 0]
  408. active_invoices = [i for i in invoices if i.amount_remaining_to_pay() > 0]
  409. s = 0
  410. s -= sum([i.amount_remaining_to_pay() for i in active_invoices])
  411. s += sum([p.amount_not_allocated() for p in active_payments])
  412. return s
  413. @receiver(post_save, sender=Payment)
  414. @disable_for_loaddata
  415. def payment_changed(sender, instance, created, **kwargs):
  416. if created:
  417. accounting_log.info("Adding payment %s (Date: %s, Member: %s, Amount: %s, Label: %s)."
  418. % (instance.pk, instance.date, instance.member,
  419. instance.amount, instance.label.encode('utf-8')))
  420. else:
  421. accounting_log.info("Updating payment %s (Date: %s, Member: %s, Amount: %s, Label: %s, Allocated: %s)."
  422. % (instance.pk, instance.date, instance.member,
  423. instance.amount, instance.label.encode('utf-8'),
  424. instance.amount_already_allocated))
  425. # If this payment is related to a member, update the accounting for
  426. # this member
  427. if (created or instance.amount_not_allocated != 0) \
  428. and (instance.member is not None):
  429. update_accounting_for_member(instance.member)
  430. @receiver(post_save, sender=Invoice)
  431. @disable_for_loaddata
  432. def invoice_changed(sender, instance, created, **kwargs):
  433. if created:
  434. accounting_log.info("Creating draft invoice %s (Member: %s)."
  435. % ('DRAFT-{}'.format(instance.pk), instance.member))
  436. else:
  437. if not instance.validated:
  438. accounting_log.info("Updating draft invoice %s (Member: %s)."
  439. % (instance.number, instance.member))
  440. else:
  441. accounting_log.info("Updating invoice %s (Member: %s, Total amount: %s, Amount paid: %s)."
  442. % (instance.number, instance.member, instance.amount(), instance.amount_paid ))
  443. def test_accounting_update():
  444. Member.objects.all().delete()
  445. Payment.objects.all().delete()
  446. Invoice.objects.all().delete()
  447. johndoe = Member.objects.create(username="johndoe",
  448. first_name="John",
  449. last_name="Doe",
  450. email="johndoe@yolo.test")
  451. johndoe.set_password("trololo")
  452. # First facture
  453. invoice = Invoice.objects.create(number="1337",
  454. member=johndoe)
  455. InvoiceDetail.objects.create(label="superservice",
  456. amount="15.0",
  457. invoice=invoice)
  458. invoice.validate()
  459. # Second facture
  460. invoice2 = Invoice.objects.create(number="42",
  461. member=johndoe)
  462. InvoiceDetail.objects.create(label="superservice",
  463. amount="42",
  464. invoice=invoice2)
  465. invoice2.validate()
  466. # Payment
  467. payment = Payment.objects.create(amount=20,
  468. member=johndoe)
  469. Member.objects.all().delete()
  470. Payment.objects.all().delete()
  471. Invoice.objects.all().delete()