From 9de9d5007c688661c0f5bcc974310aef15b7618b Mon Sep 17 00:00:00 2001
From: mpeltriaux <michel.peltriaux@sgdnord.rlp.de>
Date: Fri, 25 Oct 2024 14:23:21 +0200
Subject: [PATCH] # 439 Wartungskommando Nachverschneidung

* refactors command update_all_parcels into recalculate_parcels
* fixes bug in command generate_report
---
 konova/management/commands/generate_report.py |  2 +-
 ..._all_parcels.py => recalculate_parcels.py} | 38 ++++++++++++-------
 2 files changed, 26 insertions(+), 14 deletions(-)
 rename konova/management/commands/{update_all_parcels.py => recalculate_parcels.py} (61%)

diff --git a/konova/management/commands/generate_report.py b/konova/management/commands/generate_report.py
index 51091871..daba9f69 100644
--- a/konova/management/commands/generate_report.py
+++ b/konova/management/commands/generate_report.py
@@ -6,11 +6,11 @@ Created on: 26.10.22
 
 """
 import zipfile
+from datetime import datetime
 from io import BytesIO
 
 from django.core.mail import EmailMessage
 from django.utils import timezone
-from django.utils.datetime_safe import datetime
 
 from analysis.utils.excel.excel import TempExcelFile
 from analysis.utils.report import TimespanReport
diff --git a/konova/management/commands/update_all_parcels.py b/konova/management/commands/recalculate_parcels.py
similarity index 61%
rename from konova/management/commands/update_all_parcels.py
rename to konova/management/commands/recalculate_parcels.py
index c9dd5158..e3768f77 100644
--- a/konova/management/commands/update_all_parcels.py
+++ b/konova/management/commands/recalculate_parcels.py
@@ -8,27 +8,46 @@ Created on: 04.01.22
 import datetime
 
 from django.contrib.gis.db.models.functions import Area
+from django.utils.timezone import now
 
 from konova.management.commands.setup import BaseKonovaCommand
 from konova.models import Geometry, Parcel, District
 
 
 class Command(BaseKonovaCommand):
-    help = "Checks the database' sanity and removes unused entries"
+    help = "Recalculates parcels for entries with geometry but missing parcel information"
+
+    def add_arguments(self, parser):
+        parser.add_argument(
+            "--force-all",
+            action="store_true",
+            default=False,
+            help="If Attribute set, all entries parcels will be recalculated"
+        )
 
     def handle(self, *args, **options):
         try:
-            self.update_all_parcels()
+            self.recalculate_parcels(options)
         except KeyboardInterrupt:
             self._break_line()
             exit(-1)
 
-    def update_all_parcels(self):
-        num_parcels_before = Parcel.objects.count()
-        num_districts_before = District.objects.count()
+    def recalculate_parcels(self, options: dict):
+        force_all = options.get("force_all", False)
+
+        if force_all:
+            geometry_objects = Geometry.objects.all()
+        else:
+            _today = now().date()
+            _date_threshold = _today - datetime.timedelta(days=1)
+            geometry_objects = Geometry.objects.filter(
+                parcel_update_start__date__lte=_date_threshold,
+                parcel_update_end__isnull=True
+            )
+
         self._write_warning("=== Update parcels and districts ===")
         # Order geometries by size to process smaller once at first
-        geometries = Geometry.objects.all().exclude(
+        geometries = geometry_objects.exclude(
             geom=None
         ).annotate(area=Area("geom")).order_by(
             'area'
@@ -43,12 +62,5 @@ class Command(BaseKonovaCommand):
             i += 1
             self._write_warning(f"--- {i}/{num_geoms} processed")
 
-        num_parcels_after = Parcel.objects.count()
-        num_districts_after = District.objects.count()
-        if num_parcels_after != num_parcels_before:
-            self._write_error(f"Parcels have changed: {num_parcels_before} to {num_parcels_after} entries. You should run the sanitize command.")
-        if num_districts_after != num_districts_before:
-            self._write_error(f"Districts have changed: {num_districts_before} to {num_districts_after} entries. You should run the sanitize command.")
-
         self._write_success("Updating parcels done!")
         self._break_line()