view client/src/store/fairwayavailability.js @ 3678:8f58851927c0

client: make layer factory only return new layer config for individual maps instead of each time it is invoked. The purpose of the factory was to support multiple maps with individual layers. But returning a new config each time it is invoked leads to bugs that rely on the layer's state. Now this factory reuses the same objects it created before, per map.
author Markus Kottlaender <markus@intevation.de>
date Mon, 17 Jun 2019 17:31:35 +0200
parents 3d273d76a963
children 271683dee9bf
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):
 * Thomas Junk <thomas.junk@intevation.de>
 */

/*eslint no-unused-vars: ["error", { "varsIgnorePattern": "_" }]*/

import { HTTP } from "@/lib/http";
import {
  format,
  subYears,
  startOfMonth,
  endOfMonth,
  startOfYear,
  endOfYear,
  startOfQuarter,
  endOfQuarter
} from "date-fns";

const LIMITINGFACTORS = {
  WIDTH: "width",
  DEPTH: "depth"
};

const TYPES = {
  BOTTLENECK: "bottleneck",
  SECTION: "section",
  STRETCH: "stretch"
};

const FREQUENCIES = {
  MONTHLY: "monthly",
  QUARTERLY: "quarterly",
  YEARLY: "yearly"
};

const isoFormat = date => {
  return format(date, "YYYY-MM-DD");
};

const getIntervallBorders = (start, end, frequency) => {
  switch (frequency) {
    case FREQUENCIES.MONTHLY:
      return [isoFormat(startOfMonth(start)), isoFormat(endOfMonth(end))];
    case FREQUENCIES.YEARLY:
      return [isoFormat(startOfYear(start)), isoFormat(endOfYear(end))];
    case FREQUENCIES.QUARTERLY:
      return [isoFormat(startOfQuarter(start)), isoFormat(endOfQuarter(end))];
    default:
      throw new Error("Boom!");
  }
};

const init = () => {
  return {
    type: TYPES.BOTTLENECK,
    selectedFairwayAvailabilityFeature: null,
    to: isoFormat(new Date()),
    from: isoFormat(subYears(new Date(), 1)),
    frequency: FREQUENCIES.MONTHLY,
    limitingFactor: null,
    depthlimit1: 230,
    depthlimit2: 250,
    widthlimit1: null,
    widthlimit2: null,
    csv: null,
    fwData: null,
    fwLNWLData: null,
    fwLNWLOverviewData: [],
    legendLNWL: null,
    legend: null,
    LOS: 3
  };
};

/**
 * transformAFD
 * @param {string} csv
 *
 * takes the afd csv and transforms it to an intermediary format
 * for display of diagrams
 *
 * Incoming csv Format
 * #label,# <LDC ,# >= LDC [h],# < 230.00 [h],# >= 230.00 [h],# >= 250.00 [h]
 * 05-2019,215.500,0.000,0.000,215.500
 *
 * Format:
 * $LABEL, $LDC, $BELOWLIMIT1, $BETWEENLIMIT12, $ABOVELIMIT2^
 *
 * This format is assumed to be fix
 *
 */
const transformAFD = csv => {
  return csv.map(e => {
    const result = e.split(",");
    let [label, _, ldc, lower, middle, highestLevel] = result;
    let levelsWithSum = [
      {
        height: Number(lower),
        translateY: Number(middle)
      },
      {
        height: Number(middle),
        translateY: 0
      }
    ];
    return {
      label: label,
      ldc: ldc,
      highestLevel: highestLevel,
      lowerLevels: levelsWithSum
    };
  });
};

