This commit is contained in:
2026-04-27 18:02:26 +03:30
parent 7c2ec2144d
commit 190a668355
19 changed files with 193 additions and 825 deletions
+3 -23
View File
@@ -1,25 +1,9 @@
from __future__ import annotations
from typing import Any
from django.apps import apps
from farm_data.models import SensorData
def build_water_stress_summary(sensor: Any) -> dict[str, Any]:
moisture = float(getattr(sensor, "soil_moisture", None) or 0.0)
water_stress = max(0, min(100, round(35 - (moisture / 2))))
return {
"waterStressIndex": water_stress,
"level": "پایین" if water_stress <= 20 else "متوسط" if water_stress <= 45 else "بالا",
"sourceMetric": {
"soilMoisture": round(moisture, 2),
"formula": "clamp(round(35 - (soil_moisture / 2)), 0, 100)",
},
}
class WaterStressService:
def get_water_stress(self, *, farm_uuid: str, plant_name: str | None = None) -> dict[str, Any]:
sensor = SensorData.objects.filter(farm_uuid=farm_uuid).first()
@@ -32,10 +16,6 @@ class WaterStressService:
plant_name=plant_name,
)
except Exception as exc:
fallback = {
"farm_uuid": str(sensor.farm_uuid),
**build_water_stress_summary(sensor),
}
fallback["sourceMetric"]["engine"] = "sensor_fallback"
fallback["sourceMetric"]["fallbackReason"] = str(exc)
return fallback
raise RuntimeError(
f"Water stress simulation failed for farm {sensor.farm_uuid}: {exc}"
) from exc
+5 -7
View File
@@ -68,7 +68,7 @@ class WaterStressServiceTests(TestCase):
@patch("irrigation.indicators.apps.get_app_config")
@patch("irrigation.indicators.SensorData.objects.filter")
def test_service_falls_back_when_crop_simulation_fails(self, mock_filter, mock_get_app_config):
def test_service_raises_when_crop_simulation_fails(self, mock_filter, mock_get_app_config):
mock_filter.return_value.first.return_value = SimpleNamespace(
farm_uuid="550e8400-e29b-41d4-a716-446655440000",
soil_moisture=46.0,
@@ -82,9 +82,7 @@ class WaterStressServiceTests(TestCase):
get_water_stress_service=lambda: BrokenService()
)
payload = WaterStressService().get_water_stress(
farm_uuid="550e8400-e29b-41d4-a716-446655440000"
)
self.assertEqual(payload["sourceMetric"]["engine"], "sensor_fallback")
self.assertEqual(payload["sourceMetric"]["fallbackReason"], "simulation offline")
with self.assertRaises(RuntimeError):
WaterStressService().get_water_stress(
farm_uuid="550e8400-e29b-41d4-a716-446655440000"
)