uncloud/uncloud_pay/admin.py
2020-09-28 21:34:24 +02:00

98 lines
3.1 KiB
Python

from django.contrib import admin
from django.template.response import TemplateResponse
from django.urls import path
from django.shortcuts import render
from django.conf.urls import url
from uncloud_pay.views import BillViewSet
from hardcopy import bytestring_to_pdf
from django.core.files.temp import NamedTemporaryFile
from django.http import FileResponse
from django.template.loader import render_to_string
from uncloud_pay.models import Bill, Order, BillRecord, BillingAddress, Product
class BillRecordInline(admin.TabularInline):
# model = Bill.bill_records.through
model = BillRecord
# AT some point in the future: expose REPLACED and orders that depend on us
# class OrderInline(admin.TabularInline):
# model = Order
# fk_name = "replaces"
# class OrderAdmin(admin.ModelAdmin):
# inlines = [ OrderInline ]
class BillAdmin(admin.ModelAdmin):
inlines = [ BillRecordInline ]
def get_urls(self):
"""
Create URLs for PDF view
"""
info = "%s_%s" % (self.model._meta.app_label, self.model._meta.model_name)
pat = lambda regex, fn: url(regex, self.admin_site.admin_view(fn), name='%s_%s' % (info, fn.__name__))
url_patterns = [
pat(r'^([0-9]+)/as_pdf/$', self.as_pdf),
pat(r'^([0-9]+)/as_html/$', self.as_html),
] + super().get_urls()
return url_patterns
def as_pdf(self, request, object_id):
bill = self.get_object(request, object_id=object_id)
print(bill)
if bill is None:
raise self._get_404_exception(object_id)
output_file = NamedTemporaryFile()
bill_html = render_to_string("bill.html.j2", {'bill': bill,
'bill_records': bill.billrecord_set.all()
})
bytestring_to_pdf(bill_html.encode('utf-8'), output_file)
response = FileResponse(output_file, content_type="application/pdf")
response['Content-Disposition'] = f'filename="bill_{bill}.pdf"'
return response
def as_html(self, request, object_id):
bill = self.get_object(request, object_id=object_id)
if bill is None:
raise self._get_404_exception(object_id)
return render(request, 'bill.html.j2',
{'bill': bill,
'bill_records': bill.billrecord_set.all()
})
bill_html = render_to_string("bill.html.j2", {'bill': bill,
'bill_records': bill.billrecord_set.all()
})
bytestring_to_pdf(bill_html.encode('utf-8'), output_file)
response = FileResponse(output_file, content_type="application/pdf")
response['Content-Disposition'] = f'filename="bill_{bill}.pdf"'
return HttpResponse(template.render(context, request))
return response
admin.site.register(Bill, BillAdmin)
admin.site.register(Order)
admin.site.register(BillRecord)
admin.site.register(BillingAddress)
#for m in [ SampleOneTimeProduct, SampleRecurringProduct, SampleRecurringProductOneTimeFee ]:
admin.site.register(Product)
#admin.site.register(Order, OrderAdmin)