Minor enhancements

* refactors eco account rest surface calculation into designated method get_available_rest()
* refactors placeholder setter for BaseForm
* adds automatic eco account identifier generating on saving
* fixes ServerMessageImportance template tag
pull/9/head
mipel 3 years ago
parent 5f85f49636
commit c8b6d001ef

@ -67,6 +67,7 @@ class NewPaymentForm(BaseModalForm):
self.intervention = self.instance
self.form_title = _("Payment")
self.form_caption = _("Add a payment for intervention '{}'").format(self.intervention.title)
self.add_placeholder_for_field("amount", "0,00")
def save(self):
with transaction.atomic():
@ -110,6 +111,7 @@ class NewStateModalForm(BaseModalForm):
super().__init__(*args, **kwargs)
self.form_title = _("New state")
self.form_caption = _("Insert data for the new state")
self.add_placeholder_for_field("surface", "0,00")
def save(self, is_before_state: bool = False):
with transaction.atomic():
@ -286,6 +288,7 @@ class NewActionModalForm(BaseModalForm):
super().__init__(*args, **kwargs)
self.form_title = _("New action")
self.form_caption = _("Insert data for the new action")
self.add_placeholder_for_field("amount", "0,00")
def save(self):
with transaction.atomic():

@ -12,7 +12,8 @@ from django.db.models import Sum
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _
from compensation.settings import COMPENSATION_IDENTIFIER_LENGTH, COMPENSATION_IDENTIFIER_TEMPLATE
from compensation.settings import COMPENSATION_IDENTIFIER_LENGTH, COMPENSATION_IDENTIFIER_TEMPLATE, \
ECO_ACCOUNT_IDENTIFIER_LENGTH, ECO_ACCOUNT_IDENTIFIER_TEMPLATE
from intervention.models import Intervention, ResponsibilityData
from konova.models import BaseObject, BaseResource, Geometry, UuidModel
from konova.settings import DEFAULT_SRID_RLP, LANIS_LINK_TEMPLATE
@ -218,13 +219,44 @@ class EcoAccount(AbstractCompensation):
def __str__(self):
return "{}".format(self.identifier)
def save(self, *args, **kwargs):
if self.identifier is None or len(self.identifier) == 0:
# Create new identifier
new_id = self._generate_new_identifier()
while EcoAccount.objects.filter(identifier=new_id).exists():
new_id = self._generate_new_identifier()
self.identifier = new_id
super().save(*args, **kwargs)
def get_surface_withdraws(self) -> float:
""" Calculates the compensation's/account's surface
Returns:
sum_surface (float)
"""
return self.withdraws.all().aggregate(Sum("surface"))["surface__sum"]
return self.withdraws.all().aggregate(Sum("surface"))["surface__sum"] or 0
def get_available_rest(self, as_percentage: bool = False):
""" Calculates available rest surface of the eco account
Args:
as_percentage (bool): Whether to return the result as or %
Returns:
"""
ret_val = 0
withdraws = self.withdraws.all()
withdraw_surfaces = withdraws.aggregate(Sum("surface"))["surface__sum"] or 0
after_states_surfaces = self.after_states.all().aggregate(Sum("surface"))["surface__sum"] or withdraw_surfaces ## no division by zero
ret_val = after_states_surfaces - withdraw_surfaces
if as_percentage:
if after_states_surfaces > 0:
ret_val = int((ret_val / after_states_surfaces) * 100)
else:
ret_val = 0
return ret_val
def get_LANIS_link(self) -> str:
""" Generates a link for LANIS depending on the geometry
@ -252,6 +284,22 @@ class EcoAccount(AbstractCompensation):
# ToDo
pass
@staticmethod
def _generate_new_identifier() -> str:
""" Generates a new identifier for the intervention object
Returns:
str
"""
curr_month = str(now().month)
curr_year = str(now().year)
rand_str = generate_random_string(
length=ECO_ACCOUNT_IDENTIFIER_LENGTH,
only_numbers=True,
)
_str = "{}{}{}".format(curr_month, curr_year, rand_str)
return ECO_ACCOUNT_IDENTIFIER_TEMPLATE.format(_str)
class EcoAccountWithdraw(BaseResource):
"""

