amoralesch / hledger-db-grafana

Import hledger journals to a DB and inspect them using Grafana
MIT License
2 stars 0 forks source link

debt-to-income ratio panel not showing correctly #20

Open BardenB opened 2 months ago

BardenB commented 2 months ago

I have found that unless there is already income in the hledger file at a date before the date range of the debt-to-income panel, there is a division by zero error.

For example, when looking at a date range of this year so far, unless there is income on January 1, the debt-to-income panel will not work (assuming you have liabilities that carry over from the previous year). However, this issue is resolved with inaccurate accounting practices, such as a 'paycheck' on January 1 with just $1. This does mess up the averages of the ratio, and make the first part look odd, but it does work.

I wonder if there can be an if statement in there that does not start calculating the ratio until income is reported to resolve this issue correctly.

amoralesch commented 2 months ago

I see, the issue is that there are liabilities but no income at that point of time.

A quick hack would be to change the SQL query that generates the graph, the original query is similar to this:

select
    a.date,
    -1 * sum(case when a.account = 'Liabilities' then balance else 0 end) as "Liabilities",
    -1 * sum(case when a.account = 'Income' then balance else 0 end) as "Income",
    (
        sum(case when a.account = 'Liabilities' then balance else 0 end) /
        sum(case when a.account = 'Income' then balance else 0 end)
    ) as "Ratio"
-- more lines

We can change the line sum(case when a.account = 'Income' then balance else 0 end) (the divisor part) to this: nullif(sum(case when a.account = 'Income' then balance else 0 end), 0). In this case, the division will be # / null, and this just returns null, nothing will be printed at that point of time in the graph, but at least it won't throw any error.

Let me see if there is a way to implement the if solution that you suggested.