Skip to content
Snippets Groups Projects
Commit 454afc79 authored by Tor-Einar Skog's avatar Tor-Einar Skog
Browse files

Major overhaul of front page

parent dad1ca7a
No related branches found
No related tags found
No related merge requests found
...@@ -67,7 +67,7 @@ function initForecastMap(lonLat, zoomLevel, mapAttribution) ...@@ -67,7 +67,7 @@ function initForecastMap(lonLat, zoomLevel, mapAttribution)
forecastLayer = new ol.layer.Vector({ forecastLayer = new ol.layer.Vector({
source: new ol.source.Vector({ source: new ol.source.Vector({
url: "http://" + settings.vipslogicServerName + "/rest/forecastresults/aggregate/" + settings.vipsOrganizationId + "?" + buildPathParamString("cropOrganismId", getSelectedCropIds()), url: "http://" + settings.vipslogicServerName + "/rest/forecastresults/aggregate/" + settings.vipsOrganizationId + "?" + buildPathParamString("cropCategoryId", getSelectedCropCategoryIds()),
format: new ol.format.KML({"extractAttributes":true}), format: new ol.format.KML({"extractAttributes":true}),
projection: ol.proj.get('EPSG:3857') projection: ol.proj.get('EPSG:3857')
}) })
...@@ -191,7 +191,7 @@ function initForecastMap(lonLat, zoomLevel, mapAttribution) ...@@ -191,7 +191,7 @@ function initForecastMap(lonLat, zoomLevel, mapAttribution)
+ "</ul>"; + "</ul>";
} }
console.log(feature); //console.log(feature);
poiDetails.popover({ poiDetails.popover({
animation: true, animation: true,
trigger: 'manual', trigger: 'manual',
...@@ -334,11 +334,11 @@ function getCurrentMapZoomLevel() ...@@ -334,11 +334,11 @@ function getCurrentMapZoomLevel()
function updateForecastLayers() function updateForecastLayers()
{ {
map.removeLayer(forecastLayer); map.removeLayer(forecastLayer);
var cropOrganismIdStr = buildPathParamString("cropOrganismId", getSelectedCropIds()); var cropCategoryIdStr = buildPathParamString("cropCategoryId", getSelectedCropCategoryIds());
// If empty, make sure we send a number anyway // If empty, make sure we send a number anyway
if(cropOrganismIdStr === "") if(cropCategoryIdStr === "")
{ {
cropOrganismIdStr = "&cropOrganismId=-1"; cropCategoryIdStr = "&cropCategoryId=-1";
} }
/*forecastLayer = new ol.layer.Vector({ /*forecastLayer = new ol.layer.Vector({
source: new ol.source.KML({ source: new ol.source.KML({
...@@ -348,7 +348,7 @@ function updateForecastLayers() ...@@ -348,7 +348,7 @@ function updateForecastLayers()
});*/ });*/
forecastLayer = new ol.layer.Vector({ forecastLayer = new ol.layer.Vector({
source: new ol.source.Vector({ source: new ol.source.Vector({
url: "http://" + settings.vipslogicServerName + "/rest/forecastresults/aggregate/" + settings.vipsOrganizationId + "?" + cropOrganismIdStr, url: "http://" + settings.vipslogicServerName + "/rest/forecastresults/aggregate/" + settings.vipsOrganizationId + "?" + cropCategoryIdStr,
format: new ol.format.KML(), format: new ol.format.KML(),
projection: ol.proj.get('EPSG:3857') projection: ol.proj.get('EPSG:3857')
}) })
......
...@@ -31,18 +31,33 @@ ...@@ -31,18 +31,33 @@
* Which crops have been selected? Checks the form * Which crops have been selected? Checks the form
* @returns * @returns
*/ */
function getSelectedCropIds() function getSelectedCropCategoryIds()
{ {
selectedCropIds = []; selectedCropCategoryIds = [];
formFields = document.getElementsByName("cropIds"); formFields = document.getElementsByName("cropCategoryIds");
for(var i=0;i<formFields.length;i++) for(var i=0;i<formFields.length;i++)
{ {
if(formFields[i].checked) if(formFields[i].checked)
{ {
selectedCropIds = selectedCropIds.concat(eval(formFields[i].value)); selectedCropCategoryIds.push(parseInt(formFields[i].value));
} }
} }
return selectedCropIds; return selectedCropCategoryIds;
}
function getSelectedCropIds()
{
var selectedCropCategoryIds = getSelectedCropCategoryIds();
var selectedCropIdsTemp = [];
for(var i in settings.cropCategories)
{
if(selectedCropCategoryIds.indexOf(settings.cropCategories[i]["cropCategoryId"]) >= 0)
{
selectedCropIdsTemp = selectedCropIdsTemp.concat(settings.cropCategories[i]["cropOrganismIds"]);
}
}
// This trick ensures all elements in array are unique
return selectedCropIdsTemp.filter(function(value,index,self){return self.indexOf(value) === index;});
} }
var allObservations; var allObservations;
...@@ -54,8 +69,8 @@ function cacheObservations() ...@@ -54,8 +69,8 @@ function cacheObservations()
allObservations = json; allObservations = json;
//console.log(allObservations); //console.log(allObservations);
filterObservations(); filterObservations();
} }
); );
} }
/** /**
...@@ -90,7 +105,6 @@ function renderObservationMessages() ...@@ -90,7 +105,6 @@ function renderObservationMessages()
messagesLeftColTBody.innerHTML += '<tr>\n<td class="dateCell">' + getStandardFormattedDate(observation["timeOfObservation"]) + '</td><td><a href="/observations/' + observation["observationId"] + '">' + observation["observationHeading"] + '</a></td>\n</tr>'; messagesLeftColTBody.innerHTML += '<tr>\n<td class="dateCell">' + getStandardFormattedDate(observation["timeOfObservation"]) + '</td><td><a href="/observations/' + observation["observationId"] + '">' + observation["observationHeading"] + '</a></td>\n</tr>';
} }
} }
var allMessages; var allMessages;
...@@ -113,20 +127,6 @@ function cacheMessages() ...@@ -113,20 +127,6 @@ function cacheMessages()
*/ */
function renderMessages() function renderMessages()
{ {
/*for(var i in settings.frontpageMessageTagIds)
{
var tagId = settings.frontpageMessageTagIds[i];
document.getElementById("tbody_messageTag_" + tagId).innerHTML = "";
tagMessages = filteredMessages[tagId];
//console.log(tagMessages);
for(var j in tagMessages)
{
var tagMessage = tagMessages[j];
document.getElementById("tbody_messageTag_" + tagId).innerHTML +=
'<tr><td class="dateCell">' + tagMessage["datePub"] + '</td><td><a href="/messages/' + tagMessage["messageId"] + '">' + getMessageLocale(tagMessage, settings.currentLanguage,settings.languageCode)["heading"] + '</a></td></tr>';
}
}*/
var messagesRightColTBody = document.getElementById("messagesRightColTBody"); var messagesRightColTBody = document.getElementById("messagesRightColTBody");
messagesRightColTBody.innerHTML = ""; messagesRightColTBody.innerHTML = "";
...@@ -147,7 +147,6 @@ function renderMessages() ...@@ -147,7 +147,6 @@ function renderMessages()
function filterMessages() function filterMessages()
{ {
var selectedCropIds = getSelectedCropIds(); var selectedCropIds = getSelectedCropIds();
//console.log(selectedCropIds);
filteredMessages = []; filteredMessages = [];
for(var tagI in allMessages) for(var tagI in allMessages)
{ {
...@@ -156,23 +155,23 @@ function filterMessages() ...@@ -156,23 +155,23 @@ function filterMessages()
for(var mI in allMessages[tagI]) for(var mI in allMessages[tagI])
{ {
var message = allMessages[tagI][mI]; var message = allMessages[tagI][mI];
var messageCropOrganismIds = message["messageCropOrganismIds"]; var cropCategoryIds = message["cropCategoryIds"];
if(messageCropOrganismIds.length == 0) if(cropCategoryIds.length == 0)
{ {
//filteredForTag.push(message); //filteredForTag.push(message);
filteredMessages.push(message); filteredMessages.push(message);
} }
else else
{ {
for(var mCOI in messageCropOrganismIds) for(var cci in cropCategoryIds)
{ {
//console.log(messageCropOrganismIds[mCOI]); //console.log(messageCropOrganismIds[mCOI]);
if(selectedCropIds.indexOf(messageCropOrganismIds[mCOI]) >= 0) /*if(selectedCropIds.indexOf(messageCropOrganismIds[mCOI]) >= 0)
{ {
//filteredForTag.push(message); //filteredForTag.push(message);
filteredMessages.push(message); filteredMessages.push(message);
break; break;
} }*/
} }
} }
} }
...@@ -235,6 +234,7 @@ function renderForecastConfigurationSummaries(forecastConfigurations) ...@@ -235,6 +234,7 @@ function renderForecastConfigurationSummaries(forecastConfigurations)
forecastSummariesTable.innerHTML = summariesHTML; forecastSummariesTable.innerHTML = summariesHTML;
forecastSummariesTable.style.display="block"; forecastSummariesTable.style.display="block";
//document.getElementById("emptyForecastSummariesTableInfo").style.display="none"; //document.getElementById("emptyForecastSummariesTableInfo").style.display="none";
} }
/** /**
...@@ -283,8 +283,6 @@ function renderMyForecastConfigurationSummaries() ...@@ -283,8 +283,6 @@ function renderMyForecastConfigurationSummaries()
return; return;
} }
console.log(myForecastConfigurations);
var mySummariesHTML = getforecastSummariesTableHTML(myForecastConfigurations,false, true); var mySummariesHTML = getforecastSummariesTableHTML(myForecastConfigurations,false, true);
myForecastSummariesTable.innerHTML = mySummariesHTML; myForecastSummariesTable.innerHTML = mySummariesHTML;
//document.getElementById("myForecastSummariesContainer").style.display = "block"; //document.getElementById("myForecastSummariesContainer").style.display = "block";
...@@ -570,17 +568,15 @@ function updateForecastSummaries() ...@@ -570,17 +568,15 @@ function updateForecastSummaries()
// Iterate all forecast summaries, filter by crop (must be among the selected crops) // Iterate all forecast summaries, filter by crop (must be among the selected crops)
// and location on the map (must be visible on the map) // and location on the map (must be visible on the map)
var selectedCropIds = getSelectedCropIds(); var selectedCropIds = getSelectedCropIds();
var filteredForecastSummaries = []; var filteredForecastSummaries = [];
for(var i in cachedForecastSummaries) for(var i in cachedForecastSummaries)
{ {
var forecastSummary = cachedForecastSummaries[i]; var forecastSummary = cachedForecastSummaries[i];
//console.log(forecastSummary);
// Filter by crop // Filter by crop
var isASelectedCrop = false; var isASelectedCrop = false;
for(var j in selectedCropIds) for(var j in selectedCropIds)
{ {
if(selectedCropIds[j] === forecastSummary.cropOrganismId.organismId) if(selectedCropIds.indexOf(forecastSummary.cropOrganismId.organismId) > 0)
{ {
isASelectedCrop = true; isASelectedCrop = true;
} }
...@@ -615,7 +611,18 @@ function updateForecastSummaries() ...@@ -615,7 +611,18 @@ function updateForecastSummaries()
renderForecastConfigurationSummaries(filteredForecastSummaries); renderForecastConfigurationSummaries(filteredForecastSummaries);
}
function getOrganismIdsForCropCategory(cropCategoryId)
{
for(var i in settings.cropCategories)
{
if(settings.cropCategories[i]["crop_group_id"] == cropCategoryId)
{
return settings.cropCategories[i]["crop_ids"];
}
}
return [];
} }
/** /**
...@@ -696,9 +703,9 @@ function getExternalResourcesForPoi(poiId) ...@@ -696,9 +703,9 @@ function getExternalResourcesForPoi(poiId)
* TODO: If user logged in, store in user session on server for * TODO: If user logged in, store in user session on server for
* global access on clients where the user is logged in * global access on clients where the user is logged in
*/ */
function storeSelectedCropIds() function storeSelectedCropCategoryIds()
{ {
storeLocalSettings({"selectedCropIds":getSelectedCropIds()}); storeLocalSettings({"selectedCropCategoryIds":getSelectedCropCategoryIds()});
} }
/** /**
...@@ -706,16 +713,16 @@ function storeSelectedCropIds() ...@@ -706,16 +713,16 @@ function storeSelectedCropIds()
* TODO: Add server as persistence layer when login system is * TODO: Add server as persistence layer when login system is
* implemented * implemented
*/ */
function restoreSelectedCropIds() function restoreSelectedCropCategoryIds()
{ {
// localStorage only stores strings, so we must recreate as array // localStorage only stores strings, so we must recreate as array
var selectedCropIds = getLocalSettings(["selectedCropIds"]) != null ? var selectedCropCategoryIds = getLocalSettings(["selectedCropCategoryIds"]) != null ?
getLocalSettings(["selectedCropIds"])["selectedCropIds"].split(",") getLocalSettings(["selectedCropCategoryIds"])["selectedCropCategoryIds"].split(",")
: null; : null;
if(selectedCropIds != null) if(selectedCropCategoryIds != null)
{ {
// Loop through existing crops, set as checked/unchecked // Loop through existing crops, set as checked/unchecked
formFields = document.getElementsByName("cropIds"); formFields = document.getElementsByName("cropCategoryIds");
for(i in formFields) for(i in formFields)
{ {
if(formFields[i].value == undefined) if(formFields[i].value == undefined)
...@@ -723,10 +730,10 @@ function restoreSelectedCropIds() ...@@ -723,10 +730,10 @@ function restoreSelectedCropIds()
continue; continue;
} }
var previouslySelected = false; var previouslySelected = false;
for(var j in selectedCropIds) for(var j in selectedCropCategoryIds)
{ {
// Need to use eval() as values are strings with [] representing arrays // Need to use eval() as values are strings with [] representing arrays
if(eval(formFields[i].value).indexOf(parseInt(selectedCropIds[j])) >=0) if(parseInt(formFields[i].value) == parseInt(selectedCropCategoryIds[j]))
{ {
previouslySelected = true; previouslySelected = true;
} }
...@@ -756,7 +763,6 @@ function removeFromMyForecastConfigurations(forecastConfigurationId) ...@@ -756,7 +763,6 @@ function removeFromMyForecastConfigurations(forecastConfigurationId)
{ {
myForecastConfigurationIds.splice(spliceIndex,1); myForecastConfigurationIds.splice(spliceIndex,1);
} }
console.log(myForecastConfigurationIds);
storeLocalSettings({"myForecastConfigurationIds":myForecastConfigurationIds}); storeLocalSettings({"myForecastConfigurationIds":myForecastConfigurationIds});
updateForecastSummaries(); updateForecastSummaries();
} }
......
...@@ -47,10 +47,11 @@ ...@@ -47,10 +47,11 @@
latitude = parseFloat(storedMapSettings["latitude"]); latitude = parseFloat(storedMapSettings["latitude"]);
zoomLevel = parseInt(storedMapSettings["zoomLevel"]); zoomLevel = parseInt(storedMapSettings["zoomLevel"]);
} }
restoreSelectedCropCategoryIds();
// Init frontpage map. Depending on forecastmap.js. // Init frontpage map. Depending on forecastmap.js.
initForecastMap([longitude,latitude],zoomLevel,"{{settings.MAP_ATTRIBUTION|safe}}"); initForecastMap([longitude,latitude],zoomLevel,"{{settings.MAP_ATTRIBUTION|safe}}");
cachePois(); cachePois();
restoreSelectedCropIds();
cacheMessages(); cacheMessages();
cacheObservations(); cacheObservations();
cachePrivateForecastSummaries(); cachePrivateForecastSummaries();
...@@ -83,10 +84,11 @@ ...@@ -83,10 +84,11 @@
<div id="cropList" class="mapBoxPlacement_{{settings.MAP_CROP_LIST_PLACEMENT}}"> <div id="cropList" class="mapBoxPlacement_{{settings.MAP_CROP_LIST_PLACEMENT}}">
<h3>{% trans "Crops" %}</h3> <h3>{% trans "Crops" %}</h3>
<ul class="cropList single"> <ul class="cropList single">
{% for crop_group in crop_groups %} <!--ul-->
{% for crop_category in crop_categories %}
<li> <li>
<input type="checkbox" name="cropIds" id="cropIds_{{crop_group.crop_ids|slugify}}" value="{{crop_group.crop_ids}}" checked="checked" onchange="refreshForecasts({{settings.VIPS_ORGANIZATION_ID}},'{{settings.VIPSLOGIC_SERVER_NAME}}');storeSelectedCropIds();filterMessages();filterObservations();"/> <input type="checkbox" name="cropCategoryIds" id="cropCategoryIds_{{crop_category.crop_category_id}}" value="{{crop_category.crop_category_id}}" checked="checked" onchange="refreshForecasts({{settings.VIPS_ORGANIZATION_ID}},'{{settings.VIPSLOGIC_SERVER_NAME}}');storeSelectedCropCategoryIds();filterMessages();filterObservations();"/>
<label for="cropIds_{{crop_group.crop_ids|slugify}}"><span></span>{{ crop_group.name|safe }}</label> <label for="cropCategoryIds_{{crop_category.crop_category_id}}"><span></span>{{ crop_category.name|safe }}</label>
</li> </li>
{% endfor %} {% endfor %}
</ul> </ul>
......
...@@ -19,5 +19,7 @@ var settings = { ...@@ -19,5 +19,7 @@ var settings = {
frontpageMessageTagIds: {{settings.FRONTPAGE_MESSAGE_TAG_IDS}}, frontpageMessageTagIds: {{settings.FRONTPAGE_MESSAGE_TAG_IDS}},
userUuid: {% if request.session.vips_logic_user == None %}null{% else %}"{{request.session.user_uuid}}"{% endif %} userUuid: {% if request.session.vips_logic_user == None %}null{% else %}"{{request.session.user_uuid}}"{% endif %},
cropCategories : {{crop_categories|safe}}
}; };
...@@ -21,7 +21,7 @@ from django.http import HttpResponse, JsonResponse ...@@ -21,7 +21,7 @@ from django.http import HttpResponse, JsonResponse
from django.conf import settings from django.conf import settings
from django.utils import translation from django.utils import translation
from vips_messages.models import Message, MessageTag from vips_messages.models import Message, MessageTag
from organisms.models import CropGroup from organisms.models import CropCategory
def index(request): def index(request):
# Get front page categories. This is defined in local_settings.py # Get front page categories. This is defined in local_settings.py
...@@ -29,13 +29,13 @@ def index(request): ...@@ -29,13 +29,13 @@ def index(request):
# Last 10 messages # Last 10 messages
context = { context = {
'message_tags': message_tags, 'message_tags': message_tags,
'crop_groups': CropGroup.get_crop_groups(translation.get_language()) 'crop_categories': CropCategory.get_crop_categories(translation.get_language())
} }
return render(request, 'index.html', context) return render(request, 'index.html', context)
# Serving settings for JavaScript # Serving settings for JavaScript
def settings_js(request): def settings_js(request):
context = {} context = {'crop_categories': CropCategory.get_crop_categories_from_vipslogic_as_text()}
return render(request,'settings.js', context, content_type="application/javascript;charset=UTF-8") return render(request,'settings.js', context, content_type="application/javascript;charset=UTF-8")
## TODO: Is this being used??? ## TODO: Is this being used???
......
...@@ -20,28 +20,45 @@ import requests ...@@ -20,28 +20,45 @@ import requests
from django.conf import settings from django.conf import settings
from django.utils import translation from django.utils import translation
class CropGroup: class CropCategory:
def __init__(self, def __init__(self,
crop_group_id, crop_category_id,
name, name,
crop_ids crop_ids
): ):
self.crop_group_id = crop_group_id self.crop_category_id = crop_category_id
self.name = name self.name = name
self.crop_ids = crop_ids self.crop_ids = crop_ids
@staticmethod @staticmethod
def get_crop_groups(language): def get_crop_categories(language):
crop_groups = [] crop_categories = []
for item in settings.CROP_GROUPS: for item in CropCategory.get_crop_categories_from_vipslogic_as_json():
crop_groups.append(CropGroup.get_instance_from_dict(item,language)) crop_categories.append(CropCategory.get_instance_from_dict(item,language))
return crop_groups return crop_categories
@staticmethod
def get_crop_categories_from_vipslogic():
request_result = requests.get("http://%s/rest/organism/cropcategory/%s" % (settings.VIPSLOGIC_SERVER_NAME, settings.VIPS_ORGANIZATION_ID))
return request_result
@staticmethod
def get_crop_categories_from_vipslogic_as_json():
return CropCategory.get_crop_categories_from_vipslogic().json()
@staticmethod
def get_crop_categories_from_vipslogic_as_text():
return CropCategory.get_crop_categories_from_vipslogic().text
@staticmethod @staticmethod
def get_instance_from_dict(dict,language): def get_instance_from_dict(dict,language):
return CropGroup(dict["crop_group_id"], local_name = dict["defaultName"]
dict["name"].get(language,dict["name"]["en"]), for crop_category_local in dict["cropCategoryLocalSet"]:
dict["crop_ids"] if crop_category_local["cropCategoryLocalPK"]["locale"] == language:
local_name = crop_category_local["localName"]
return CropCategory(dict["cropCategoryId"],
local_name,
dict["cropOrganismIds"]
) )
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment