From d9cc45d720989c632ef35b9363b444b06d1a1184 Mon Sep 17 00:00:00 2001
From: Tor-Einar Skog <tor-einar.skog@nibio.no>
Date: Wed, 13 Nov 2024 11:07:36 +0100
Subject: [PATCH] feat: Add configurable weather data sites

---
 VIPSWeb/local_settings_sample.py              |  3 +
 cydiapomonella/static/js/cydiapomonella.js    | 18 +++--
 .../templates/cydiapomonella/index.html       | 80 ++++++++++---------
 3 files changed, 57 insertions(+), 44 deletions(-)

diff --git a/VIPSWeb/local_settings_sample.py b/VIPSWeb/local_settings_sample.py
index 58088731..d358377f 100755
--- a/VIPSWeb/local_settings_sample.py
+++ b/VIPSWeb/local_settings_sample.py
@@ -136,6 +136,9 @@ VIPSCOREMANAGER_SSLCERT_PATH = None
 # Date format for dates from VIPSLogic
 VIPSLOGIC_DATE_FORMAT = "%Y-%m-%d"
 
+# Settings for VIPS Norway - apps that are not globally applicable
+LMT_SERVICES_URL = "https://foo.bar.com/services"
+
 # Site owner info
 SITE_OWNER_NAME = {"en":"FooBar Inc","nb":"ACME industrier"}
 SITE_OWNER_URL = "http://www.example.com/"
