django-orchestra/orchestra/apps/orders/billing.py

69 lines
2.7 KiB
Python
Raw Normal View History

2014-09-03 13:56:02 +00:00
import datetime
from django.utils.translation import ugettext_lazy as _
2014-09-11 14:00:20 +00:00
from orchestra.apps.bills.models import Invoice, Fee, ProForma, BillLine, BillSubline
2014-09-03 13:56:02 +00:00
class BillsBackend(object):
2014-09-11 14:00:20 +00:00
def create_bills(self, account, lines, **options):
bill = None
2014-09-03 14:51:07 +00:00
bills = []
2014-09-19 14:47:25 +00:00
create_new = options.get('new_open', False)
2014-09-22 15:59:53 +00:00
proforma = options.get('proforma', False)
2014-09-10 16:53:09 +00:00
for line in lines:
service = line.order.service
2014-09-11 14:00:20 +00:00
# Create bill if needed
if bill is None or service.is_fee:
2014-09-22 15:59:53 +00:00
if proforma:
2014-09-11 14:00:20 +00:00
if create_new:
bill = ProForma.objects.create(account=account)
else:
2014-09-22 15:59:53 +00:00
bill = ProForma.objects.filter(account=account, is_open=True).last()
if not bill:
bill = ProForma.objects.create(account=account, is_open=True)
2014-09-11 14:00:20 +00:00
elif service.is_fee:
bill = Fee.objects.create(account=account)
else:
if create_new:
bill = Invoice.objects.create(account=account)
else:
2014-09-22 15:59:53 +00:00
bill = Invoice.objects.filter(account=account, is_open=True).last()
if not bill:
bill = Invoice.objects.create(account=account, is_open=True)
2014-09-11 14:00:20 +00:00
bills.append(bill)
# Create bill line
billine = bill.lines.create(
2014-09-03 13:56:02 +00:00
rate=service.nominal_price,
2014-09-18 15:07:39 +00:00
quantity=line.size,
subtotal=line.subtotal,
2014-09-03 13:56:02 +00:00
tax=service.tax,
2014-09-11 14:00:20 +00:00
description=self.get_line_description(line),
)
self.create_sublines(billine, line.discounts)
2014-09-03 14:51:07 +00:00
return bills
2014-09-03 13:56:02 +00:00
def format_period(self, ini, end):
2014-09-10 16:53:09 +00:00
ini = ini.strftime("%b, %Y")
end = (end-datetime.timedelta(seconds=1)).strftime("%b, %Y")
if ini == end:
return ini
return _("{ini} to {end}").format(ini=ini, end=end)
2014-09-11 14:00:20 +00:00
def get_line_description(self, line):
service = line.order.service
if service.is_fee:
return self.format_period(line.ini, line.end)
else:
description = line.order.description
if service.billing_period != service.NEVER:
description += " %s" % self.format_period(line.ini, line.end)
return description
2014-09-03 13:56:02 +00:00
def create_sublines(self, line, discounts):
2014-09-10 16:53:09 +00:00
for discount in discounts:
2014-09-03 13:56:02 +00:00
line.sublines.create(
2014-09-10 16:53:09 +00:00
description=_("Discount per %s") % discount.type,
total=discount.total,
2014-09-03 13:56:02 +00:00
)