Skip to content
Snippets Groups Projects
feature.js 6.89 KiB
Newer Older
import router from '../../router'
leandro's avatar
leandro committed
axios.defaults.headers.common['X-CSRFToken'] = (name => {
  var re = new RegExp(name + "=([^;]+)");
  var value = re.exec(document.cookie);
  return (value != null) ? unescape(value[1]) : null;
})('csrftoken');


const feature = {
  namespaced: true,
  state: {
    attachmentFormset: [],
    linkedFormset: [],
    features: [],
    form: null,
    extra_form: [],
    linked_features: [],
  },
  mutations: {
    SET_FEATURES(state, features) {
      state.features = features;
    },
    UPDATE_FORM(state, payload) {
      state.form = payload;
    },
    UPDATE_EXTRA_FORM(state, extra_form) {
      const index = state.extra_form.findIndex(el => el.label === extra_form.label);
      if (index !== -1) {
        state.extra_form[index] = extra_form;
      }
    },
    SET_EXTRA_FORM(state, extra_form) {
      state.extra_form = extra_form;
    },
    ADD_ATTACHMENT_FORM(state, attachmentFormset) {
      state.attachmentFormset = [...state.attachmentFormset, attachmentFormset];
    },
    UPDATE_ATTACHMENT_FORM(state, payload) {
      const index = state.attachmentFormset.findIndex((el) => el.dataKey === payload.dataKey);
      if (index !== -1) state.attachmentFormset[index] = payload
    },
    REMOVE_ATTACHMENT_FORM(state, payload) {
      state.attachmentFormset = state.attachmentFormset.filter(form => form.dataKey !== payload);
    },
    CLEAR_ATTACHMENT_FORM(state) {
      state.attachmentFormset = [];
    },
    ADD_LINKED_FORM(state, linkedFormset) {
      state.linkedFormset = [...state.linkedFormset, linkedFormset];
    },
    UPDATE_LINKED_FORM(state, payload) {
      const index = state.linkedFormset.findIndex((el) => el.dataKey === payload.dataKey);
      if (index !== -1) state.linkedFormset[index] = payload
    },
    REMOVE_LINKED_FORM(state, payload) {
      state.linkedFormset = state.linkedFormset.filter(form => form.dataKey !== payload);
    },
    SET_LINKED_FEATURES(state, payload) {
      state.linked_features = payload;
    },
Timothee P's avatar
Timothee P committed
    GET_PROJECT_FEATURES({ commit, rootState }, project_slug) {
      return axios
Timothee P's avatar
Timothee P committed
        .get(`${rootState.configuration.VUE_APP_DJANGO_API_BASE}projects/${project_slug}/feature/`)
Timothee P's avatar
Timothee P committed
          if (response.status === 200 && response.data) {
            const features = response.data.features;
            commit("SET_FEATURES", features);
            //dispatch("map/ADD_FEATURES", null, { root: true }); //todo: should check if map was initiated
          }
    SEND_FEATURE({ state, rootState, dispatch }, routeName) {
      const message = routeName === "editer-signalement" ? "Le signalement a été mis à jour" : "Le signalement a été crée";
      function redirect(featureId) {
        router.push({
          name: "details-signalement",
          params: {
            slug_type_signal: rootState.feature_type.current_feature_type_slug,
            slug_signal: featureId,
            message,
          },
        });
      }
      async function handleOtherForms(featureId) {
        await dispatch("SEND_ATTACHMENTS", featureId)
        await dispatch("PUT_LINKED_FEATURES", featureId)
        redirect(featureId);
      }

      let extraFormObject = {}; //* prepare an object to be flatten in properties of geojson
      for (const field of state.extra_form) {
        extraFormObject[field.name] = field.value;
      const geojson = {
        "id": state.form.feature_id,
        "type": "Feature",
        "geometry": state.form.geometry,
        "properties": {
          "title": state.form.title,
          "description": state.form.description.value,
          "status": state.form.status.value,
          "project": rootState.project_slug,
          "feature_type": rootState.feature_type.current_feature_type_slug,
      if (routeName === "editer-signalement") {
Timothee P's avatar
Timothee P committed
          .put(`${rootState.configuration.VUE_APP_DJANGO_API_BASE}features/${state.form.feature_id}/`, geojson)
Timothee P's avatar
Timothee P committed
            if (response.status === 200 && response.data) {
              if (state.attachmentFormset.length > 0 || state.linkedFormset.length > 0) {
                handleOtherForms(response.data.id)
              } else {
                redirect(response.data.id)
              }
Timothee P's avatar
Timothee P committed
            }
      } else {
        axios
Timothee P's avatar
Timothee P committed
          .post(`${rootState.configuration.VUE_APP_DJANGO_API_BASE}features/`, geojson)
Timothee P's avatar
Timothee P committed
            if (response.status === 201 && response.data) {
              if (state.attachmentFormset.length > 0 || state.linkedFormset.length > 0) {
                handleOtherForms(response.data.id)
              } else {
                redirect(response.data.id)
              }
Timothee P's avatar
Timothee P committed
            }
Timothee P's avatar
Timothee P committed
    SEND_ATTACHMENTS({ state, rootState }, featureId) {
Timothee P's avatar
Timothee P committed
      for (let attacht of state.attachmentFormset) {
        if (attacht.fileToImport) { //* if no new file imported abort, until beeing able to do PUT
          let formdata = new FormData();
          formdata.append("file", attacht.fileToImport, attacht.fileToImport.name);
          const data = {
            title: attacht.title,
            info: attacht.info,
          }
          formdata.append("data", JSON.stringify(data));
          axios
            .post(`${rootState.configuration.VUE_APP_DJANGO_API_BASE}features/${featureId}/attachments/`, formdata)
            .then((response) => {
              if (response.status === 200 && response.data) {
                console.log(response, response.data)
                return "La pièce jointe a bien été ajouté"
              }
            })
            .catch((error) => {
              throw error;
            });
Timothee P's avatar
Timothee P committed
        }
    PUT_LINKED_FEATURES({ state, rootState }, featureId) {
      return axios
        .put(`${rootState.configuration.VUE_APP_DJANGO_API_BASE}features/${featureId}/feature-links/`, state.linkedFormset)
        .then((response) => {
          if (response.status === 200 && response.data) {
            console.log(response, response.data)
            return "La relation a bien été ajouté"
          }
        })
        .catch((error) => {
          throw error;
        });
    },

Timothee P's avatar
Timothee P committed
    DELETE_FEATURE({ state, rootState }, feature_id) {
leandro's avatar
leandro committed
      console.log("Deleting feature:", feature_id, state)
      const url = `${rootState.configuration.VUE_APP_DJANGO_API_BASE}features/${feature_id}`;
      return axios
        .delete(url)
        .then((response) => response)
        .catch(() => {
          return false;
        });
leandro's avatar
leandro committed
    },
export default feature