Created
March 12, 2024 06:10
-
-
Save ijharulislam/a2c910369a2565b7ee5ad71cfb34360c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@login_required | |
def income_statement_pdf(request): | |
from weasyprint import HTML | |
items = Transactions.objects.filter(institute_id=request.session['institute_id']) | |
from_date = request.GET.get("from_date", "").strip() | |
to_date = request.GET.get("to_date", "").strip() | |
account_id = request.GET.get("account") | |
from_date = parse(from_date) if from_date else datetime.datetime.now() - relativedelta(days=2) | |
to_date = parse(to_date) if to_date else datetime.datetime.now() | |
items = items.filter(date__gte=from_date, date__lte=to_date) | |
total_income = items.aggregate(total_income=Sum("income"))["total_income"] | |
total_expense = items.aggregate(total_expense=Sum("expense"))["total_expense"] | |
if total_income and total_expense: | |
total_balance = total_income - total_expense | |
else: | |
total_balance = 0 | |
if account_id: | |
items = items.filter(account_id=account_id) | |
template = PdfTemplate.objects.get(name="income_statement") | |
institute = Institute.objects.get(id=request.session['institute_id']) | |
today = datetime.datetime.now() | |
data = { | |
"institute": institute, | |
"items": items.iterator(), | |
"today": today, | |
"from_date": from_date, | |
"to_date": to_date, | |
"total_income": total_income, | |
"total_expense": total_expense, | |
"total_balance": total_balance, | |
"host": request.get_host(), | |
} | |
tpl = Template(template.html_content) | |
html_string = tpl.render(Context(data)) | |
# Creating http response | |
response = HttpResponse(content_type='application/pdf;') | |
response['Content-Disposition'] = f'inline; filename=Income Statement.pdf' | |
HTML(string=html_string, base_url=request.build_absolute_uri()).write_pdf(response) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment