|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +import logging |
| 3 | +from decimal import Decimal |
| 4 | + |
| 5 | +from django.conf import settings |
| 6 | +from django.core.mail import EmailMessage |
| 7 | +from django.template import Context |
| 8 | +from django.template.loader import get_template |
| 9 | +from django.utils import timezone |
| 10 | +from holviapi.utils import barcode as bank_barcode |
| 11 | +from holviapp.utils import list_invoices |
| 12 | + |
| 13 | +from .models import NotificationSent |
| 14 | + |
| 15 | +logger = logger.getLogger() |
| 16 | + |
| 17 | + |
| 18 | +class HolviOverdueInvoicesHandler(object): |
| 19 | + def process_overdue(self, send=False): |
| 20 | + barcode_iban = settings.HOLVI_BARCODE_IBAN |
| 21 | + body_template = get_template('velkoja/notification_email_body.jinja') |
| 22 | + subject_template = get_template('velkoja/notification_email_subject.jinja') |
| 23 | + overdue = list_invoices(status='overdue') |
| 24 | + ret = [] |
| 25 | + for invoice in overdue: |
| 26 | + # Quick check to make sure the invoice has not been credited |
| 27 | + if float(invoice._jsondata.get('credited_sum')) > 0: |
| 28 | + continue |
| 29 | + # If we have already sent notification recently, do not sent one just yet |
| 30 | + if NotificationSent.objects.filter(transaction_unique_id=invoice.code).count(): |
| 31 | + notified = NotificationSent.objects.get(transaction_unique_id=invoice.code) |
| 32 | + if (timezone.now() - notified.stamp).days < settings.HOLVI_NOTIFICATION_INTERVAL_DAYS: |
| 33 | + continue |
| 34 | + |
| 35 | + if send: |
| 36 | + invoice.send() |
| 37 | + |
| 38 | + barcode = None |
| 39 | + if barcode_iban: |
| 40 | + barcode = bank_barcode(barcode_iban, invoice.rf_reference, Decimal(invoice.due_sum)) |
| 41 | + |
| 42 | + mail = EmailMessage() |
| 43 | + mail.subject = subject_template.render(Context({"invoice": invoice, "barcode": barcode})).strip() |
| 44 | + mail.body = body_template.render(Context({"invoice": invoice, "barcode": barcode})) |
| 45 | + mail.to = [invoice.receiver.email] |
| 46 | + if send: |
| 47 | + try: |
| 48 | + mail.send() |
| 49 | + except Exception as e: |
| 50 | + logger.exception("Sending email failed") |
| 51 | + |
| 52 | + try: |
| 53 | + notified = NotificationSent.objects.get(transaction_unique_id=invoice.code) |
| 54 | + notified.notification_no += 1 |
| 55 | + except NotificationSent.DoesNotExist: |
| 56 | + notified = NotificationSent() |
| 57 | + notified.transaction_unique_id = invoice.code |
| 58 | + notified.stamp = timezone.now() |
| 59 | + notified.email = invoice.receiver.email |
| 60 | + if send: |
| 61 | + notified.save() |
| 62 | + ret.append((notified, invoice)) |
| 63 | + return ret |
0 commit comments