view client/src/store/bottlenecks.js @ 5587:2576a399c2cf surveysperbottleneckid

Using squarebrackets in displayName
author Thomas Junk <thomas.junk@intevation.de>
date Mon, 04 Apr 2022 15:30:54 +0200
parents 215e6ba9651b
children 94ef43fac0eb
line wrap: on
line source

/* This is Free Software under GNU Affero General Public License v >= 3.0
 * without warranty, see README.md and license for details.
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later
 * License-Filename: LICENSES/AGPL-3.0.txt
 *
 * Copyright (C) 2018 by via donau
 *   – Österreichische Wasserstraßen-Gesellschaft mbH
 * Software engineering by Intevation GmbH
 *
 * Author(s):
 * Markus Kottländer <markuks.kottlaender@intevation.de>
 * Thomas Junk <thomas.junk@intevation.de>
 */
import { HTTP } from "@/lib/http";
import { WFS } from "ol/format";
import { compareAsc } from "date-fns";
import { displayError } from "@/lib/errors";
// initial state
const init = () => {
  return {
    bottlenecks: [],
    bottlenecksList: [],
    selectedBottleneck: null,
    surveys: [],
    selectedSurvey: null,
    surveysLoading: false,
    bottleneckForPrint: null,
    soundingInfo: null
  };
};

