From aa36b8d811e592d55d39a8ba6988478c7c715aa6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timoth=C3=A9e=20Poussard?= <tpoussard@neogeo.fr>
Date: Tue, 14 Sep 2021 16:04:35 +0200
Subject: [PATCH] fix project_mapping form with endpoints for basemaps and
 layers, left to do: change post in put

---
 .../project/ProjectMappingContextLayer.vue    |  4 +-
 src/main.js                                   |  3 +-
 src/store/index.js                            | 41 ++++++---
 src/store/modules/map.js                      | 92 ++++++++++++++-----
 .../feature_type/Feature_type_detail.vue      |  7 --
 5 files changed, 102 insertions(+), 45 deletions(-)

diff --git a/src/components/project/ProjectMappingContextLayer.vue b/src/components/project/ProjectMappingContextLayer.vue
index cca87b1a..13a1fb07 100644
--- a/src/components/project/ProjectMappingContextLayer.vue
+++ b/src/components/project/ProjectMappingContextLayer.vue
@@ -72,7 +72,9 @@ export default {
     selectedLayer: {
       get() {
         return {
-          name: this.layer ? this.layer.service : "",
+          name: this.layer
+            ? this.layers.find((el) => el.title === this.layer.title).service
+            : "",
           value: this.layer ? this.layer.title : "",
         };
       },
diff --git a/src/main.js b/src/main.js
index 1603b301..8fa1df52 100644
--- a/src/main.js
+++ b/src/main.js
@@ -11,7 +11,8 @@ Vue.config.productionTip = false
 axios.all([store.dispatch("USER_INFO"),
 store.dispatch("GET_ALL_PROJECTS"),
 store.dispatch("GET_STATIC_PAGES"),
-store.dispatch("GET_USER_LEVEL_PROJECTS") // * mock en attendant endpoint ou autre
+store.dispatch("GET_USER_LEVEL_PROJECTS"),
+store.dispatch("map/GET_LAYERS"),
 ]).then(axios.spread(function () {
   new Vue({
     router,
diff --git a/src/store/index.js b/src/store/index.js
index ccb328c4..f1fceb11 100644
--- a/src/store/index.js
+++ b/src/store/index.js
@@ -118,11 +118,13 @@ export default new Vuex.Store({
             password: payload.password,
           })
           .then((response) => {
-            // * use stored previous route to go back after login if page not open on login at first
-            const routerHistory = router.options.routerHistory[0].name !== "login" ? router.options.routerHistory : "/"
-            commit("SET_USER", response.data.user);
-            router.push(routerHistory[routerHistory.length - 1] || "/")
-            dispatch("GET_USER_LEVEL_PROJECTS");
+            if (response && response.status === 200) {
+              // * use stored previous route to go back after login if page not open on login at first
+              const routerHistory = router.options.routerHistory[0].name !== "login" ? router.options.routerHistory : "/"
+              commit("SET_USER", response.data.user);
+              router.push(routerHistory[routerHistory.length - 1] || "/")
+              dispatch("GET_USER_LEVEL_PROJECTS");
+            }
           })
           .catch(() => {
             commit("SET_USER", false);
@@ -134,9 +136,11 @@ export default new Vuex.Store({
       axios
         .get(`${DJANGO_API_BASE}user_info/`)
         .then((response) => {
-          const user = response.data.user;
-          commit("SET_USER", user);
-          window.localStorage.setItem("user", JSON.stringify(user));
+          if (response && response.status === 200) {
+            const user = response.data.user;
+            commit("SET_USER", user);
+            window.localStorage.setItem("user", JSON.stringify(user));
+          }
         }) // todo: ajouter au localestorage
         .catch(() => {
           router.push({ name: "login" });
@@ -146,9 +150,11 @@ export default new Vuex.Store({
     LOGOUT({ commit }) { // ? logout bien dans django ?
       axios
         .get(`${DJANGO_API_BASE}logout/`)
-        .then((/* response */) => { // todo: check status
-          commit("SET_USER", false); // ? better false or null
-          commit("SET_USER_LEVEL_PROJECTS", null);
+        .then((response) => { // todo: check status
+          if (response && response.status === 200) {
+            commit("SET_USER", false); // ? better false or null
+            commit("SET_USER_LEVEL_PROJECTS", null);
+          }
         })
         .catch((error) => {
           throw error;
@@ -159,7 +165,11 @@ export default new Vuex.Store({
     GET_USER_LEVEL_PROJECTS({ commit }) {
       axios
         .get(`${DJANGO_API_BASE}user-level-projects/`)
-        .then((response) => (commit("SET_USER_LEVEL_PROJECTS", response.data)))
+        .then((response) => {
+          if (response && response.status === 200) {
+            commit("SET_USER_LEVEL_PROJECTS", response.data)
+          }
+        })
         .catch((error) => {
           throw error;
         });
@@ -170,12 +180,17 @@ export default new Vuex.Store({
       dispatch("GET_PROJECT_LAST_MESSAGES", slug);
       dispatch("feature_type/GET_PROJECT_FEATURE_TYPES", slug);
       dispatch("feature/GET_PROJECT_FEATURES", slug);
+      dispatch("map/GET_BASEMAPS", slug);
     },
 
     GET_PROJECT_LAST_MESSAGES({ commit }, project_slug) {
       axios
         .get(`${DJANGO_API_BASE}projects/${project_slug}/comments`)
-        .then((response) => commit("SET_PROJECT_COMMENTS", response.data.last_comments))
+        .then((response) => {
+          if (response && response.status === 200) {
+            commit("SET_PROJECT_COMMENTS", response.data.last_comments)
+          }
+        })
         .catch((error) => {
           throw error;
         });
diff --git a/src/store/modules/map.js b/src/store/modules/map.js
index edda029e..233a1614 100644
--- a/src/store/modules/map.js
+++ b/src/store/modules/map.js
@@ -1,23 +1,15 @@
+const axios = require("axios");
 import { mapUtil } from "@/assets/js/map-util.js";
 
+const DJANGO_API_BASE = process.env.VUE_APP_DJANGO_API_BASE;
 
 const map = {
   namespaced: true,
   state: {
     basemaps: [],
+    basemapsToDelete: [],
     features: [],
-    layers: [
-      {
-        "id": 1,
-        "options": {
-          "maxZoom": 20,
-          "attribution": "© les contributeurs d’OpenStreetMap"
-        },
-        "title": "Open street map",
-        "service": "https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png",
-        "schema_type": "tms"
-      }
-    ],
+    layers: [],
     serviceMap: "https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png",
     optionsMap: {
       "attribution": "&copy; contributeurs d'<a href=\"https://osm.org/copyright\">OpenStreetMap</a>",
@@ -25,15 +17,18 @@ const map = {
     },
   },
   mutations: {
+    SET_LAYERS(state, layers) {
+      state.layers = layers;
+    },
     SET_BASEMAPS(state, basemaps) {
       state.basemaps = basemaps;
     },
     CREATE_BASEMAP(state, id) {
       state.basemaps = [...state.basemaps, { id, layers: [] }]
     },
-    DELETE_BASEMAP(state, id) {
-      state.basemaps = state.basemaps.filter(el => el.id !== id)
-    },
+    /*     DELETE_BASEMAP(state, id) {
+          state.basemaps = state.basemaps.filter(el => el.id !== id)
+        }, */
     UPDATE_BASEMAPS(state, basemaps) {
       state.basemaps = basemaps;
     },
@@ -48,10 +43,17 @@ const map = {
         }
       }
     },
+    DELETE_BASEMAP(state, basemapId) {
+      state.basemaps = state.basemaps.filter(el => el.id !== basemapId);
+      state.basemapsToDelete.push(basemapId);
+    },
+    REMOVE_BASEMAP_ID_TO_DELETE(state, basemapId) {
+      state.basemapsToDelete = state.basemapsToDelete.filter(el => el !== basemapId);
+    },
     DELETE_BASEMAP_LAYER(state, { basemapId, layerId }) {
       const index = state.basemaps.findIndex((el) => el.id === basemapId);
       if (index !== -1) {
-        state.basemaps[index].layers = state.basemaps[index].layers.filter((el) => el.dataKey !== layerId)
+        state.basemaps[index].layers = state.basemaps[index].layers.filter((el) => el.dataKey !== layerId);
       }
     },
     UPDATE_BASEMAP_LAYER(state, { basemapId, layerId, layer }) {
@@ -59,7 +61,7 @@ const map = {
       if (index !== -1) {
         state.basemaps[index].layers = state.basemaps[index].layers.map(
           (el) => el.dataKey === layerId ? layer : el
-        )
+        );
       }
     },
   },
@@ -75,6 +77,24 @@ const map = {
   },
 
   actions: {
+    GET_LAYERS({ commit }) {
+      axios
+        .get(`${DJANGO_API_BASE}layers/`)
+        .then((response) => (commit("SET_LAYERS", response.data)))
+        .catch((error) => {
+          throw error;
+        });
+    },
+
+    GET_BASEMAPS({ commit }, project_slug) {
+      axios
+        .get(`${DJANGO_API_BASE}base-maps/?project__slug=${project_slug}`)
+        .then((response) => (commit("SET_BASEMAPS", response.data)))
+        .catch((error) => {
+          throw error;
+        });
+    },
+
     INITIATE_MAP({ state, rootGetters, dispatch }) {
       const project = rootGetters.project
       let mapDefaultViewCenter = [46, 2]; // defaultMapView.center;
@@ -135,11 +155,37 @@ const map = {
       }
     },
 
-    //SAVE_BASEMAPS({ state }) {
-    // const data = JSON.stringify(state.basemaps);
-    // console.log("SAVE_BASEMAPS", data);
-    // todo : call axios POST
-    //}
-  }
+    SAVE_BASEMAPS({ state, dispatch }) {
+      console.log("SAVE_BASEMAPS", state.basemaps);
+      for (let basemap of state.basemaps) {
+        console.log("BASEMAP", basemap);
+        // TODO: À transformer en PUT dès que dispo
+        axios
+          .post(`${DJANGO_API_BASE}base-maps/`, basemap)
+          .then((response) => (console.log(response.data)))
+          .catch((error) => {
+            throw error;
+          });
+      }
+      for (let basemapId of state.basemapsToDelete) {
+        dispatch("DELETE_BASEMAP", basemapId);
+      }
+    },
+
+    DELETE_BASEMAP({ commit }, basemapId) {
+      console.log("DELETE_BASEMAP", basemapId);
+      axios
+        .delete(`${DJANGO_API_BASE}base-maps/`, basemapId)
+        .then((response) => {
+          if (response && response.status === 200) {
+            console.log(response.data)
+            commit("REMOVE_BASEMAP_ID_TO_DELETE", basemapId)
+          }
+        })
+        .catch((error) => {
+          throw error;
+        });
+    }
+  },
 }
 export default map
\ No newline at end of file
diff --git a/src/views/feature_type/Feature_type_detail.vue b/src/views/feature_type/Feature_type_detail.vue
index be60179f..5b642ab4 100644
--- a/src/views/feature_type/Feature_type_detail.vue
+++ b/src/views/feature_type/Feature_type_detail.vue
@@ -227,13 +227,6 @@ export default {
     },
   },
 
-  /*   watch: {
-    structure(newVal, oldVal) {
-      if (newVal !== oldVal) {
-        }
-    },
-  }, */
-
   methods: {
     toggleShowImport() {
       this.showImport = !this.showImport;
-- 
GitLab