2016-05-17 13:31:41 +00:00
|
|
|
from django.core.management.base import BaseCommand
|
|
|
|
from shop.pdf import generate_pdf_letter
|
|
|
|
from shop.email import send_invoice_email
|
|
|
|
|
|
|
|
|
|
|
|
class Command(BaseCommand):
|
|
|
|
args = 'none'
|
2016-05-30 14:58:55 +00:00
|
|
|
help = 'Send out invoices that have not been sent yet'
|
2016-05-17 13:31:41 +00:00
|
|
|
|
|
|
|
def handle(self, *args, **options):
|
|
|
|
self.stdout.write('Invoice worker running...')
|
|
|
|
while True:
|
|
|
|
### check if we need to generate any invoices
|
|
|
|
for order in Order.objects.filter(paid=True, invoice__isnull=True):
|
|
|
|
### generate invoice for this Order
|
|
|
|
Invoice.objects.create(order=order)
|
2016-05-30 14:58:55 +00:00
|
|
|
self.stdout.write('Generated Invoice object for order %s' % order)
|
|
|
|
|
|
|
|
### check if we need to generate any pdf invoices
|
|
|
|
for invoice in Invoice.objects.filter(pdf_generated=False):
|
|
|
|
# put the dict with data for the pdf together
|
|
|
|
formatdict = {
|
|
|
|
'invoice': invoice,
|
|
|
|
}
|
|
|
|
# generate the pdf
|
2016-05-17 13:31:41 +00:00
|
|
|
try:
|
2016-05-30 14:58:55 +00:00
|
|
|
pdffile = generate_pdf_letter(
|
|
|
|
filename=invoice.filename,
|
|
|
|
template='invoice.html',
|
|
|
|
formatdict=formatdict,
|
|
|
|
)
|
|
|
|
self.stdout.write('Generated pdf for invoice %s' % invoice)
|
2016-05-17 13:31:41 +00:00
|
|
|
except Exception as E:
|
2016-05-30 14:58:55 +00:00
|
|
|
self.stdout.write('ERROR: Unable to generate PDF file for invoice #%s. Error: %s' % (invoice.pk, E))
|
2016-05-17 13:31:41 +00:00
|
|
|
continue
|
2016-05-30 14:58:55 +00:00
|
|
|
# so, do we have a pdf?
|
2016-05-17 13:31:41 +00:00
|
|
|
if not pdffile:
|
2016-05-30 14:58:55 +00:00
|
|
|
self.stdout.write('ERROR: Unable to generate PDF file for invoice #%s' % invoice.pk)
|
2016-05-17 13:31:41 +00:00
|
|
|
continue
|
|
|
|
|
2016-05-30 14:58:55 +00:00
|
|
|
# update invoice object
|
|
|
|
invoice.pdf_generated=True
|
|
|
|
invoice.save()
|
|
|
|
|
|
|
|
### check if we need to send out any invoices
|
|
|
|
for invoice in Invoice.objects.filter(sent_to_customer=False, pdf_generated=True):
|
|
|
|
# read the pdf invoice from the archive
|
|
|
|
with open(settings.INVOICE_ARCHIVE_PATH+invoice.filename, 'r') as fh:
|
|
|
|
pdffile = fh.read()
|
|
|
|
|
|
|
|
# send the email
|
|
|
|
if send_invoice_email(invoice=invoice, attachment=pdffile):
|
2016-05-17 13:31:41 +00:00
|
|
|
self.stdout.write('OK: Invoice email sent to %s' % order.user.email)
|
|
|
|
invoice.sent_to_customer=True
|
|
|
|
invoice.save()
|
|
|
|
else:
|
2016-05-30 14:58:55 +00:00
|
|
|
self.stdout.write('ERROR: Unable to send invoice email for order %s to %s' % (order.pk, order.user.email))
|
2016-05-17 13:31:41 +00:00
|
|
|
|
|
|
|
### pause for a bit
|
|
|
|
sleep(60)
|
|
|
|
|
|
|
|
|