export default {
  init,
  namespaced: true,
  state: init(),
  getters: {
    limitingFactorsPerBottleneck: state => {
      if (state.bottlenecks.length === 0) return {};
      return state.bottlenecks.reduce((o, n) => {
        o[n.properties.bottleneck_id] = n.properties.limiting;
        return o;
      }, {});
    },
    orderedBottlenecks: state => {
      const groupedBottlenecks = {};
      const orderedGroups = {};
      // group bottlenecks by cc
      state.bottlenecksList.forEach(bn => {
        let cc = bn.properties.responsible_country;
        if (groupedBottlenecks.hasOwnProperty(cc)) {
          groupedBottlenecks[cc].push(bn);
        } else {
          groupedBottlenecks[cc] = [bn];
        }
      });

      // order groups by cc
      Object.keys(groupedBottlenecks)
        .sort()
        .forEach(cc => {
          const names = {};
          const doubleNames = {};
          groupedBottlenecks[cc].forEach(bn => {
            const name = bn.properties.name || bn.properties.objnam;
            if (!names[name]) {
              names[name] = name;
            } else {
              doubleNames[name] = name;
            }
          });
          groupedBottlenecks[cc].forEach(bn => {
            const name = bn.properties.name || bn.properties.objnam;
            if (doubleNames[name]) {
              bn.properties.displayName = `${name} [${bn.properties.bottleneck_id}]`;
            } else {
              bn.properties.displayName = name;
            }
          });
          orderedGroups[cc] = groupedBottlenecks[cc];
        });

      return orderedGroups;
    }
  },
  mutations: {
    setSoundingInfo: (state, data) => {
      state.soundingInfo = data;
    },
    setBottleneckForPrint: (state, bottleneck) => {
      state.bottleneckForPrint = bottleneck;
    },
    setBottlenecks: (state, bottlenecks) => {
      state.bottlenecks = bottlenecks;
    },
    setBottlenecksList: (state, bottlenecksList) => {
      state.bottlenecksList = bottlenecksList;
    },
    setSelectedBottleneck: (state, value) => {
      state.selectedBottleneck = value;
    },
    setSurveys(state, surveys) {
      state.surveys = surveys;
    },
    setSelectedSurveyByDate(state, date) {
      const survey = state.surveys.filter(x => x.date_info === date)[0];
      state.selectedSurvey = survey;
    },
    setFirstSurveySelected(state) {
      state.selectedSurvey = state.surveys[0];
    },
    selectedSurvey(state, survey) {
      state.selectedSurvey = survey;
    },
    surveysLoading: (state, loading) => {
      state.surveysLoading = loading;
    }
  },
  actions: {
    setSelectedBottleneck({ state, commit, rootState }, id) {
      return new Promise((resolve, reject) => {
        if (id !== state.selectedBottleneck) {
          commit("selectedSurvey", null);
          commit("fairwayprofile/additionalSurvey", null, { root: true });
          commit("fairwayprofile/clearCurrentProfile", null, { root: true });
          commit("map/cutToolEnabled", false, { root: true });
          rootState.map.openLayersMaps.forEach(m => {
            m.getLayer("CUTTOOL")
              .getSource()
              .clear();
          });
        }
        commit("setSelectedBottleneck", id);
        if (id) {
          commit("surveysLoading", true);
          HTTP.get("/surveys?id=" + encodeURIComponent(id), {
            headers: {
              "X-Gemma-Auth": localStorage.getItem("token"),
              "Content-type": "text/xml; charset=UTF-8"
            }
          })
            .then(response => {
              const surveys = response.data.surveys.sort((a, b) =>
                a.date_info < b.date_info ? 1 : -1
              );
              commit("setSurveys", surveys);
              commit("setFirstSurveySelected");
              resolve(response);
            })
            .catch(error => {
              commit("setSurveys", []);
              commit("selectedSurvey", null);
              const { status, data } = error.response;
              displayError({
                title: "Backend Error",
                message: `${status}: ${data.message || data}`
              });
              reject(error);
            })
            .finally(() => commit("surveysLoading", false));
        } else {
          commit("setSurveys", []);
          resolve();
        }
      });
    },
    loadBottlenecksList({ commit }) {
      return new Promise((resolve, reject) => {
        var bottleneckFeatureCollectionRequest = new WFS().writeGetFeature({
          srsName: "EPSG:4326",
          featureNS: "gemma",
          featurePrefix: "gemma",
          featureTypes: ["bottleneck_overview"],
          outputFormat: "application/json"
        });
        HTTP.post(
          "/internal/wfs",
          new XMLSerializer().serializeToString(
            bottleneckFeatureCollectionRequest
          ),
          {
            headers: {
              "X-Gemma-Auth": localStorage.getItem("token"),
              "Content-type": "text/xml; charset=UTF-8"
            }
          }
        )
          .then(response => {
            commit("setBottlenecksList", response.data.features);
            resolve(response);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    loadBottlenecks({ commit }) {
      return new Promise((resolve, reject) => {
        var bottleneckFeatureCollectionRequest = new WFS().writeGetFeature({
          srsName: "EPSG:4326",
          featureNS: "gemma",
          featurePrefix: "gemma",
          featureTypes: ["bottlenecks_geoserver"],
          outputFormat: "application/json",
          propertyNames: [
            "bottleneck_id",
            "objnam",
            "responsible_country",
            "limiting",
            "reference_water_levels"
          ]
        });
        HTTP.post(
          "/internal/wfs",
          new XMLSerializer().serializeToString(
            bottleneckFeatureCollectionRequest
          ),
          {
            headers: {
              "X-Gemma-Auth": localStorage.getItem("token"),
              "Content-type": "text/xml; charset=UTF-8"
            }
          }
        )
          .then(response => {
            // Filter bottlenecks to get them unique with the latest time for each one.
            const bottlenecks = response.data.features;
            let btnIds = [],
              filteredBottlenceks = [];
            bottlenecks.forEach(btn => {
              const btnName = btn.properties.bottleneck_id;
              if (btnIds.indexOf(btnName) === -1) {
                btnIds.push(btnName);
                filteredBottlenceks.push(btn);
              } else {
                let btnToCompare = filteredBottlenceks.find(
                  b => b.properties.bottleneck_id === btnName
                );
                if (
                  compareAsc(
                    btn.properties.date_info,
                    btnToCompare.properties.date_info
                  ) === 1
                ) {
                  const index = filteredBottlenceks.findIndex(
                    x => x.properties.bottleneck_id === btnName
                  );
                  filteredBottlenceks[index] = btn;
                }
              }
            });
            commit("setBottlenecks", filteredBottlenceks);
            resolve(response);
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
};