Revised the view of the ledger summary and replaced the raw SQL query with the Django model query in the accounting transaction.

This commit is contained in:
依瑪貓 2020-07-18 07:46:01 +08:00
parent ff9146c8b1
commit a15a359ca7

View File

@ -22,7 +22,8 @@ import re
from datetime import timedelta from datetime import timedelta
from django.db import connection from django.db import connection
from django.db.models import Sum from django.db.models import Sum, Case, When, F
from django.db.models.functions import TruncMonth
from django.http import HttpResponseRedirect, Http404 from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render from django.shortcuts import render
from django.urls import reverse from django.urls import reverse
@ -465,25 +466,26 @@ def ledger_summary(request, subject_code):
if current_subject is None: if current_subject is None:
raise Http404() raise Http404()
# The accounting records # The accounting records
if connection.vendor == "postgresql": records = [RecordSummary(
month_definition = "CAST(DATE_TRUNC('month', t.date) AS date)" month=x["month"],
elif connection.vendor == "sqlite": debit_amount=x["debit"] if x["debit"] is not None else 0,
month_definition = "DATE(t.date, 'start of month')" credit_amount=x["credit"] if x["credit"] is not None else 0,
else: balance=x["balance"],
month_definition = None ) for x in Record.objects\
records = list(RecordSummary.objects.raw( .filter(subject__code__startswith=current_subject.code)\
f"""SELECT .annotate(month=TruncMonth("transaction__date"))\
{month_definition} AS month, .values("month")\
SUM(CASE WHEN r.is_credit THEN 0 ELSE r.amount END) AS debit_amount, .order_by("month")\
SUM(CASE WHEN r.is_credit THEN r.amount ELSE 0 END) AS credit_amount, .annotate(
SUM(CASE WHEN r.is_credit THEN -1 ELSE 1 END * r.amount) AS balance debit=Sum(Case(
FROM accounting_records AS r When(is_credit=False, then=F("amount"))),
INNER JOIN accounting_transactions AS t ON r.transaction_sn = t.sn default=0),
INNER JOIN accounting_subjects AS s ON r.subject_sn = s.sn credit=Sum(Case(
WHERE s.code LIKE %s When(is_credit=True, then=F("amount"))),
GROUP BY month default=0),
ORDER BY month""", balance=Sum(Case(
[current_subject.code + "%"])) When(is_credit=False, then=F("amount")),
default=-F("amount"))))]
cumulative_balance = 0 cumulative_balance = 0
for record in records: for record in records:
cumulative_balance = cumulative_balance + record.balance cumulative_balance = cumulative_balance + record.balance