Features: 1) Added arith template tags for sub and neg operations to support arithmetic in templates;

Fixes: 1) Replaced `add:-X` with `sub:X` in template logic for consistent arithmetic;

Extra: 1) Added `arith` to template load context; 2) Introduced `_to_float` helper for safe type conversion; 3) Used `suppress` to handle invalid conversions gracefully.
This commit is contained in:
Egor Pavlovich Gorbunov 2025-11-17 15:59:39 +03:00
parent 08340c801a
commit be9940cdc0
2 changed files with 25 additions and 3 deletions

View file

@ -1,5 +1,5 @@
{% extends 'admin/base.html' %} {% extends 'admin/base.html' %}
{% load i18n unfold static %} {% load i18n unfold static arith %}
{% block title %} {% block title %}
{% if subtitle %} {% if subtitle %}
@ -68,7 +68,7 @@
{% endcomponent %} {% endcomponent %}
{% if total and total > 0 %} {% if total and total > 0 %}
{% with net=revenue_net_30|default:0 %} {% with net=revenue_net_30|default:0 %}
{% with tax_amt=gross|add:-net %} {% with tax_amt=gross|sub:net %}
{% with returns_capped=returns %} {% with returns_capped=returns %}
{% if returns > gross %} {% if returns > gross %}
{% with returns_capped=gross %}{% endwith %} {% with returns_capped=gross %}{% endwith %}
@ -77,7 +77,7 @@
{% if tax_amt_pos < 0 %} {% if tax_amt_pos < 0 %}
{% with tax_amt_pos=0 %}{% endwith %} {% with tax_amt_pos=0 %}{% endwith %}
{% endif %} {% endif %}
{% with net_for_pie=gross|add:-tax_amt_pos|add:-returns_capped %} {% with net_for_pie=gross|sub:tax_amt_pos|sub:returns_capped %}
{% if net_for_pie < 0 %} {% if net_for_pie < 0 %}
{% with net_for_pie=0 %}{% endwith %} {% with net_for_pie=0 %}{% endwith %}
{% endif %} {% endif %}

View file

@ -0,0 +1,22 @@
from contextlib import suppress
from django import template
register = template.Library()
def _to_float(val: object) -> float:
conv: float = 0.0
with suppress(Exception):
return float(val) # type: ignore [arg-type]
return conv
@register.filter(name="sub")
def sub(value: object, arg: object) -> float:
return _to_float(value) - _to_float(arg)
@register.filter(name="neg")
def neg(value: object) -> float:
return -_to_float(value)