const fairwayavailability = {
  init,
  namespaced: true,
  state: init(),
  getters: {
    fwLNWLOverviewData: state => feature => {
      return state.fwLNWLOverviewData.find(
        d => d.feature.get("id") === feature.get("id")
      );
    }
  },
  mutations: {
    type: (state, type) => {
      state.type = type;
    },
    setLOS: (state, LOS) => {
      state.LOS = LOS;
    },
    setFrequency: (state, frequency) => {
      state.frequency = frequency;
    },
    setFrom: (state, from) => {
      state.from = from;
    },
    setTo: (state, to) => {
      state.to = to;
    },
    setDepthlimit1: (state, depthlimit1) => {
      state.depthlimit1 = depthlimit1;
    },
    setDepthlimit2: (state, depthlimit2) => {
      state.depthlimit2 = depthlimit2;
    },
    setWidthlimit1: (state, widthlimit1) => {
      state.widthlimit1 = widthlimit1;
    },
    setWidthlimit2: (state, widthlimit2) => {
      state.widthlimit2 = widthlimit2;
    },
    setSelectedFairwayAvailability: (state, feature) => {
      state.selectedFairwayAvailabilityFeature = feature;
    },
    setFwData: (state, fwData) => {
      state.fwData = fwData;
    },
    setFwLNWLData: (state, fwLNWLData) => {
      state.fwLNWLData = fwLNWLData;
    },
    setCSV: (state, csv) => {
      state.csv = csv;
    },
    addFwLNWLOverviewData: (state, data) => {
      let existingIndex = state.fwLNWLOverviewData.findIndex(
        d => d.feature.get("id") === data.feature.get("id")
      );
      if (existingIndex !== -1)
        state.fwLNWLOverviewData.splice(existingIndex, 1);
      state.fwLNWLOverviewData.push(data);
    },
    setLegend: (state, header) => {
      const headerEntries = header.split(",");
      headerEntries.shift();
      headerEntries.shift();
      state.legend = headerEntries.map(x => {
        let entry = x.split("#")[1]; // split leading #
        entry = entry.replace("[h]", "").trim(); // omit unit
        return entry;
      });
    },
    setLegendLNWL: (state, headerLNWL) => {
      this.headerLNWL = headerLNWL;
    }
  },
  actions: {
    loadAvailableFairwayDepth: ({ commit }, options) => {
      return new Promise((resolve, reject) => {
        const {
          feature,
          frequency,
          LOS,
          depthLimit1,
          depthLimit2,
          widthLimit1,
          widthLimit2,
          limitingFactor,
          type
        } = options;
        let { from, to } = options;
        let name = feature.hasOwnProperty("properties")
          ? feature.properties.name
          : feature.get("objnam");
        [from, to] = getIntervallBorders(from, to, frequency);
        let additionalParams = "";
        let endpoint = type;
        if (type === TYPES.BOTTLENECK) {
          if (limitingFactor === LIMITINGFACTORS.DEPTH)
            additionalParams = `&breaks=${depthLimit1},${depthLimit2}`;
          if (limitingFactor === LIMITINGFACTORS.WIDTH)
            additionalParams = `&breaks=${widthLimit1},${widthLimit2}`;
        } else if (type == TYPES.SECTION || type == TYPES.STRETCH) {
          additionalParams = `&depthbreaks=${depthLimit1},${depthLimit2}&widthbreaks=${widthLimit1},${widthLimit2}`;
        }
        const start = encodeURIComponent("00:00:00+00:00");
        const end = encodeURIComponent("23:59:59+00:00");
        const URL = `data/${endpoint}/fairway-depth/${encodeURIComponent(
          name
        )}?from=${from}T${start}&to=${to}T${end}&mode=${frequency}&los=${LOS}${additionalParams}`;
        HTTP.get(URL, {
          headers: { "X-Gemma-Auth": localStorage.getItem("token") }
        })
          .then(response => {
            const { data } = response;
            commit("setCSV", data);
            const csv = data.split("\n").filter(x => x !== ""); //omit empty lines
            commit("setLegend", csv.shift());
            let transformed = transformAFD(csv);
            commit("setFwData", transformed);
            resolve(response);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    loadAvailableFairwayDepthLNWL: (context, options) => {
      return new Promise((resolve, reject) => {
        const {
          feature,
          frequency,
          LOS,
          depthLimit1,
          depthLimit2,
          widthLimit1,
          widthLimit2,
          limitingFactor,
          type
        } = options;
        let { from, to } = options;
        let name = feature.hasOwnProperty("properties")
          ? feature.properties.name
          : feature.get("objnam");
        [from, to] = getIntervallBorders(from, to, frequency);
        const start = encodeURIComponent("00:00:00+00:00");
        const end = encodeURIComponent("23:59:59+00:00");
        let additionalParams = "";
        let endpoint = type || TYPES.BOTTLENECK;
        if (type === TYPES.BOTTLENECK) {
          if (limitingFactor === LIMITINGFACTORS.DEPTH)
            additionalParams = `&breaks=${depthLimit1},${depthLimit2}`;
          if (limitingFactor === LIMITINGFACTORS.WIDTH)
            additionalParams = `&breaks=${widthLimit1},${widthLimit2}`;
        } else if (type == TYPES.SECTION || type == TYPES.STRETCH) {
          additionalParams = `&depthbreaks=${depthLimit1},${depthLimit2}&widthbreaks=${widthLimit1},${widthLimit2}`;
        }
        const URL = `data/${endpoint}/availability/${encodeURIComponent(
          name
        )}?from=${from}T${start}&to=${to}T${end}&mode=${frequency}&los=${LOS}${additionalParams}`;
        HTTP.get(URL, {
          headers: { "X-Gemma-Auth": localStorage.getItem("token") }
        })
          .then(response => {
            const { data } = response;
            resolve(data);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    loadAvailableFairwayDepthLNWLDiagram: ({ commit, dispatch }, options) => {
      dispatch("loadAvailableFairwayDepthLNWL", options).then(response => {
        commit("setCSV", response);
        let data = response.split("\n").filter(d => d);
        data.shift(); // remove header line
        data = data.map(d => {
          let columns = d.split(",");
          return {
            date: columns[0],
            ldc: Number(columns[2]),
            below: Number(columns[3]),
            between: Number(columns[4]),
            above: Number(columns[5])
          };
        });
        commit("setFwLNWLData", data);
        return data;
      });
    },
    loadAvailableFairwayDepthLNWLForMap: ({ dispatch }, options) => {
      return dispatch("loadAvailableFairwayDepthLNWL", options).then(
        response => {
          let data = response.split("\n").filter(d => d);
          data.shift(); // remove header line
          data = data.map(d => {
            let columns = d.split(",");
            return {
              ldc: Number(columns[2]),
              below: Number(columns[3]),
              between: Number(columns[4]),
              above: Number(columns[5])
            };
          });
          return data[0];
        }
      );
    }
  }
};

export { LIMITINGFACTORS, FREQUENCIES, fairwayavailability };