@ -6,4 +6,6 @@ Created on: 18.12.20
"""
COMPENSATION_IDENTIFIER_LENGTH = 10
COMPENSATION_IDENTIFIER_TEMPLATE = "KOM-{}"
COMPENSATION_IDENTIFIER_TEMPLATE = "KOM-{}"
ECO_ACCOUNT_IDENTIFIER_LENGTH = 10
ECO_ACCOUNT_IDENTIFIER_TEMPLATE = "OEK-{}"

@ -238,10 +238,7 @@ class EcoAccountTable(BaseTable):
Returns:
"""
withdraws = record.withdraws.all()
withdraw_surfaces = withdraws.aggregate(Sum("surface"))["surface__sum"] or 0
after_states_surfaces = record.after_states.all().aggregate(Sum("surface"))["surface__sum"] or withdraw_surfaces ## no division by zero
value = int(((after_states_surfaces - withdraw_surfaces) / after_states_surfaces) * 100)
value = record.get_available_rest(as_percentage=True)
html = render_to_string("konova/custom_widgets/progressbar.html", {"value": value})
return format_html(html)

@ -95,8 +95,7 @@ def open_view(request: HttpRequest, id: str):
diff_states = abs(sum_before_states - sum_after_states)
# Calculate rest of available surface for withdraws
withdraw_surfaces = acc.get_surface_withdraws() or 0
available = int(((sum_after_states - withdraw_surfaces) / sum_after_states) * 100)
available = acc.get_available_rest(as_percentage=True)
context = {
"obj": acc,
@ -106,8 +105,8 @@ def open_view(request: HttpRequest, id: str):
"after_states": after_states,
"sum_before_states": sum_before_states,
"sum_after_states": sum_after_states,
"available": available,
"diff_states": diff_states,
"available": available,
"is_default_member": in_group(_user, DEFAULT_GROUP),
"is_zb_member": in_group(_user, ZB_GROUP),
"is_ets_member": in_group(_user, ETS_GROUP),

@ -481,7 +481,7 @@ class NewWithdrawForm(BaseModalForm):
self.is_intervention_initially = False
# Add a placeholder for field 'surface' without having to define the whole widget above
self.fields["surface"].widget.attrs["placeholder"] = "0,00"
self.add_placeholder_for_field("surface", "0,00")
# Check for Intervention or EcoAccount
if isinstance(self.instance, Intervention):

@ -71,6 +71,19 @@ class BaseForm(forms.Form):
"""
self.fields[field].initial = val
def add_placeholder_for_field(self, field: str, val):
"""
Adds a placeholder to a field after initialization
Args:
field (str): Field name
val (str): Placeholder
Returns:
"""
self.fields[field].widget.attrs["placeholder"] = val
def load_initial_data(self, form_data: dict, disabled_fields: list):
""" Initializes form data from instance
@ -369,7 +382,7 @@ class RecordForm(BaseModalForm):
"""
super_val = super().is_valid()
msgs = self.instance.quality_check()
msgs = self.instance.quality_check() or []
for msg in msgs:
self.add_error(
"confirm",

@ -14,9 +14,9 @@ register = template.Library()
# ServerMessageImportance bootstrap resolver
SVI_BOOTSTRAP_CLS_MAP = {
ServerMessageImportance.DEFAULT.name: "",
ServerMessageImportance.WARNING.name: "alert-danger",
ServerMessageImportance.INFO.name: "alert-info",
ServerMessageImportance.DEFAULT: "",
ServerMessageImportance.WARNING: "alert-danger",
ServerMessageImportance.INFO: "alert-info",
}

Loading…
Cancel
Save