2013-11-15 19:42:31 +00:00
|
|
|
from datetime import datetime
|
|
|
|
from jinja2 import Environment, FileSystemLoader
|
2013-11-18 19:49:54 +00:00
|
|
|
from xhtml2pdf import pisa
|
|
|
|
import StringIO
|
2013-11-15 19:42:31 +00:00
|
|
|
|
|
|
|
jinja_options = {
|
|
|
|
"loader": FileSystemLoader('util'),
|
|
|
|
}
|
|
|
|
|
|
|
|
env = Environment(**jinja_options)
|
|
|
|
|
2013-11-18 19:49:54 +00:00
|
|
|
|
|
|
|
def renderInvoiceToPdf(invoice, user):
|
|
|
|
""" Renders a nice PDF display for the given invoice. """
|
|
|
|
sourceHtml = renderInvoiceToHtml(invoice, user)
|
|
|
|
output = StringIO.StringIO()
|
|
|
|
pisaStatus = pisa.CreatePDF(sourceHtml, dest=output)
|
|
|
|
if pisaStatus.err:
|
|
|
|
return None
|
2014-11-24 21:07:38 +00:00
|
|
|
|
2013-11-18 19:49:54 +00:00
|
|
|
value = output.getvalue()
|
|
|
|
output.close()
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
2013-11-15 19:42:31 +00:00
|
|
|
def renderInvoiceToHtml(invoice, user):
|
|
|
|
""" Renders a nice HTML display for the given invoice. """
|
2015-06-12 16:32:41 +00:00
|
|
|
from endpoints.api.billing import get_invoice_fields
|
|
|
|
|
2013-11-15 19:42:31 +00:00
|
|
|
def get_price(price):
|
|
|
|
if not price:
|
|
|
|
return '$0'
|
|
|
|
|
2013-11-15 20:31:05 +00:00
|
|
|
return '$' + '{0:.2f}'.format(float(price) / 100)
|
2013-11-15 19:42:31 +00:00
|
|
|
|
|
|
|
def get_range(line):
|
|
|
|
if line.period and line.period.start and line.period.end:
|
2014-11-24 21:07:38 +00:00
|
|
|
return ': ' + format_date(line.period.start) + ' - ' + format_date(line.period.end)
|
2013-11-15 19:42:31 +00:00
|
|
|
return ''
|
|
|
|
|
|
|
|
def format_date(timestamp):
|
|
|
|
return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d')
|
|
|
|
|
|
|
|
data = {
|
|
|
|
'user': user.username,
|
|
|
|
'invoice': invoice,
|
|
|
|
'invoice_date': format_date(invoice.date),
|
|
|
|
'getPrice': get_price,
|
2015-06-12 16:32:41 +00:00
|
|
|
'getRange': get_range,
|
|
|
|
'custom_fields': get_invoice_fields(user)[0],
|
2014-11-24 21:07:38 +00:00
|
|
|
}
|
|
|
|
|
2013-11-15 19:42:31 +00:00
|
|
|
template = env.get_template('invoice.tmpl')
|
|
|
|
rendered = template.render(data)
|
|
|
|
return rendered
|