diff --git a/cydiapomonella/static/js/cydiapomonella.js b/cydiapomonella/static/js/cydiapomonella.js
index 964f06fb..5a42ea57 100644
--- a/cydiapomonella/static/js/cydiapomonella.js
+++ b/cydiapomonella/static/js/cydiapomonella.js
@@ -19,9 +19,8 @@
 
 class CydiaPomonella 
 {
-
-    weatherStationDataURL = "https://lmt.nibio.no/services/rest/vips/getdata/forecastfallback";
-    gridDataURL = "https://weather.vips.nibio.no/rest/grid/openmeteo/"; 
+    weatherStationDataURL = undefined;
+    gridDataURL = undefined;
     TIMEZONE_OSLO = "Europe/Oslo";
     DATE_FORMAT = "YYYY-MM-DD";
     HEATSUM_BASE_TEMP = 10.0;
@@ -56,6 +55,11 @@ class CydiaPomonella
 
     appleWeatherStationIds = this.appleWeatherStations.map(ws=>ws.id);
 
+    constructor(lmtServicesURL, gridDataURL){
+        this.weatherStationDataURL = lmtServicesURL + "/rest/vips/getdata/forecastfallback";
+        this.gridDataURL = gridDataURL;
+    }
+
     renderWeatherstations = function () {
         let wsSelect = document.getElementById("weatherStationId");
         this.appleWeatherStations.forEach((ws) => {
@@ -110,8 +114,8 @@ class CydiaPomonella
             else if(this.getSelectedWeatherdataSourceType() == this.WEATHER_DATASOURCE_TYPE_COORDINATES && selectedCoordinate != undefined)
             {
                 hourlyDataResponse = await fetch(
-                    this.gridDataURL + "?longitude=" + selectedCoordinate[0] + "&latitude=" + selectedCoordinate[1]
-                    + "&elementMeasurementTypes[]=RR&elementMeasurementTypes[]=TM"
+                    this.gridDataURL.replace("%s",selectedCoordinate[0] + "_" + selectedCoordinate[1]) //+ "?longitude=" + selectedCoordinate[0] + "&latitude=" + selectedCoordinate[1]
+                    + "?elementMeasurementTypes[]=RR&elementMeasurementTypes[]=TM"
                     + "&timeZone="  + document.getElementById("timezone").value
                     + "&startDate=" + startDateHourly.format(this.DATE_FORMAT) + "&startTime=0" 
                     + "&endDate=" + endDateHourly.format(this.DATE_FORMAT) + "&endTime=12"  
@@ -172,8 +176,8 @@ class CydiaPomonella
         else if(this.getSelectedWeatherdataSourceType() == this.WEATHER_DATASOURCE_TYPE_COORDINATES && selectedCoordinate != undefined)
         {
             heatSumDataResponse = await fetch(
-                this.gridDataURL + "?longitude=" + selectedCoordinate[0] + "&latitude=" + selectedCoordinate[1]
-                + "&elementMeasurementTypes[]=TM"
+                this.gridDataURL.replace("%s",selectedCoordinate[0] + "_" + selectedCoordinate[1])// + "?longitude=" + selectedCoordinate[0] + "&latitude=" + selectedCoordinate[1]
+                + "?elementMeasurementTypes[]=TM"
                 + "&timeZone="  + document.getElementById("timezone").value
                 + "&startDate=" + heatSumStartDate.format(this.DATE_FORMAT) + "&startTime=0" 
                 + "&endDate=" + heatSumEndDate.format(this.DATE_FORMAT) + "&endTime=23"  
diff --git a/cydiapomonella/templates/cydiapomonella/index.html b/cydiapomonella/templates/cydiapomonella/index.html
index 84fe0b58..c1f09174 100644
--- a/cydiapomonella/templates/cydiapomonella/index.html
+++ b/cydiapomonella/templates/cydiapomonella/index.html
@@ -22,8 +22,8 @@ Created: 2024-10-28
 {% block title%}{% trans "Cydia pomonella" %}{%endblock%}
 
 {% block customCSS %}
-<link type="text/css" rel="stylesheet" href="https://logic.testvips.nibio.no/css/3rdparty/leaflet.css" />
-<link type="text/css" rel="stylesheet" href="https://logic.testvips.nibio.no/css/mapModal.css" />
+<link type="text/css" rel="stylesheet" href="{{ settings.VIPSLOGIC_PROTOCOL }}://{{ settings.VIPSLOGIC_SERVER_NAME }}/css/3rdparty/leaflet.css" />
+<link type="text/css" rel="stylesheet" href="{{ settings.VIPSLOGIC_PROTOCOL }}://{{ settings.VIPSLOGIC_SERVER_NAME }}/css/mapModal.css" />
 {% endblock %}
 
 {% block extendJS %}
@@ -38,49 +38,55 @@ Created: 2024-10-28
 {% block customJS %}
 <script type="module">
     import CydiaPomonella from "../static/js/cydiapomonella.js";
-    const cydiaPomonella = new CydiaPomonella();
+    let cydiaPomonella = undefined;
     const userSettingsFields = ["latitude","longitude","timezone","weatherStationId","heatSumStartDate"];
     const userSettingsRadios = ["weatherdataType","radioDays"];
     window.onload = (event) => {
-        cydiaPomonella.renderWeatherstations();
-        //console.info(getNameSpaced("{{ form_id }}",userSettingsFields.concat(userSettingsRadios)));
-        let userSettings = getLocalSettings(getNameSpaced("{{ form_id }}",userSettingsFields.concat(userSettingsRadios)), false);
+        fetch("{{ settings.VIPSLOGIC_PROTOCOL }}://{{ settings.VIPSLOGIC_SERVER_NAME }}/rest/organization/{{ settings.VIPS_ORGANIZATION_ID }}")
+        .then(response => response.json())
+        .then(organizationJson => {
+            cydiaPomonella = new CydiaPomonella("{{ settings.LMT_SERVICES_URL }}",organizationJson.defaultGridWeatherStationDataSource.datafetchUriExpression);
         
-        // Settings found, render form and run model
-        if(Object.keys(userSettings).length > 0)
-        {
-            userSettingsFields.forEach((fieldId) =>{
-                document.getElementById(fieldId).value = userSettings[`{{ form_id }}.${fieldId}`];
-            });
-            userSettingsRadios.forEach((radioName) => {
-                let radioValue = userSettings[`{{ form_id }}.${radioName}`];
-                document.getElementsByName(radioName).forEach((radioElement) => {
-                    radioElement.checked = (radioElement.value == radioValue);
+            cydiaPomonella.renderWeatherstations();
+            //console.info(getNameSpaced("{{ form_id }}",userSettingsFields.concat(userSettingsRadios)));
+            let userSettings = getLocalSettings(getNameSpaced("{{ form_id }}",userSettingsFields.concat(userSettingsRadios)), false);
+            
+            // Settings found, render form and run model
+            if(Object.keys(userSettings).length > 0)
+            {
+                userSettingsFields.forEach((fieldId) =>{
+                    document.getElementById(fieldId).value = userSettings[`{{ form_id }}.${fieldId}`];
+                });
+                userSettingsRadios.forEach((radioName) => {
+                    let radioValue = userSettings[`{{ form_id }}.${radioName}`];
+                    document.getElementsByName(radioName).forEach((radioElement) => {
+                        radioElement.checked = (radioElement.value == radioValue);
+                    });
                 });
-            });
 
-            // Check that heat sum start date is in current year. If not: Update to current year
-            let heatSumStartDateElement = document.getElementById("heatSumStartDate");
-            let heatSumStartDate = moment(heatSumStartDateElement.value);
-            if(heatSumStartDate.year() != moment().year())
-            {
-                heatSumStartDate.year(moment().year());
-                heatSumStartDateElement.value = heatSumStartDate.format(cydiaPomonella.DATE_FORMAT);
-            }
+                // Check that heat sum start date is in current year. If not: Update to current year
+                let heatSumStartDateElement = document.getElementById("heatSumStartDate");
+                let heatSumStartDate = moment(heatSumStartDateElement.value);
+                if(heatSumStartDate.year() != moment().year())
+                {
+                    heatSumStartDate.year(moment().year());
+                    heatSumStartDateElement.value = heatSumStartDate.format(cydiaPomonella.DATE_FORMAT);
+                }
 
 
-            if(document.getElementById("coordinates").checked)
-            {
-                displayCoordinatesInput();
-                getTimezoneForPoint(inputLatitudeElement.value, inputLongitudeElement.value);
-            }
-            else
-            {
-                displayWeatherstationInput();
-            }
+                if(document.getElementById("coordinates").checked)
+                {
+                    displayCoordinatesInput();
+                    getTimezoneForPoint(inputLatitudeElement.value, inputLongitudeElement.value);
+                }
+                else
+                {
+                    displayWeatherstationInput();
+                }
 
-            cydiaPomonella.runModel();
-        }
+                cydiaPomonella.runModel();
+            }
+        });
     }
     // We need to do it this way to keep the "this" reference of the class
     window.runModel = function () {cydiaPomonella.runModel()};
@@ -104,7 +110,7 @@ Created: 2024-10-28
     }
 
     /* ########   MAP UI FUNCTIONALITY  ######### */
-    import MapModal from 'https://logic.testvips.nibio.no/js/mapModal.js';
+    import MapModal from "{{ settings.VIPSLOGIC_PROTOCOL }}://{{ settings.VIPSLOGIC_SERVER_NAME }}/js/mapModal.js";
     const inputLatitudeElement = document.getElementById("latitude");
     const inputLongitudeElement = document.getElementById("longitude");
     const selectWeatherstationElement = document.getElementById("weatherStationId");
-- 
GitLab