Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • geocontrib/geocontrib-frontend
  • ext_matthieu/geocontrib-frontend
  • fnecas/geocontrib-frontend
  • MatthieuE/geocontrib-frontend
4 results
Show changes
Showing
with 2934 additions and 1121 deletions
......@@ -26,15 +26,19 @@ if (process.env.NODE_ENV === 'production') {
console.log('New content is downloading.');
},
updated (registration) {
alert('Une nouvelle version de l\'application est disponible, l\'application va se recharger');
console.log('New content is available; please refresh.');
//
if (!registration || !registration.waiting) {
return;
if (!navigator.webdriver) {
alert('Une nouvelle version de l\'application est disponible, l\'application va se recharger');
console.log('New content is available; please refresh.');
//
if (!registration || !registration.waiting) {
return;
}
// Send message to SW to skip the waiting and activate the new SW
registration.waiting.postMessage({ type: 'SKIP_WAITING' });
//window.location.reload(true);
} else {
console.log('Execution dans un navigateur controlé par un agent automatisé, la mise à jour n\'est pas appliqué pendant le test.');
}
// Send message to SW to skip the waiting and activate the new SW
registration.waiting.postMessage({ type: 'SKIP_WAITING' });
//window.location.reload(true);
},
offline () {
console.log('No internet connection found. App is running in offline mode.');
......
import Vue from 'vue';
import VueRouter from 'vue-router';
import ProjectsList from '../views/Projects/ProjectsList.vue';
import store from '@/store';
import featureAPI from '@/services/feature-api';
Vue.use(VueRouter);
......@@ -16,12 +18,24 @@ const routes = [
component: ProjectsList
},
{
path: `${projectBase === 'projet' ? '': '/' + projectBase + '/:slug'}/connexion/`,
path: `${projectBase === 'projet' ? '': `/${projectBase}/:slug`}/connexion/`,
name: 'login',
props: true,
component: () => import('../views/Login.vue')
},
{
path: `${projectBase === 'projet' ? '': `/${projectBase}/:slug`}/inscription/`,
name: 'signup',
component: () => import('../views/Login.vue')
},
{
path: `${projectBase === 'projet' ? '': `/${projectBase}/:slug`}/inscription/succes`,
name: 'sso-signup-success',
props: true,
component: () => import('../views/Login.vue')
},
{
path: `${projectBase === 'projet' ? '': '/' + projectBase + '/:slug'}/my_account/`,
path: `${projectBase === 'projet' ? '': `/${projectBase}/:slug`}/my_account/`,
name: 'my_account',
component: () => import('../views/Account.vue')
},
......@@ -77,6 +91,11 @@ const routes = [
name: 'project_members',
component: () => import('../views/Project/ProjectMembers.vue')
},
{
path: `/${projectBase}/:slug/signalement-filtre/`,
name: 'details-signalement-filtre',
component: () => import('../views/Feature/FeatureDetail.vue')
},
// * FEATURE TYPE
{
path: `/${projectBase}/:slug/type-signalement/ajouter/`,
......@@ -100,9 +119,9 @@ const routes = [
component: () => import('../views/FeatureType/FeatureTypeEdit.vue')
},
{
path: `/${projectBase}/:slug/type-signalement/:slug_type_signal/symbologie/`,
name: 'editer-symbologie-signalement',
component: () => import('../views/FeatureType/FeatureTypeSymbology.vue')
path: `/${projectBase}/:slug/type-signalement/:slug_type_signal/affichage/`,
name: 'editer-affichage-signalement',
component: () => import('../views/FeatureType/FeatureTypeDisplay.vue')
},
// * FEATURE
{
......@@ -113,7 +132,66 @@ const routes = [
{
path: `/${projectBase}/:slug/type-signalement/:slug_type_signal/signalement/:slug_signal`,
name: 'details-signalement',
component: () => import('../views/Feature/FeatureDetail.vue')
component: () => import('../views/Feature/FeatureDetail.vue'),
/**
* Handles routing logic before entering the details-signalement route.
* This function manages access and navigation based on user permissions and feature data.
*/
beforeEnter: async (to, from, next) => {
try {
const { slug, slug_type_signal, slug_signal } = to.params;
// Retrieve the project details from the store
const project = await store.dispatch('projects/GET_PROJECT', slug);
// Prepare query based on the project settings for feature browsing
const query = { ordering: project.feature_browsing_default_sort };
// Check if the default filter of the project is set to feature_type and apply it
if (project.feature_browsing_default_filter) { // when feature_type is the default filter of the project,
query['feature_type_slug'] = slug_type_signal; // set feature_type slug in query
}
// Get the feature's position based on the feature slug and query settings
const offset = await featureAPI.getFeaturePosition(slug, slug_signal, query);
// Decide next routing based on the offset result
if (offset >= 0) {
next({
name: 'details-signalement-filtre',
params: { slug },
query: { ...query, offset }
});
} else if (offset === 'No Content') {
// API return no content when user is not allowed to see the feature or isn't connected
if (store.state.user) {
// If the user is connected, display information that he's not allowed to view the feature
store.commit('DISPLAY_MESSAGE', { comment: 'Vous n\'avez pas accès à ce signalement avec cet utilisateur', level: 'negative' });
// and redirect to main page
next({ path: '/' });
} else {
// If the user is not connected, remove other messages to avoid displaying twice that the user is not connected
store.commit('CLEAR_MESSAGES');
// display information that user need to be connected
store.commit('DISPLAY_MESSAGE', { comment: 'Vous n\'avez pas accès à ce signalement hors connexion, veuillez-vous connecter au préalable', level: 'negative' });
// Then redirect to login page
if (store.state.configuration.VUE_APP_LOGIN_URL) {
// If the login is through SSO, redirect to external login page (if the instance accepts a redirect_url it would be caught before when requesting user_info with GET_USER_INFO)
setTimeout(() => { // delay switching page to allow the info message to be read by user
window.open(store.state.configuration.VUE_APP_LOGIN_URL);
}, 1500);
} else {
// In a classic installation, redirect to the login page of this application
next({ name: 'login' });
}
}
} else {
store.commit('DISPLAY_MESSAGE', { comment: 'Désolé, une erreur est survenue pendant la recherche du signalement', level: 'negative' });
next({ path: '/' });
}
} catch (error) {
console.error('error', error);
store.commit('DISPLAY_MESSAGE', { comment: `Désolé, une erreur est survenue pendant la recherche du signalement - ${error}`, level: 'negative' });
next({ path: '/' });
}
}
},
{
path: `/${projectBase}/:slug/type-signalement/:slug_type_signal/offline`,
......@@ -125,6 +203,11 @@ const routes = [
name: 'editer-signalement',
component: () => import('../views/Feature/FeatureEdit.vue')
},
{
path: `/${projectBase}/:slug/type-signalement/:slug_type_signal/editer-signalements-attributs/`,
name: 'editer-attribut-signalement',
component: () => import('../views/Feature/FeatureEdit.vue')
},
{
path: '/projet/:slug/catalog/:feature_type_slug',
......@@ -132,6 +215,12 @@ const routes = [
component: () => import('../views/Catalog.vue')
},
{
path: '/projet/:slug/type-signalement/:slug_type_signal/signalement/:slug_signal/attachment-preview/',
name: 'attachment-preview',
component: () => import('../views/AttachmentPreview.vue')
},
{ path: '/:pathMatch(.*)*', name: 'NotFound', component: () => import('../views/NotFound.vue') },
];
......
......@@ -5,7 +5,7 @@ if (workbox) {
//workbox.core.setLogLevel(workbox.core.LOG_LEVELS.debug)
// apply precaching. In the built version, the precacheManifest will
// be imported using importScripts (as is workbox itself) and we can
// be imported using importScripts (as is workbox itself) and we can
// precache this. This is all we need for precaching
workbox.precaching.precacheAndRoute(self.__precacheManifest);
......@@ -74,7 +74,6 @@ self.addEventListener('message', (e) => {
if (!e.data) {
return;
}
//console.log(e.data);
switch (e.data.type) {
case 'SKIP_WAITING':
self.skipWaiting();
......
import { Draw } from 'ol/interaction';
import GeometryType from 'ol/geom/GeometryType';
import { Draw, Snap } from 'ol/interaction';
import Modify from 'ol/interaction/Modify';
import Select from 'ol/interaction/Select';
import { Collection } from 'ol';
import MultiPoint from 'ol/geom/MultiPoint';
import Point from 'ol/geom/Point';
import {
Fill, Stroke, Style, Circle, Text //RegularShape, Circle as CircleStyle, Text,Icon
} from 'ol/style';
......@@ -13,46 +11,93 @@ import mapService from '@/services/map-service';
import { buffer } from 'ol/extent';
const editionService = {
drawnFeature: null,
featureToEdit: null,
editing_feature: {},
geom_type: 'linestring',
drawStyle: new Style({
fill: new Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new Stroke({
color: 'rgba(0, 0, 255, 0.5)',
lineDash: [],
width: 2
}),
image: new Circle({
radius: 7,
stroke: new Stroke({
color: 'rgba(255, 0, 0, 0.5)',
lineDash: [],
width: 2
}),
fill: new Fill({
color: 'rgba(255, 255, 255, 0.5)'
})
}),
text: new Text({
font: '12px Calibri,sans-serif',
fill: new Fill({ color: '#000' }),
stroke: new Stroke({
color: '#fff',
width: 1
// Création d'une collection filtrée
filteredFeatures: new Collection(),
// Méthode pour créer un style basé sur la couleur actuelle
createDrawStyle(isEditing) {
return [
new Style({
// Style principal pour le polygone
fill: new Fill({
color: isEditing ? 'rgba(255, 145, 0, .2)' : 'rgba(255, 255, 255, .2)',
}),
// Style principal pour la ligne et le tour du polygone
stroke: new Stroke({
color: isEditing ? 'rgba(255, 145, 0, .9)' : 'rgba(255, 45, 0, 0.5)',
lineDash: [],
width: 2,
}),
// Style principal pour le point
image: new Circle({
radius: 7,
stroke: new Stroke({
color: 'rgba(255, 0, 0, 0.5)',
lineDash: [],
width: 2
}),
fill: new Fill({
color: isEditing ? 'rgba(255, 145, 0, 0.9)' : 'rgba(255, 255, 255, 0.5)'
})
}),
// Style pour le texte, pas utilisé mais peut être conservé au cas où
text: new Text({
font: '12px Calibri,sans-serif',
fill: new Fill({ color: '#000' }),
stroke: new Stroke({
color: '#fff',
width: 1
}),
text: ''
}),
zIndex: 50
}),
text: ''
}),
zIndex: 50
}),
// Style pour afficher des points sur les sommets de ligne ou polygone (seulement en mode édition)
...(isEditing
? [
// Définition du style de point
new Style({
image: new Circle({
radius: 5,
stroke: new Stroke({
color: 'rgba(255, 145, 0, .9)',
width: 2,
}),
fill: new Fill({
color: 'rgba(255, 145, 0, .5)',
}),
}),
// Récupération des sommets où afficher les points uniquement pour ligne et polygone
geometry: function (feature) {
const geometry = feature.getGeometry();
if (geometry.getType() === 'LineString') {
return new MultiPoint(geometry.getCoordinates()); // Sommets de la ligne
} else if (geometry.getType() === 'Polygon') {
return new MultiPoint(geometry.getCoordinates()[0]); // Sommets du premier anneau
}
return null;
},
}),
]
: []),
];
},
// Méthode pour changer la couleur de la géométrie existante en passant en mode édition
toggleEditionColor(isEditing) {
const drawStyle = this.createDrawStyle(isEditing); // Re-crée le style
this.drawnItems.setStyle(drawStyle); // Applique le style à la couche
},
setEditingFeature(feature) {
this.editing_feature = feature;
},
startEditFeature(feature){
this.editing_feature=feature;
initFeatureToEdit(feature) {
this.editing_feature = feature;
this.draw.setActive(false);
this.drawSource.addFeature(feature);
this.drawnItems.setZIndex(50);
......@@ -60,104 +105,70 @@ const editionService = {
},
addEditionControls(geomType) {
this.geom_type=geomType;
this.geom_type = geomType;
this.drawSource = new VectorSource();
this.drawnItems = new VectorLayer({
source: this.drawSource,
style: this.drawStyle,
style: this.createDrawStyle(),
zIndex: 4000
});
window.olMap = mapService.getMap();
mapService.getMap().addLayer(this.drawnItems);
if (this.draw) {
mapService.getMap().removeInteraction(this.draw);
}
let gType = GeometryType.POINT;
let gType = 'Point';
if (geomType.toUpperCase().indexOf('POLYGON') >= 0) {
gType = GeometryType.POLYGON;
gType = 'Polygon';
}
else if (geomType.toUpperCase().indexOf('LINE') >= 0) {
gType = GeometryType.LINE_STRING;
gType = 'LineString';
}
this.draw = new Draw({
source: this.drawSource,
type: gType,
style: this.drawStyle,
//geometryName: layer.getGeomAttributeName()
style: this.createDrawStyle()
});
mapService.getMap().addInteraction(this.draw);
this.setEditingFeature(undefined);
this.draw.on('drawend', (evt) => {
var feature = evt.feature;
console.log(feature);
this.drawnFeature = feature;
this.setEditingFeature(feature);
this.draw.setActive(false);
});
this.selectForUpdate = new Select({
style: [
this.drawStyle,
new Style({
image: new Circle({
radius: 5,
fill: new Fill({
color: 'orange',
}),
}),
geometry: function (feature) {
// return the coordinates of the first ring of the polygon
const coordinates = feature.getGeometry().getCoordinates()[0];
if (feature.getGeometry() instanceof Point){
return feature.getGeometry();
}
return new MultiPoint(coordinates);
},
})
]
});
this.modify = new Modify({
style: this.drawStyle,
features: this.selectForUpdate.getFeatures()
style: this.createDrawStyle(),
features: this.filteredFeatures, // Limite la modification aux entités filtrées
});
// je garde ce bout de code pour l'implementation a venir du snapping
//snapping
// var snap = new Snap({
// source: this.drawSource
//});
// This workaround allows to avoid the ol freeze
// referenced bug : https://github.com/openlayers/openlayers/issues/6310
// May be corrected in a future version
this.modify.handleUpEvent_old = this.modify.handleUpEvent;
this.modify.handleUpEvent = function (evt) {
try {
try {
this.handleUpEvent_old(evt);
} catch (ex) {
console.log(ex);
} catch (ex) {
console.log(ex);
}
};
mapService.getMap().addInteraction(this.selectForUpdate);
mapService.getMap().addInteraction(this.modify);
// je garde ce bout de code pour l'implementation a venir du snapping
//map.addInteraction(snap);
// Supprime dynamiquement la feature des entités modifiables
this.drawSource.on('removefeature', (event) => {
const feature = event.feature;
this.filteredFeatures.remove(feature);
});
},
resetAllTools() {
if (this.draw) {
this.draw.setActive(false);
}
if (this.selectForDeletion) {
this.removeSelectInteraction(this.selectForDeletion);
}
if (this.selectForUpdate) {
this.removeSelectInteraction(this.selectForUpdate);
}
if (this.modify) {
this.modify.setActive(false);
}
......@@ -166,62 +177,106 @@ const editionService = {
interaction.getFeatures().clear();
interaction.setActive(false);
},
activeUpdateFeature() {
activeUpdateFeature(isEditing) {
this.resetAllTools();
this.modify.setActive(true);
this.selectForUpdate.setActive(true);
this.selectForUpdate.getFeatures().push(this.editing_feature);
},
activeDeleteFeature() {
this.resetAllTools();
if (!this.selectForDeletion) {
var style = new Style({
fill: new Fill({
color: 'rgba(255, 0, 0, 0.2)'
}),
stroke: new Stroke({
color: 'rgba(255, 0, 0, 0.5)',
width: 2
}),
image: new Circle({
radius: 7,
fill: new Fill({
color: 'rgba(255, 0, 0, 0.5)'
})
}),
text: new Text({
font: '12px Calibri,sans-serif',
fill: new Fill({ color: 'rgba(255, 0, 0, 0.5)' }),
}),
zIndex: 50
});
this.selectForDeletion = new Select({ style: style });
mapService.getMap().addInteraction(this.selectForDeletion);
// Lorsque de nouvelles features sont sélectionnées
let selected_features = this.selectForDeletion.getFeatures();
this.listenerKey = selected_features.on('add', (evt) => {
var feature = evt.element;
if (feature) {
setTimeout(() => {
if (confirm('Etes-vous sur de vouloir supprimer cet objet ?')) {
// supprimer l'edition de la sélection
this.selectForDeletion.getFeatures().clear();
// supprimer l'edition de la carte
this.drawSource.removeFeature(feature);
this.editing_feature = undefined;
this.draw.setActive(true);
this.selectForDeletion.setActive(false);
}
}, 300);
if (isEditing) {
// Mise à jour des entités modifiables
this.drawSource.forEachFeature((feature) => {
if (
(this.featureToEdit && feature.id_ === this.featureToEdit.id) ||
(this.drawnFeature && feature.ol_uid === this.drawnFeature.ol_uid) ||
(!this.drawnFeature && !this.featureToEdit)
) {
this.filteredFeatures.push(feature);
}
});
} else {
this.selectForDeletion.setActive(true);
this.modify.setActive(true);
}
this.toggleEditionColor(isEditing);
},
/**
* Deletes the currently displayed feature from the map.
* This method removes the feature directly from the source without additional selection steps.
* It assumes that there is only one feature present in the source.
* Resets the color for future drawings to the default to ensure that the editing color
* is not displayed if the edit mode was active prior to deletion.
*/
removeFeatureFromMap() {
// Access the source where the features are stored
const source = this.drawSource; // Replace with the correct reference to your OpenLayers source
// Get all features from the source
const features = source.getFeatures();
// Check if there is a feature to delete
if (features.length > 0 && confirm('Etes-vous sur de vouloir supprimer cet objet ?')) {
try {
// Reset all other tools to ensure only the delete feature functionality is active
this.resetAllTools();
// Remove the feature from the source
const featureToRemove = features[0];
source.removeFeature(featureToRemove);
// Reinitialize the feature edited on the map
this.editing_feature = undefined;
// Toggle draw mode to create a new feature
this.draw.setActive(true);
// Reset color to default
this.toggleEditionColor(false);
// Return operation result after user confirmed to remove the feature
return true;
} catch (error) {
// Log an error if the feature cannot be removed
console.error('Error while deleting the feature: ', error);
}
}
return false;
},
setFeatureToEdit(feature) {
this.featureToEdit = feature;
},
removeActiveFeatures() {
this.drawnFeature = null;
this.featureToEdit = null;
},
addSnapInteraction(map) {
// The snap interaction must be added after the Modify and Draw interactions
// in order for its map browser event handlers to be fired first. Its handlers
// are responsible of doing the snapping.
// Since we can't give a list of source to snap,
// we use this workaround, an interaction collection: https://github.com/openlayers/openlayers/issues/7100
let interactions = [];
map.getLayers().forEach((layer) => {
if (layer instanceof VectorLayer) {
let interaction = new Snap({
source: layer.getSource()
});
interactions.push(interaction);
}
});
for(let snap of interactions ) {
map.addInteraction(snap);
}
},
removeSnapInteraction(map) {
// Find the double click interaction that is on the map.
let interactions = [];
map.getInteractions().forEach(function (interaction) {
if (interaction instanceof Snap) {
interactions.push(interaction);
}
});
// Remove the interaction from the map.
for(let snap of interactions ) {
map.removeInteraction(snap);
}
}
};
export default editionService;
\ No newline at end of file
export default editionService;
import axios from '@/axios-client.js';
import store from '../store';
const baseUrl = store.state.configuration.VUE_APP_DJANGO_API_BASE;
const featureAPI = {
async getFeaturesBbox(project_slug, queryParams) {
async getFeaturesBbox(project_slug, queryString) {
const baseUrl = store.state.configuration.VUE_APP_DJANGO_API_BASE;
const response = await axios.get(
`${baseUrl}projects/${project_slug}/feature-bbox/${queryParams ? '?' + queryParams : ''}`
`${baseUrl}projects/${project_slug}/feature-bbox/${queryString ? '?' + queryString : ''}`
);
if (
response.status === 200 &&
......@@ -22,8 +21,28 @@ const featureAPI = {
}
},
async getProjectFeature(project_slug, feature_id) {
const baseUrl = store.state.configuration.VUE_APP_DJANGO_API_BASE;
const response = await axios.get(
`${baseUrl}v2/features/${feature_id}/?project__slug=${project_slug}`
);
if (
response.status === 200 &&
response.data
) {
return response.data;
} else {
return null;
}
},
async getPaginatedFeatures(url) {
const response = await axios.get(url);
// Cancel any ongoing search request.
store.dispatch('CANCEL_CURRENT_SEARCH_REQUEST');
// Prepare the cancel token for the new request and store it.
const cancelToken = axios.CancelToken.source();
store.commit('SET_CANCELLABLE_SEARCH_REQUEST', cancelToken);
const response = await axios.get(url, { cancelToken: cancelToken.token });
if (
response.status === 200 &&
response.data
......@@ -35,6 +54,7 @@ const featureAPI = {
},
async getFeatureEvents(featureId) {
const baseUrl = store.state.configuration.VUE_APP_DJANGO_API_BASE;
const response = await axios.get(
`${baseUrl}features/${featureId}/events/`
);
......@@ -49,6 +69,7 @@ const featureAPI = {
},
async getFeatureAttachments(featureId) {
const baseUrl = store.state.configuration.VUE_APP_DJANGO_API_BASE;
const response = await axios.get(
`${baseUrl}features/${featureId}/attachments/`
);
......@@ -63,6 +84,7 @@ const featureAPI = {
},
async getFeatureLinks(featureId) {
const baseUrl = store.state.configuration.VUE_APP_DJANGO_API_BASE;
const response = await axios.get(
`${baseUrl}features/${featureId}/feature-links/`
);
......@@ -88,17 +110,16 @@ const featureAPI = {
return null;
}
},
// todo : fonction pour faire un post ou un put du signalement
async postOrPutFeature({ method, feature_id, feature_type__slug, project__slug, data }) {
let url = `${baseUrl}features/`;
const baseUrl = store.state.configuration.VUE_APP_DJANGO_API_BASE;
let url = `${baseUrl}v2/features/`;
if (method === 'PUT') {
url += `${feature_id}/?
feature_type__slug=${feature_type__slug}
&project__slug=${project__slug}`;
}
const response = await axios({
url,
method,
......@@ -112,7 +133,8 @@ const featureAPI = {
},
async updateFeature({ feature_id, feature_type__slug, project__slug, newStatus }) {
const url = `${baseUrl}features/${feature_id}/?feature_type__slug=${feature_type__slug}&project__slug=${project__slug}`;
const baseUrl = store.state.configuration.VUE_APP_DJANGO_API_BASE;
const url = `${baseUrl}v2/features/${feature_id}/?feature_type__slug=${feature_type__slug}&project__slug=${project__slug}`;
const response = await axios({
url,
......@@ -126,7 +148,39 @@ const featureAPI = {
}
},
async projectFeatureBulkUpdateStatus(projecSlug, queryString, newStatus) {
const baseUrl = store.state.configuration.VUE_APP_DJANGO_API_BASE;
const url = `${baseUrl}projects/${projecSlug}/feature-bulk-modify/?${queryString}`;
const response = await axios({
url,
method: 'PUT',
data: { status: newStatus }
});
if (response.status === 200 && response.data) {
return response;
} else {
return null;
}
},
async projectFeatureBulkDelete(projecSlug, queryString) {
const baseUrl = store.state.configuration.VUE_APP_DJANGO_API_BASE;
const url = `${baseUrl}projects/${projecSlug}/feature-bulk-modify/?${queryString}`;
const response = await axios({
url,
method: 'DELETE'
});
if (response.status === 200 && response.data) {
return response;
} else {
return null;
}
},
async postComment({ featureId, comment }) {
const baseUrl = store.state.configuration.VUE_APP_DJANGO_API_BASE;
const response = await axios.post(
`${baseUrl}features/${featureId}/comments/`, { comment }
);
......@@ -140,10 +194,12 @@ const featureAPI = {
}
},
async postCommentAttachment({ featureId, file, fileName, commentId, title }) {
async postCommentAttachment({ featureId, file, fileName, title, isKeyDocument, commentId }) {
const baseUrl = store.state.configuration.VUE_APP_DJANGO_API_BASE;
const formdata = new FormData();
formdata.append('file', file, fileName);
formdata.append('title', title);
formdata.append('is_key_document', isKeyDocument);
const response = await axios.put(
`${baseUrl}features/${featureId}/comments/${commentId}/upload-file/`, formdata
......@@ -157,6 +213,18 @@ const featureAPI = {
return null;
}
},
async getFeaturePosition(projectSlug, featureId, query) {
const searchParams = new URLSearchParams(query);
const baseUrl = store.state.configuration.VUE_APP_DJANGO_API_BASE;
const response = await axios.get(`${baseUrl}projects/${projectSlug}/feature/${featureId}/position-in-list/?${searchParams.toString()}`);
if (response && response.status === 200) {
return response.data;
} else if (response.status === 204) {
return response.statusText;
}
return null;
},
};
export default featureAPI;
import axios from '@/axios-client.js';
import store from '../store';
import store from '@/store';
const baseUrl = store.state.configuration.VUE_APP_DJANGO_API_BASE;
const featureTypeAPI = {
async deleteFeatureType(featureType_slug) {
const response = await axios.delete(
`${baseUrl}feature-types/${featureType_slug}`
`${baseUrl}v2/feature-types/${featureType_slug}/`
);
if (
response.status === 204
......
......@@ -10,14 +10,14 @@ const mapAPI = {
basemap['project'] = projectSlug;
if (newBasemapIds.includes(basemap.id)) {
return axios
.post(`${baseUrl}base-maps/`, basemap)
.post(`${baseUrl}v2/base-maps/`, basemap)
.then((response) => response)
.catch((error) => {
throw error;
});
} else {
return axios
.put(`${baseUrl}base-maps/${basemap.id}/`, basemap)
.put(`${baseUrl}v2/base-maps/${basemap.id}/`, basemap)
.then((response) => response)
.catch((error) => {
throw error;
......
import TileWMS from 'ol/source/TileWMS';
import axios from '@/axios-client.js';
import { View, Map } from 'ol';
import { ScaleLine, Zoom, Attribution } from 'ol/control';
import { ScaleLine, Zoom, Attribution, FullScreen } from 'ol/control';
import TileLayer from 'ol/layer/Tile';
import { transform, transformExtent } from 'ol/proj.js';
import { transform, transformExtent, fromLonLat } from 'ol/proj';
import { defaults } from 'ol/interaction';
import XYZ from 'ol/source/XYZ';
import VectorTileLayer from 'ol/layer/VectorTile';
......@@ -11,35 +10,44 @@ import VectorTileSource from 'ol/source/VectorTile';
import { MVT, GeoJSON } from 'ol/format';
import { boundingExtent } from 'ol/extent';
import Overlay from 'ol/Overlay';
import {
Fill, Stroke, Style, Circle //RegularShape, Circle as CircleStyle, Text,Icon
} from 'ol/style';
import { Fill, Stroke, Style, Circle } from 'ol/style';
import { asArray } from 'ol/color';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import { fromLonLat } from 'ol/proj.js';
import OverlayPositioning from 'ol/OverlayPositioning';
import WMTSTileGrid from 'ol/tilegrid/WMTS';
import WMTS, { optionsFromCapabilities } from 'ol/source/WMTS';
import WMTSCapabilities from 'ol/format/WMTSCapabilities';
import Geolocation from 'ol/Geolocation.js';
import Feature from 'ol/Feature.js';
import Point from 'ol/geom/Point.js';
import { applyStyle } from 'ol-mapbox-style';
import { isEqual } from 'lodash';
let dictLayersToLeaflet = {};
let statusList = [
{
name: 'Brouillon',
value: 'draft',
},
{
name: 'Publié',
value: 'published',
},
{
name: 'Archivé',
value: 'archived',
},
{
name: 'En attente de publication',
value: 'pending',
},
];
import axios from '@/axios-client.js';
import router from '@/router';
import store from '@/store';
import { retrieveFeatureProperties } from '@/utils';
const parser = new WMTSCapabilities();
let dictLayersToMap = {};
let layersCount = 0;
const geolocationStyle = new Style({
image: new Circle({
radius: 6,
fill: new Fill({
color: '#3399CC',
}),
stroke: new Stroke({
color: '#fff',
width: 2,
}),
}),
});
const mapService = {
layers: [],
......@@ -52,45 +60,73 @@ const mapService = {
map: undefined,
queryParams: {},
geolocation: undefined, // for geolocation
geolocationSource: null, // for geolocation
positionFeature: null, // for geolocation
lastPosition: null, // for geolocation
getMap() {
return this.map;
},
destroyMap() {
this.map=undefined;
this.map = undefined;
},
createMap(el, options) {
const {
lat,
lng,
mapDefaultViewCenter,
mapDefaultViewZoom,
maxZoom,
zoom,
zoomControl = true,
fullScreenControl = false,
geolocationControl = false,
interactions = { doubleClickZoom: false, mouseWheelZoom: false, dragPan: true },
controls = [
new Attribution({ collapsible: false }),
new ScaleLine({
units: 'metric',
}),
],
} = options;
this.map = new Map({
if (fullScreenControl) {
controls.push(new FullScreen({ tipLabel: 'Mode plein écran' }));
}
const mapOptions = {
layers: [],
target: el,
controls: [
new Attribution(),
new ScaleLine({
units: 'metric',
})],
controls,
interactions: defaults(interactions),
view: new View({
center: transform([
!lng ? mapDefaultViewCenter[1] : lng,
!lat ? mapDefaultViewCenter[0] : lat,
center: transform([ //* since 0 is considered false, check for number instead of just defined (though boolean will pass through)
Number(lng) ? lng : mapDefaultViewCenter[1],
Number(lat) ? lat : mapDefaultViewCenter[0],
], 'EPSG:4326', 'EPSG:3857'),
zoom: !zoom ? mapDefaultViewZoom : zoom
zoom: Number(mapDefaultViewZoom) ? mapDefaultViewZoom : zoom,
maxZoom
}),
});
};
this.map = new Map(mapOptions);
if (zoomControl) {
this.map.addControl(new Zoom({ zoomInTipLabel: 'Zoomer', zoomOutTipLabel: 'Dézoomer' }));
}
if (geolocationControl) {
this.initGeolocation();
}
this.map.once('rendercomplete', () => {
this.map.updateSize();
});
......@@ -106,93 +142,150 @@ const mapService = {
},
});
let overlay = this.overlay;
closer.onclick = function () {
overlay.setPosition(undefined);
closer.blur();
return false;
};
if (closer) {
closer.onclick = function () {
overlay.setPosition(undefined);
closer.blur();
return false;
};
}
this.map.addOverlay(this.overlay);
this.map.on('click', this.onMapClick.bind(this));
// catch event from sidebarLayer to update layers order (since all maps use it now)
document.addEventListener('change-layers-order', (event) => {
// Reverse is done because the first layer in order has to be added in the map in last.
// Slice is done because reverse() changes the original array, so we make a copy first
this.updateOrder(event.detail.layers.slice().reverse());
});
return this.map;
},
onMapClick(event) {
let self = this;
addRouterToPopup({ featureId, featureTypeSlug, index }) {
const getFeaturePosition = async (searchParams) => {
const response = await axios.get(`${store.state.configuration.VUE_APP_DJANGO_API_BASE}projects/${router.history.current.params.slug}/feature/${featureId}/position-in-list/?${searchParams.toString()}`);
return response.data;
};
const goToBrowseFeatureDetail = async () => {
const currentQuery = { ...this.queryParams };
if (this.queryParams && this.queryParams.filter === 'feature_type_slug') { // when feature_type is the default filter of the project,
currentQuery['feature_type_slug'] = featureTypeSlug; // get its slug for the current feature
}
const searchParams = new URLSearchParams(currentQuery); // urlSearchParams allow to get rid of undefined values
if (!index >= 0) { // with mvt feature, there can't be an index
index = await getFeaturePosition(searchParams);
}
router.push({
name: 'details-signalement-filtre',
query: {
...Object.fromEntries(searchParams.entries()), // transform search params into object and spread it into query
offset: index
}
});
};
function goToFeatureDetail() {
router.push({
name: 'details-signalement',
params: {
slug_type_signal: featureTypeSlug,
slug_signal: featureId,
},
});
}
const goToFeatureTypeDetail = () => {
router.push({
name: 'details-type-signalement',
params: {
feature_type_slug: featureTypeSlug,
},
});
};
const isFeatureBrowsing = (router.history.current.name === 'project_detail' || router.history.current.name === 'liste-signalements');
const featureEl = document.getElementById('goToFeatureDetail');
if (featureEl) featureEl.onclick = isFeatureBrowsing ? goToBrowseFeatureDetail : goToFeatureDetail;
const featureTypeEl = document.getElementById('goToFeatureTypeDetail');
if (featureTypeEl) featureTypeEl.onclick = goToFeatureTypeDetail;
},
async onMapClick (event) {
//* retrieve features under pointer
const features = this.map.getFeaturesAtPixel(event.pixel, {
layerFilter(l) {
return l === self.mvtLayer;
},
layerFilter: (l) => l === this.mvtLayer || this.olLayer
});
if (features && features.length > 0) {
const popupContent = this._createContentPopup(features[0],
this.mvtLayer.featureTypes, this.mvtLayer.project_slug);
this.content.innerHTML = popupContent;
this.overlay.setPosition(event.coordinate);
}
//const queryableLayerSelected = document.getElementById(`queryable-layers-selector-${this.wmsParams.basemapId}`).getElementsByClassName('selected')[0].textContent;
if (this.layers) {
let queryLayer = this.layers.find(x => x.query);
// pour compatibilité avec le proxy django
let proxyparams = [
'request',
'service',
'srs',
'version',
'bbox',
'height',
'width',
'layers',
'query_layers',
'info_format', 'x', 'y', 'i', 'j',
];
//* prepare popup content
if (features && features.length > 0 && this.content) {
const featureId = features[0].properties_ ? features[0].properties_.feature_id : features[0].id_;
const isEdited = router.history.current.name === 'editer-signalement' &&
router.history.current.params.slug_signal === featureId; //* avoid opening popup on feature currently edited
if (featureId && !isEdited) {
const popupContent = await this._createContentPopup(features[0]);
this.content.innerHTML = popupContent.html;
this.overlay.setPosition(event.coordinate);
this.addRouterToPopup({
featureId,
featureTypeSlug: popupContent.feature_type ? popupContent.feature_type.slug : '',
index: popupContent.index,
});
}
} else if (this.layers) { // If no feature under the mouse pointer, attempt to find a query layer
const queryLayer = this.layers.find(x => x.query);
if (queryLayer) {
let url = this.getFeatureInfoUrl(event, queryLayer);
let urlInfos = url.split('?');
// pour compatibilité avec le proxy django
const proxyparams = [
'request',
'service',
'srs',
'version',
'bbox',
'height',
'width',
'layers',
'query_layers',
'info_format', 'x', 'y', 'i', 'j',
];
const url = this.getFeatureInfoUrl(event, queryLayer);
const urlInfos = url ? url.split('?') : [];
const urlParams = new URLSearchParams(urlInfos[1]);
let params = {};
const params = {};
Array.from(urlParams.keys()).forEach(param => {
if (proxyparams.indexOf(param.toLowerCase()) >= 0)
if (proxyparams.indexOf(param.toLowerCase()) >= 0) {
params[param.toLowerCase()] = urlParams.get(param);
}
});
params.url = urlInfos[0];
let self = this;
axios.get(
window.proxy_url,
{
params: params,
}
{ params }
).then(response => {
let data = response.data;
var err = typeof data === 'object' ? null : data;
if (data.features || err) {
self.showGetFeatureInfo(err, event, data, queryLayer);
}
})
.catch(error => {
throw (error);
}
);
const data = response.data;
const err = typeof data === 'object' ? null : data;
if (data.features || err) this.showGetFeatureInfo(err, event, data, queryLayer);
}).catch(error => {
throw error;
});
}
}
},
showGetFeatureInfo: function (err, event, data, layer) {
showGetFeatureInfo: function (err, event, data, layer) {
let content;
if (err) {
content = `
<h4>${layer.options.title}</h4>
<p>Données de la couche inaccessibles</p>
`;
this.content.innerHTML = content;
this.overlay.setPosition(event.coordinate);
} else {
// Otherwise show the content in a popup
let contentLines = [];
} else { // Otherwise show the content in a popup
const contentLines = [];
let contentTitle;
if (data.features.length > 0) {
Object.entries(data.features[0].properties).forEach(entry => {
......@@ -206,80 +299,179 @@ const mapService = {
this.content.innerHTML = content;
this.overlay.setPosition(event.coordinate);
}
}
},
getFeatureInfoUrl(event, layer) {
let olLayer = dictLayersToLeaflet[layer.id];
const olLayer = dictLayersToMap[layer.id];
const source = olLayer.getSource();
const viewResolution = this.map.getView().getResolution();
let url;
let wmsOptions = { info_format: 'application/json', query_layers: layer.options.layers };
const wmsOptions = { info_format: 'application/json', query_layers: layer.options.layers };
if (source && source.getFeatureInfoUrl) {
url = source.getFeatureInfoUrl(event.coordinate, viewResolution, 'EPSG:3857', wmsOptions);
}
return url;
},
fitBounds(bounds) {
let ext = boundingExtent([[bounds[0][1], bounds[0][0]], [bounds[1][1], bounds[1][0]]]);
ext = transformExtent(ext, 'EPSG:4326', 'EPSG:3857');
this.map.getView().fit(ext, { padding: [25, 25, 25, 25] });
this.map.getView().fit(ext, { padding: [25, 25, 25, 25], maxZoom: 16 });
},
fitExtent(ext) {
//ext = transformExtent(ext, 'EPSG:4326', 'EPSG:3857');
this.map.getView().fit(ext, { padding: [25, 25, 25, 25] });
},
/**
* Add multiple layers to the map. If custom layers are defined, they will be added using `addConfigLayer`.
* If no custom layers are defined, a default basemap will be added based on the schema type (WMS, WMTS, or XYZ).
*
* @param {Array} layers - Array of layer configurations to be added.
* @param {string} serviceMap - URL or service for the map base layer.
* @param {Object} optionsMap - Options for the base layer (e.g., attribution, noWrap).
* @param {string} schemaType - Type of the base layer (either 'wms', 'wmts', or fallback to XYZ).
*
* @returns {void}
*/
addLayers: function (layers, serviceMap, optionsMap, schemaType) {
// Set the current layers to the provided layers array
this.layers = layers;
if (layers) { //* if admin has defined basemaps for this project
// Check if custom layers are defined (admin-defined basemaps)
if (layers) {
// Reset the layer count for managing Z-index
layersCount = 0;
// Loop through each layer and add it using the addConfigLayer method
layers.forEach((layer) => {
if (layer) {
let options = layer.options;
if (options) {
options.noWrap = true;
options.opacity = layer.opacity;
if (layer.schema_type === 'wms') {
if (layer.queryable) {
options.title = layer.title;
dictLayersToLeaflet[layer.id] = this.addWMSLayer(layer.service, options);
} else {
dictLayersToLeaflet[layer.id] = this.addWMSLayer(layer.service, options);
}
} else if (layer.schema_type === 'tms') {
const layerTms = new TileLayer({
source: new XYZ({
attributions: options.attribution,
url: layer.service.replace('{s}', '{a-c}')
})
});
this.map.addLayer(layerTms);
dictLayersToLeaflet[layer.id] = layerTms;
}
}
if (!layer) {
console.error('Layer is missing in the provided layers array.');
} else {
this.addConfigLayer(layer);
}
});
} else { //* else when no basemaps defined
}
// If no custom layers are defined, fall back to the base map
else {
// Ensure that options for the base map are provided
if (!optionsMap) {
console.error('Options for the base map are missing.');
return;
}
// Set noWrap to true to prevent map wrapping around the globe
optionsMap.noWrap = true;
// Handle the base map based on the schema type (WMS, WMTS, or fallback)
if (schemaType === 'wms') {
this.addWMSLayer(serviceMap, optionsMap);
// Add WMS layer if the schema type is 'wms'
if (!serviceMap) {
console.error('Service URL is missing for WMS base layer.');
} else {
this.addWMSLayer(serviceMap, optionsMap);
}
} else if (schemaType === 'wmts') {
// Add WMTS layer if the schema type is 'wmts'
if (!serviceMap) {
console.error('Service URL is missing for WMTS base layer.');
} else {
this.addWMTSLayerFromCapabilities(serviceMap, optionsMap);
}
} else {
const layer = new TileLayer({
source: new XYZ({
attributions: optionsMap.attribution,
url: serviceMap.replace('{s}', '{a-c}')
})
});
this.map.addLayer(layer);
// Default to XYZ tile layer if the schema type is not WMS or WMTS
if (!serviceMap) {
console.error('Service URL is missing for XYZ base layer.');
} else {
const layer = new TileLayer({
source: new XYZ({
attributions: optionsMap.attribution, // Attribution for the layer
url: serviceMap.replace('{s}', '{a-c}') // Handle subdomains in the URL
})
});
this.map.addLayer(layer); // Add the layer to the map
}
}
}
},
/**
* Add a configuration layer (WMS, WMTS, or TMS) to the map based on the layer's schema type.
* The function handles multiple types of map layers and applies the necessary configurations.
*
* @param {Object} layer - The layer configuration object.
* @param {Object} layer.options - Options for the layer (e.g., opacity, noWrap).
* @param {string} layer.schema_type - Type of the layer ('wms', 'wmts', or 'tms').
* @param {string} layer.service - URL or service for the layer.
* @param {number} layer.opacity - Opacity of the layer.
*
* @returns {void}
*/
addConfigLayer: async function (layer) {
// Check if the layer object is provided
if (!layer) {
console.error('Layer object is missing');
return;
}
// Increment the layers count (to manage Z-index)
layersCount += 1;
// Extract options from the layer
const options = layer.options;
// Check if options are provided for the layer
if (!options) {
console.error(`Options are missing for layer: ${layer.id}`);
return;
}
// Set default layer options (noWrap and opacity)
options.noWrap = true; // Prevent wrapping of the layer around the globe
options['opacity'] = layer.opacity; // Set opacity based on the layer's configuration
// Handle WMS layers
if (layer.schema_type === 'wms') {
// Add title for queryable WMS layers
if (layer.queryable) options['title'] = layer.title;
dictLayersToMap[layer.id] = this.addWMSLayer(layer.service, options); // Add WMS layer
}
// Handle WMTS layers
else if (layer.schema_type === 'wmts') {
try {
const newLayer = await this.addWMTSLayerFromCapabilities(layer.service, options); // Add WMTS layer asynchronously
dictLayersToMap[layer.id] = newLayer;
} catch (error) {
console.error(`Error adding WMTS layer: ${layer.id}`, error);
}
}
// Handle TMS layers
else if (layer.schema_type === 'tms') {
try {
const newLayer = await this.addTMSLayer(layer.service, options); // Add TMS layer asynchronously
dictLayersToMap[layer.id] = newLayer;
} catch (error) {
console.error(`Error adding TMS layer: ${layer.id}`, error);
}
} else {
console.error(`Unsupported schema type: ${layer.schema_type}`);
}
// Set Z-index for the layer if it was successfully added to the map
if (dictLayersToMap[layer.id]) {
dictLayersToMap[layer.id].setZIndex(layersCount);
} else {
console.error(`Failed to add layer to map: ${layer.id}`);
}
},
addWMSLayer: function (url, options) {
options.VERSION = '1.1.1'; // pour compatibilité avec le proxy django
options.VERSION = options.version || '1.3.0'; // pour compatibilité avec le proxy django
const source = new TileWMS({
attributions: options.attribution,
url: url,
......@@ -288,25 +480,183 @@ const mapService = {
});
const layer = new TileLayer({
source: source
source: source,
opacity: parseFloat(options.opacity),
});
this.map.addLayer(layer);
return layer;
},
getWMTSLayerCapabilities: async function (url) {
// adapted from : https://openlayers.org/en/latest/examples/wmts-layer-from-capabilities.html
// get capabilities with request to the service
try {
const response = await fetch(url);
const text = await response.text();
const capabilities = parser.read(text);
return capabilities;
} catch (error) {
console.error(error);
}
},
addWMTSLayerFromCapabilities: async function (url, options) {
// adapted from : https://git.neogeo.fr/onegeo-suite/sites/onegeo-suite-site-maps-vuejs/-/blob/draft/src/services/MapService.ts
const wmtsCapabilities = await this.getWMTSLayerCapabilities(url);
const { layer, opacity, attributions, format, ignoreUrlInCapabiltiesResponse } = options;
let sourceOptions;
try {
if (format) {
sourceOptions = optionsFromCapabilities(wmtsCapabilities, { layer, format });
} else {
sourceOptions = optionsFromCapabilities(wmtsCapabilities, { layer });
}
}
catch (e) {
console.error(e);
if (e.message == 'projection is null') {
return 'Projection non reconnue';
}
else {
return 'Problème d\'analyse du getCapabilities';
}
}
if (ignoreUrlInCapabiltiesResponse) {
var searchMask = 'request(=|%3D)getCapabilities';
var regEx = new RegExp(searchMask, 'ig');
var replaceMask = '';
sourceOptions.urls[0] = url.replace(regEx, replaceMask);
}
sourceOptions.attributions = attributions;
sourceOptions.crossOrigin= 'anonymous';
if (layer === 'ORTHOIMAGERY.ORTHOPHOTOS') {
// un peu bourrin mais il semble y avoir qq chose de spécifique avec cette couche ORTHO
// https://geoservices.ign.fr/documentation/services/utilisation-web/affichage-wmts/openlayers-et-wmts
sourceOptions.tileGrid = new WMTSTileGrid({
origin: [-20037508,20037508],
resolutions: [
156543.03392804103,
78271.5169640205,
39135.75848201024,
19567.879241005125,
9783.939620502562,
4891.969810251281,
2445.9849051256406,
1222.9924525628203,
611.4962262814101,
305.74811314070485,
152.87405657035254,
76.43702828517625,
38.218514142588134,
19.109257071294063,
9.554628535647034,
4.777314267823517,
2.3886571339117584,
1.1943285669558792,
0.5971642834779396,
0.29858214173896974,
0.14929107086948493,
0.07464553543474241
],
matrixIds: ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19'],
});
}
const newLayer = new TileLayer({
opacity: parseFloat(opacity) || 1,
source: new WMTS(sourceOptions),
});
this.map.addLayer(newLayer);
return newLayer;
},
/**
* Add a TMS (Tile Map Service) layer to the map.
* If the URL includes `.pbf` (vector tiles), it will apply a style from the provided options.
* The layer will be added to the map, and the style will be applied asynchronously if needed.
*
* @param {string} url - The URL of the TMS layer service.
* @param {Object} options - Configuration options for the TMS layer, including opacity and style.
* @param {string} options.style - URL to the style JSON (required for vector tiles).
* @param {number} options.opacity - Opacity of the layer (optional).
*
* @returns {VectorTileLayer} - The TMS layer added to the map.
*/
async addTMSLayer(url, options) {
// Check if the URL is missing
if (!url) {
console.error('TMS layer service URL is missing');
// Check if the options object is missing
} else if (!options) {
console.error('TMS layer options object is missing');
} else {
let layerTms;
// Check if the URL refers to PBF (vector tiles)
if (url.includes('pbf')) {
// Ensure that a style is provided for vector tiles
if (!options.style) {
console.error('TMS layer from PBF requires a style in the options');
} else {
// Handle PBF vector tiles
layerTms = new VectorTileLayer({
source: new VectorTileSource({
format: new MVT(), // Format for vector tiles (Mapbox Vector Tiles)
url: url.replace('{s}', '{a-c}'), // Handle subdomain pattern in the URL if present
attributions: options.attribution,
})
});
try {
// Fetch the style JSON from the provided URL
const response = await fetch(options.style);
const json = await response.json();
// Apply the fetched style to the layer (asynchronous)
await applyStyle(layerTms, json);
} catch (error) {
// Handle any errors during the fetch process
console.error('Error loading the style JSON:', error);
}
}
} else {
// Handle PNG raster tiles
layerTms = new TileLayer({
source: new XYZ({
url: url.replace('{s}', '{a-c}'), // Use the PNG TMS URL pattern
attributions: options.attribution,
})
});
}
// Set the opacity for the layer (default to 1.0 if not specified)
layerTms.setOpacity(parseFloat(options.opacity || 1.0));
// Add the TMS layer to the map
this.map.addLayer(layerTms);
// Return the TMS layer for further manipulation if needed
return layerTms;
}
},
// Remove the base layers (not the features)
removeLayers: function () {
Object.values(dictLayersToLeaflet).forEach(element => {
Object.values(dictLayersToMap).forEach(element => {
this.map.removeLayer(element);
});
dictLayersToLeaflet = {};
dictLayersToMap = {};
},
updateOpacity(layerId, opacity) {
const layer = dictLayersToLeaflet[layerId];
layer.setOpacity(parseFloat(opacity));
const layer = dictLayersToMap[layerId];
if (layer) {
layer.setOpacity(parseFloat(opacity));
} else {
console.error(`Layer with id: ${layerId} couldn't be found for opacity update`);
}
},
updateOrder(layers) {
......@@ -319,234 +669,348 @@ const mapService = {
this.addLayers(layers);
},
retrieveFeatureColor: function (featureType, properties) {
const colorsStyle = featureType.colors_style;
if (featureType && colorsStyle && colorsStyle.custom_field_name) {
const currentValue = properties[colorsStyle.custom_field_name];
const colorStyle = colorsStyle.colors[currentValue];
return colorStyle ? colorStyle : featureType.color;
} else {
return featureType.color;
retrieveFeatureStyle: function (featureType, properties) {
const { colors_style, customfield_set } = featureType;
let { color, opacity } = featureType;
if (colors_style && colors_style.custom_field_name && customfield_set) {
const customField = customfield_set.find((el) => el.name === colors_style.custom_field_name);
if (customField) {
const fieldType = customField.field_type;
let currentValue = properties[colors_style.custom_field_name];
if (currentValue && typeof currentValue === 'string') currentValue = currentValue.trim(); // remove leading and trailing whitespaces
switch (fieldType) {
case 'list':
if (currentValue) {
color = colors_style.colors && colors_style.colors[currentValue];
opacity = colors_style.opacities && colors_style.opacities[currentValue];
}
break;
case 'char': //* if the custom field is supposed to be a string
//* check if its current value is empty or not, to select a color | https://redmine.neogeo.fr/issues/14048
color = colors_style.value.colors && colors_style.value.colors[currentValue ? 'Non vide' : 'Vide'];
opacity = colors_style.value.opacities && colors_style.value.opacities[currentValue ? 'Non vide' : 'Vide'];
break;
case 'boolean':
color = colors_style.value.colors && colors_style.value.colors[currentValue ? 'Coché' : 'Décoché'];
opacity = colors_style.value.opacities && colors_style.value.opacities[currentValue ? 'Coché' : 'Décoché'];
break;
}
}
}
return { color, opacity };
},
addVectorTileLayer: function (url, project_id, project_slug, featureTypes, form_filters) {
let format_cfg = {/*featureClass: Feature*/ };
addVectorTileLayer: function ({ url, project_slug, featureTypes, formFilters = {}, queryParams = {} }) {
const projectId = project_slug.split('-')[0];
const format_cfg = {/*featureClass: Feature*/ };
const mvt = new MVT(format_cfg);
function customLoader(tile, src) {
tile.setLoader(function(extent, resolution, projection) {
const token = () => {
const re = new RegExp('csrftoken=([^;]+)');
const value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
};
fetch(src, {
credentials: 'include',
headers: {
'X-CSRFToken': token()
},
}).then(function(response) {
response.arrayBuffer().then(function(data) {
const format = tile.getFormat(); // ol/format/MVT configured as source format
const features = format.readFeatures(data, {
extent: extent,
featureProjection: projection
});
tile.setFeatures(features);
});
});
});
}
let mvt = new MVT(format_cfg);
let options = {
const options = {
urls: [],
matrixSet: 'EPSG:3857'
matrixSet: 'EPSG:3857',
tileLoadFunction: customLoader,
};
options.format = mvt;
let layerSource = new VectorTileSource(options);
const layerSource = new VectorTileSource(options);
layerSource.setTileUrlFunction((p0) => {
return url+'/?tile=' + p0[0] + '/' + p0[1] + '/' + p0[2] + '&project_id=' + project_id;
return `${url}/?tile=${p0[0]}/${p0[1]}/${p0[2]}&project_id=${projectId}`;
});
const styleFunction = (feature) => this.getStyle(feature, featureTypes, form_filters);
const styleFunction = (feature) => this.getStyle(feature, featureTypes, formFilters);
this.mvtLayer = new VectorTileLayer({
style: styleFunction,
source: layerSource
});
this.mvtLayer.featureTypes = featureTypes;
this.mvtLayer.project_slug = project_slug;
this.featureTypes = featureTypes; // store featureTypes for popups
this.projectSlug = project_slug; // store projectSlug for popups
this.queryParams = queryParams; // store queryParams for popups
this.mvtLayer.setZIndex(30);
this.map.addLayer(this.mvtLayer);
window.layerMVT = this.mvtLayer;
},
getStyle: function (feature, featureTypes, form_filters) {
let properties = feature.getProperties();
/**
* Determines the style for a given feature based on its type and applicable filters.
*
* @param {Object} feature - The feature to style.
* @param {Array} featureTypes - An array of available feature types.
* @param {Object} formFilters - Filters applied through the form.
* @returns {ol.style.Style} - The OpenLayers style for the feature.
*/
getStyle: function (feature, featureTypes, formFilters) {
const properties = feature.getProperties();
let featureType;
// GeoJSON
if(properties.feature_type){
// Determine the feature type. Differentiate between GeoJSON and MVT sources.
if (properties && properties.feature_type) {
// Handle GeoJSON feature type
featureType = featureTypes
.find((ft) => ft.slug === (properties.feature_type.slug || properties.feature_type));
} else { //MVT
} else {
// Handle MVT feature type
featureType = featureTypes.find((x) => x.slug.split('-')[0] === '' + properties.feature_type_id);
}
const color = this.retrieveFeatureColor(featureType, properties);
const colorValue =
color.value && color.value.length ?
color.value : typeof color === 'string' && color.length ?
color : '#000000';
let rgbaColor = asArray(colorValue);
rgbaColor[3] = 0.5;//opacity
const hiddenStyle = new Style();
const defaultStyle = new Style(
{
if (featureType) {
// Retrieve the style (color, opacity) for the feature.
const { color, opacity } = this.retrieveFeatureStyle(featureType, properties);
let colorValue = '#000000'; // Default color
// Determine the color value based on the feature type.
if (color && color.value && color.value.length) {
colorValue = color.value;
} else if (typeof color === 'string' && color.length) {
colorValue = color;
}
// Convert the color value to RGBA and apply the opacity.
const rgbaColor = asArray(colorValue);
rgbaColor[3] = opacity || 0.5; // Default opacity
// Define the default style for the feature.
const defaultStyle = new Style({
image: new Circle({
fill: new Fill(
{
color: rgbaColor,
},
),
stroke: new Stroke(
{
color: colorValue,
width: 2,
},
),
fill: new Fill({ color: rgbaColor }),
stroke: new Stroke({ color: colorValue, width: 2 }),
radius: 5,
}),
stroke: new Stroke(
{
color: colorValue,
width: 2,
},
),
fill: new Fill(
{
color: rgbaColor,
},
),
},
);
stroke: new Stroke({ color: colorValue, width: 2 }),
fill: new Fill({ color: rgbaColor }),
});
// Filtre sur le feature type
if(form_filters){
if (form_filters.type && form_filters.type.selected) {
if (featureType.title !== form_filters.type.selected) {
// Define a hidden style to apply when filters are active.
const hiddenStyle = new Style();
// Apply filters based on feature type, status, and title.
if (formFilters) {
if (formFilters.type && formFilters.type.length > 0 && !formFilters.type.includes(featureType.slug)) {
return hiddenStyle;
}
}
// Filtre sur le statut
if (form_filters.status && form_filters.status.selected.value) {
if (properties.status !== form_filters.status.selected.value) {
if (formFilters.status && formFilters.status.length > 0 && !formFilters.status.includes(properties.status)) {
return hiddenStyle;
}
}
// Filtre sur le titre
if (form_filters.title) {
if (!properties.title.toLowerCase().includes(form_filters.title.toLowerCase())) {
if (formFilters.title && !properties.title.toLowerCase().includes(formFilters.title.toLowerCase())) {
return hiddenStyle;
}
}
// Return the default style if no filters are applied or if the feature passes the filters.
return defaultStyle;
} else {
console.error('No corresponding featureType found.');
return new Style();
}
return defaultStyle;
},
addFeatures: function (features, filter, addToMap = true, featureTypes) {
console.log(addToMap);
let drawSource = new VectorSource();
addFeatures: function ({ features, filter = {}, featureTypes, addToMap = true, project_slug, queryParams = {} }) {
console.log('addToMap', addToMap);
const drawSource = new VectorSource();
let retour;
// TODO verifier utilité de cette boucle et remplacer par readFeatures plutot
let index = 0;
features.forEach((feature) => {
retour = new GeoJSON().readFeature(feature, { dataProjection: 'EPSG:4326', featureProjection: 'EPSG:3857' });
drawSource.addFeature(retour);
const featureProperties = feature.properties ? feature.properties : feature;
const featureType = featureTypes
.find((ft) => ft.slug === (featureProperties.feature_type.slug || featureProperties.feature_type));
let filters = [];
if (filter) {
const typeCheck = filter.featureType && featureProperties.feature_type.slug === filter.featureType;
const statusCheck = filter.featureStatus && featureProperties.status.value === filter.featureStatus;
const titleCheck = filter.featureTitle && featureProperties.title.includes(filter.featureTitle);
filters = [typeCheck, statusCheck, titleCheck];
try {
if (feature.properties) {
feature.properties['index'] = index;
index += 1;
}
retour = new GeoJSON().readFeature(feature, { dataProjection: 'EPSG:4326', featureProjection: 'EPSG:3857' }, featureTypes);
drawSource.addFeature(retour);
} catch (err) {
console.error(err);
}
console.log(featureType, filters);
});
const styleFunction = (feature) => this.getStyle(feature, featureTypes, filter);
const olLayer = new VectorLayer({
source: drawSource,
style: styleFunction,
});
olLayer.setZIndex(29);
this.map.addLayer(olLayer);
this.olLayer = olLayer;
this.drawSource = drawSource;
this.featureTypes = featureTypes; // store featureTypes for popups
this.projectSlug = project_slug; // store projectSlug for popups
this.queryParams = queryParams; // store queryParams for popup routes
return drawSource;
},
removeFeatures: function () {
this.drawSource.clear();
},
addMapEventListener: function (eventName, callback) {
this.map.on(eventName, callback);
},
_createContentPopup: function (feature, featureTypes, project_slug) {
const formatDate = (current_datetime) => {
let formatted_date = current_datetime.getFullYear() + '-' + ('0' + (current_datetime.getMonth() + 1)).slice(-2) + '-' + ('0' + current_datetime.getDate()).slice(-2) + ' ' +
('0' + current_datetime.getHours()).slice(-2) + ':' + ('0' + current_datetime.getMinutes()).slice(-2);
return formatted_date;
};
let feature_type;
let status;
let date_maj;
let feature_type_url;
let feature_url;
if (feature.getProperties) {
status = feature.getProperties().status;
date_maj = feature.getProperties().updated_on;
feature_type_url = feature.getProperties().feature_type_url;
feature_url = feature.getProperties().feature_url;
} else {
status = feature.status;
date_maj = feature.updated_on;
feature_type_url = feature.feature_type_url;
feature_url = feature.feature_url;
}
if (featureTypes) { // => VectorTile
feature_type = featureTypes.find((x) => x.slug.split('-')[0] === '' + feature.getProperties().feature_type_id);
status = statusList.find((x) => x.value === feature.getProperties().status).name;
date_maj = formatDate(new Date(feature.getProperties().updated_on));
feature_type_url = '/geocontrib/projet/' + project_slug + '/type-signalement/' + feature_type.slug + '/';
feature_url = feature_type_url + 'signalement/' + feature.getProperties().feature_id + '/';
} else {
feature_type = feature.getProperties ? feature.getProperties().feature_type : feature.feature_type;
status = feature.getProperties ? feature.getProperties().status.label : feature.status.label;
createCustomFiedsContent(featureType, feature) {
const { customfield_set } = featureType;
// generate html for each customField configured to be displayed
let rows = '';
for (const { label, name } of customfield_set) {
const value = feature.getProperties()[name];
// check if the value is not null nor undefined (to allow false value if boolean)
if (featureType.displayed_fields.includes(name) && value !== null && value !== undefined) {
rows += `<div class="customField-row">${label} : ${value}</div>`;
}
}
// wrap all rows into customFields container
return rows.length > 0 ?
`<div id="customFields">
<div class="ui divider"></div>
<h5>Champs personnalisés</h5>
${rows}
</div>` : '';
},
//* adapt link url for shared-project restricted navigation
if (window.location.pathname.includes('projet-partage')) {
feature_url = feature_url.replace('projet', 'projet-partage');
feature_type_url = feature_type_url.replace('projet', 'projet-partage');
}
let author = '';
const creator = feature.getProperties ? feature.getProperties().creator : feature.creator;
if (creator) {
author = creator.full_name
? `<div>
Auteur : ${creator.first_name} ${creator.last_name}
</div>`
: creator.username ? `<div>Auteur: ${creator.username}</div>` : '';
}
_createContentPopup: async function (feature) {
const properties = await retrieveFeatureProperties(feature, this.featureTypes, this.projectSlug);
const { feature_type, index, status, updated_on, created_on, creator, display_last_editor } = properties; // index is used to retrieve feature by query when browsing features
const { displayed_fields } = feature_type;
// generate html for each native fields
const statusHtml = `<div>Statut : ${status}</div>`;
const featureTypeHtml = `<div>Type de signalement : ${feature_type ? '<a id="goToFeatureTypeDetail" class="pointer">' + feature_type.title + '</a>' : 'Type de signalement inconnu'}</div>`;
const updatedOnHtml = `<div>Dernière mise à jour : ${updated_on}</div>`;
const createdOnHtml = `<div>Date de création : ${created_on}</div>`;
const creatorHtml = creator ? `<div>Auteur : ${creator}</div>` : '';
const lastEditorHtml = display_last_editor ? `<div>Dernier éditeur : ${display_last_editor}</div>` : '';
// wrapping up finale html to fill popup, filtering native fields to display and adding filtered customFields
const html = `<h4>
<a id="goToFeatureDetail" class="pointer">${feature.getProperties ? feature.getProperties().title : feature.title}</a>
</h4>
<div class="fields">
${displayed_fields.includes('status') ? statusHtml : ''}
${displayed_fields.includes('feature_type') ? featureTypeHtml : ''}
${displayed_fields.includes('updated_on') ? updatedOnHtml : ''}
${displayed_fields.includes('created_on') ? createdOnHtml : ''}
${displayed_fields.includes('display_creator') ? creatorHtml : ''}
${displayed_fields.includes('display_last_editor') ? lastEditorHtml : ''}
${this.createCustomFiedsContent(feature_type, feature)}
</div>`;
return { html, feature_type, index };
},
const title = feature.getProperties ? feature.getProperties().title : feature.title;
return `
<h4>
<a href="${feature_url}">${title}</a>
</h4>
<div>
Statut : ${status}
</div>
<div>
Type : <a href="${feature_type_url}"> ${feature_type.title} </a>
</div>
<div>
Dernière mise à jour : ${date_maj}
</div>
${author}
`;
zoom(zoomlevel) {
this.map.getView().setZoom(zoomlevel);
},
zoomTo(location, zoomlevel, lon, lat) {
if (lon && lat) {
location = [+lon, +lat];
}
this.map.getView().setCenter(transform(location, 'EPSG:4326', 'EPSG:3857'));
this.map.getView().setZoom(zoomlevel);
this.zoom(zoomlevel);
},
animateTo(center, zoom) {
this.map.getView().animate({ center, zoom });
},
addOverlay(loc) {
var pos = fromLonLat(loc);
var marker = new Overlay({
position: pos,
positioning: OverlayPositioning.CENTER_CENTER,
addOverlay(loc, zoom) {
const pos = fromLonLat(loc);
const marker = new Overlay({
position: pos,
positioning: 'center',
element: document.getElementById('marker'),
stopEvent: false
stopEvent: false,
});
this.map.addOverlay(marker);
this.animateTo(pos, zoom);
},
initGeolocation() {
this.geolocation = new Geolocation({
// enableHighAccuracy must be set to true to have the heading value.
trackingOptions: {
enableHighAccuracy: true,
},
projection: this.map.getView().getProjection(),
});
// handle this.geolocation error.
this.geolocation.on('error', (error) => {
console.error(error.message);
});
this.positionFeature = new Feature();
this.positionFeature.setStyle( geolocationStyle );
this.geolocation.on('change:position', () => {
const currentPosition = this.geolocation.getPosition();
if (!currentPosition || !isEqual(this.lastPosition, currentPosition)) {
console.log('current position: ', currentPosition); // keeping this console.log for debug purpose in case needed
}
this.lastPosition = currentPosition;
this.changeTrackerPosition();
});
this.geolocationSource = new VectorSource({
features: [this.positionFeature],
});
new VectorLayer({
map: this.map,
source: this.geolocationSource,
});
},
changeTrackerPosition() {
if (this.lastPosition) {
this.positionFeature.setGeometry(new Point(this.lastPosition));
this.animateTo(this.lastPosition, 16);
}
},
displayGeolocationPoint(isVisible) {
let features = this.geolocationSource.getFeatures();
if (!features) return;
const hiddenStyle = new Style(); // hide the feature
for (let i = 0; i < features.length; i++) {
features[i].setStyle(isVisible ? geolocationStyle : hiddenStyle);
}
},
toggleGeolocation(isTracking) {
if (this.geolocation) {
this.geolocation.setTracking(isTracking);
if (this.geolocationSource) {
this.displayGeolocationPoint(isTracking);
if (isTracking) {
this.changeTrackerPosition();
}
}
}
},
getMapCenter() {
const location = this.map.getView().getCenter();
if (location) {
return transform(location, 'EPSG:3857', 'EPSG:4326');
}
return null;
}
};
......
......@@ -4,7 +4,7 @@ const projectAPI = {
async getProject( baseUrl, projectSlug ) {
const response = await axios.get(
`${baseUrl}projects/${projectSlug}/`
`${baseUrl}v2/projects/${projectSlug}/`
);
if (
response.status === 200 &&
......@@ -45,8 +45,8 @@ const projectAPI = {
}
},
async getProjects({ baseUrl, filters, page, projectSlug, myaccount }) {
let url = `${baseUrl}projects/`;
async getProjects({ baseUrl, filters, page, projectSlug, myaccount, text }) {
let url = `${baseUrl}v2/projects/`;
if (projectSlug) {
url += `${projectSlug}/`;
}
......@@ -54,6 +54,10 @@ const projectAPI = {
if (myaccount) {
url += '&myaccount=true';
}
// Append search text if provided.
if (text) {
url += `&search=${encodeURIComponent(text)}`;
}
try {
if (Object.values(filters).some(el => el && el.length > 0)) {
for (const filter in filters) {
......@@ -72,9 +76,9 @@ const projectAPI = {
}
},
async getProjectTypes( baseUrl ) {
async getProjectUsers( baseUrl, projectSlug) {
const response = await axios.get(
`${baseUrl}project-types/`
`${baseUrl}projects/${projectSlug}/utilisateurs/`
);
if (
response.status === 200 &&
......@@ -86,9 +90,23 @@ const projectAPI = {
}
},
async getProjectTypes( baseUrl ) {
const response = await axios.get(
`${baseUrl}v2/projects/?is_project_type=true`
);
if (
response.status === 200 &&
response.data
) {
return response.data.results;
} else {
return null;
}
},
async deleteProject(baseUrl, projectSlug) {
const response = await axios.delete(
`${baseUrl}projects/${projectSlug}/`
`${baseUrl}v2/projects/${projectSlug}/`
);
if ( response.status === 204 ) {
return 'success';
......
import axios from '@/axios-client.js';
import store from '../store';
const baseUrl = store.state.configuration.VUE_APP_DJANGO_API_BASE;
const userAPI = {
async signup(data, url) {
try {
const response = await axios.post(url || `${baseUrl}v2/users/`, data);
return response; // Retourne directement la réponse si succès
} catch (err) {
console.error('Erreur lors de l\'inscription :', err.response || err);
return err.response || { status: 500, data: { detail: 'Erreur inconnue' } }; // 👈 Retourne la réponse d'erreur si disponible
}
},
};
export default userAPI;
......@@ -34,12 +34,16 @@ export default new Vuex.Store({
message: 'En cours de chargement'
},
logged: false,
messageCount: 0,
messages: [],
projectAttributes: [],
reloadIntervalId: null,
staticPages: null,
user: false,
usersGroups: [],
USER_LEVEL_PROJECTS: null,
user_permissions: null,
userToken: null
},
mutations: {
......@@ -52,39 +56,43 @@ export default new Vuex.Store({
SET_CONFIG(state, payload) {
state.configuration = payload;
},
SET_USERS(state, payload) {
state.users = payload;
},
SET_COOKIE(state, cookie) {
state.cookie = cookie;
},
SET_STATIC_PAGES(state, staticPages) {
state.staticPages = staticPages;
},
SET_USERS_GROUPS(state, usersGroups) {
state.usersGroups = usersGroups;
},
SET_USER_LEVEL_PROJECTS(state, USER_LEVEL_PROJECTS) {
state.USER_LEVEL_PROJECTS = USER_LEVEL_PROJECTS;
},
SET_LOGGED(state, value) {
state.logged = value;
},
SET_USER_TOKEN(state, payload) {
state.userToken = payload;
},
SET_USER_PERMISSIONS(state, userPermissions) {
state.user_permissions = userPermissions;
},
SET_LEVELS_PERMISSIONS(state, levelsPermissions) {
state.levelsPermissions = levelsPermissions;
},
SET_PROJECT_ATTRIBUTES(state, userPermissions) {
state.projectAttributes = userPermissions;
},
DISPLAY_MESSAGE(state, message) {
state.messages = [message, ...state.messages];
if (document.getElementById('content')) {
document.getElementById('content').scrollIntoView({ block: 'start', inline: 'nearest' });
message['counter'] = state.messageCount;
state.messageCount += 1;
state.messages = [message, ...state.messages]; // add new message at the beginning of the list
if (document.getElementById('scroll-top-anchor')) {
document.getElementById('scroll-top-anchor').scrollIntoView({ block: 'start', inline: 'nearest' });
}
setTimeout(() => {
state.messages = [];
state.messages = state.messages.slice(0, -1); // remove one message from the end of the list
}, 3000);
},
DISCARD_MESSAGE(state, message) {
state.messages = state.messages.filter((el) => el.comment !== message.comment);
DISCARD_MESSAGE(state, messageCount) {
state.messages = state.messages.filter((mess) => mess.counter !== messageCount);
},
CLEAR_MESSAGES(state) {
state.messages = [];
......@@ -105,6 +113,10 @@ export default new Vuex.Store({
RESET_CANCELLABLE_SEARCH_REQUEST(state) {
state.cancellableSearchRequest = [];
},
REMOVE_LAST_CANCELLABLE_SEARCH_REQUEST(state) {
const updatedCancellableSearchRequest = state.cancellableSearchRequest.slice(0, -1);
state.cancellableSearchRequest = updatedCancellableSearchRequest;
},
SET_RELOAD_INTERVAL_ID(state, payload) {
state.reloadIntervalId = payload;
......@@ -117,8 +129,13 @@ export default new Vuex.Store({
getters: {
permissions: state => state.user_permissions && state.projects.project ?
state.user_permissions[state.projects.project.slug] :
noPermissions
state.user_permissions[state.projects.project.slug] : noPermissions,
usersGroupsOptions: state => state.usersGroups.map((group) => ({
name: group.display_name,
value: group.codename,
isGlobal: group.is_global,
})),
usersGroupsFeatureOptions: (state, getters) => getters.usersGroupsOptions.filter((group) => !group.isGlobal)
},
actions: {
......@@ -165,52 +182,145 @@ export default new Vuex.Store({
const slug = router.history.current.params.slug;
if (slug) {
router.push({ name: 'project_detail', params: { slug } });
router.push({ name: 'project_detail', params: { slug } }).catch(() => { // prevent redundant navigation error
console.error('Not critic: caught error from vue-router -> redundant navigation to same url.');
});
} else { //* not working at page load, routerHistory filled afterwards, could try history.back()
router.push(routerHistory[routerHistory.length - 1] || '/');
router.push(routerHistory[routerHistory.length - 1] || '/').catch(() => { // prevent redundant navigation error
console.error('Not critic: caught error from vue-router -> redundant navigation to same url.');
});
}
},
USER_INFO({ state, commit }) {
if (!state.user) {
axios
.get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}user_info/`)
/**
* Action to retrieve user information.
* - If a token is present in the URL, it indicates a Single Sign-On (SSO) attempt,
* in which case it logs out the user (if logged in) and connects via SSO with the token.
* - Otherwise, it fetches user information from the Django API endpoint:
* - If no user is logged in AND if the login should be done through SSO with a redirect,
* it navigates to the login platform. Afterward, the user will be redirected with the token and the original URL to open in Geocontrib.
* - Else if the response contains a login_url (to connect with OGS), the user is redirected to this url which will redirect the user
* to geocontrib after login, which will check again if the OGS session is activated
* - Otherwise, it displays a message that the user is not logged in but can still access the app as an anonymous user.
* A 'next' parameter is added to transfer to the OGS login page for redirection.
*/
async GET_USER_INFO({ state, commit, dispatch }) {
// Extract token from URL query parameters
const searchParams = new URLSearchParams(window.location.search);
const token = searchParams.get('token');
const url_redirect = searchParams.get('url_redirect');
const currentUrl = window.location.href;
// Check if token exists and SSO login URL is configured
if (token && state.configuration.VUE_APP_LOGIN_URL) {
// If user was previously connected through SSO, ensure they are logged out before reconnecting through SSO, in case user changed
await dispatch('LOGOUT');
dispatch('CONNECT_SSO_WITH_TOKEN', { token, url_redirect });
} else if (!state.user) {
// If user infos are not set, try to fetch them
return axios
.get(`${state.configuration.VUE_APP_DJANGO_API_BASE}user_info/`)
.then((response) => {
// Update the user state with received user data
if (response && response.status === 200) {
const user = response.data.user;
commit('SET_USER', user);
// Fetch user related data
dispatch('GET_USER_LEVEL_PERMISSIONS');
dispatch('GET_USER_LEVEL_PROJECTS');
dispatch('projects/GET_PROJECTS');
return;
}
})
.catch(() => {
//* if an url to redirect to an external authentification system is present, do not redirect to the login page
if (!state.configuration.VUE_APP_LOGIN_URL) {
const url = window.location.href;
if (url.includes('projet-partage')) {
const slug = url.split('projet-partage/')[1];
router.push({ name: 'login', params: { slug } });
} else {
router.push({ name: 'login' });
// If the instance is set to accept login with redirection
if (state.configuration.VUE_APP_SSO_LOGIN_URL_WITH_REDIRECT) {
commit('DISPLAY_MESSAGE', {
comment: 'Vous allez être redirigé vers la plateforme de connexion.'
});
// Call the SSO login plateform with url to redirect after login
window.open(`${state.configuration.VUE_APP_SSO_LOGIN_URL_WITH_REDIRECT}/?url_redirect=${encodeURIComponent(currentUrl)}`, '_self');
}
// If the user is not logged in, display an info message
commit('DISPLAY_MESSAGE', {
comment: `Vous n'êtes pas connecté actuellement.
Vous pouvez accéder à l'application en tant qu'utilisateur anonyme`
});
return;
});
}
},
/**
* Action to connect user through SSO with a token.
* If the app was opened with a token in the url, it attempts a login,
* if the login is succesfull, it set the user in the state
* and retrieve information that would have been retrieved in GET_USER_INFO when logged.
* If the url contained a url to redirect, it calls the router to open this page.
*/
async CONNECT_SSO_WITH_TOKEN({ state, commit, dispatch }, { token, url_redirect }) {
axios
.get(`${state.configuration.VUE_APP_DJANGO_API_BASE}login-token/?token=${token}`)
.then((response) => {
if (response && (response.status === 200 || response.status === 201)) {
const user = response.data;
commit('SET_USER', user);
dispatch('GET_USER_LEVEL_PROJECTS');
dispatch('GET_USER_LEVEL_PERMISSIONS');
commit('DISPLAY_MESSAGE', {
comment: `Vous êtes maintenant connecté ${user.first_name} ${user.last_name}`,
level: 'positive'
});
dispatch('projects/GET_PROJECTS');
if (url_redirect) {
// Prepare the url to redirect with vue-router that prefix the url with DOMAIN+BASE_URL
const substringToRemove = state.configuration.BASE_URL;
// Find the index of the string to remove
const index = url_redirect.indexOf(substringToRemove);
// If found, keep only the remaining part after the substring to remove
if (index !== -1) {
url_redirect = url_redirect.substring(index + substringToRemove.length);
}
// catch error from the router, because of second redirection to feature when call with a feature's id
router.push(url_redirect).catch((e) => e);
}
}
})
.catch((err) => {
console.error(err);
commit('DISPLAY_MESSAGE', {
comment: 'La connexion a échoué.',
level: 'negative'
});
});
},
async GET_USER_TOKEN({ state, commit }) {
const response = await axios.get(`${state.configuration.VUE_APP_DJANGO_API_BASE}get-token`);
if (
response.status === 200 &&
response.data
) {
commit('SET_USER_TOKEN', response.data);
}
},
LOGOUT({ commit, dispatch }) {
axios
.get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}logout/`)
LOGOUT({ state, commit, dispatch }) {
return axios
.get(`${state.configuration.VUE_APP_DJANGO_API_BASE}logout/`)
.then((response) => {
if (response && response.status === 200) {
commit('SET_USER', false);
commit('SET_USER_LEVEL_PROJECTS', null);
dispatch('GET_USER_LEVEL_PERMISSIONS');
if (router.history.current.name !== 'index' && !window.location.pathname.includes('projet-partage')) {
if (router.history.current.name !== 'index' &&
!window.location.pathname.includes('projet-partage') &&
!state.configuration.VUE_APP_LOGIN_URL
) {
router.push('/');
}
}
})
.catch((error) => {
throw error;
console.error(error);
});
},
......@@ -227,6 +337,19 @@ export default new Vuex.Store({
});
},
GET_USERS_GROUPS({ commit }) {
return axios
.get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}users-groups/`)
.then((response) => {
if (response && response.status === 200) {
commit('SET_USERS_GROUPS', response.data);
}
})
.catch((error) => {
throw error;
});
},
GET_USER_LEVEL_PROJECTS({ commit }) {
return axios
.get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}user-level-projects/`)
......@@ -254,7 +377,7 @@ export default new Vuex.Store({
},
GET_LEVELS_PERMISSIONS({ commit }) {
return axios
.get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}levels-permissions/`)
.get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}v2/levels-permissions/`)
.then((response) => {
if (response && response.status === 200) {
commit('SET_LEVELS_PERMISSIONS', response.data);
......@@ -264,6 +387,26 @@ export default new Vuex.Store({
throw error;
});
},
GET_PROJECT_ATTRIBUTES({ commit }) {
return axios
.get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}project-attributes/`)
.then((response) => {
if (response && response.status === 200) {
commit('SET_PROJECT_ATTRIBUTES', response.data);
}
})
.catch((error) => {
throw error;
});
},
CANCEL_CURRENT_SEARCH_REQUEST({ state, commit }) {
if (state.cancellableSearchRequest.length > 0) {
const currentRequestCancelToken =
state.cancellableSearchRequest[state.cancellableSearchRequest.length - 1];
currentRequestCancelToken.cancel('Current search request was canceled');
commit('REMOVE_LAST_CANCELLABLE_SEARCH_REQUEST');
}
},
}
});
import axios from '@/axios-client.js';
import Vue from 'vue';
const getColorsStyles = (customForms) => customForms
.filter(customForm => customForm.options && customForm.options.length)
......@@ -8,14 +9,14 @@ const getColorsStyles = (customForms) => customForms
});
const pending2draftFeatures = (features) => {
const result = [];
for (const el of features) {
if (el.properties.status === 'pending') {
if (el.properties && el.properties.status === 'pending') {
el.properties.status = 'draft';
} else if (el.status === 'pending') {
el.status = 'draft';
}
result.push(el);
}
return result;
return features;
};
const feature_type = {
......@@ -30,6 +31,8 @@ const feature_type = {
feature_types: [],
fileToImport: null,
importFeatureTypeData: [],
preRecordedLists: [],
selectedPrerecordedListValues: {}
},
getters: {
......@@ -83,15 +86,21 @@ const feature_type = {
SET_FILE_TO_IMPORT(state, payload) {
state.fileToImport = payload;
},
SET_PRERECORDED_LISTS(state, payload) {
state.preRecordedLists = payload;
},
SET_SELECTED_PRERECORDED_LIST_VALUES(state, { name, values }) {
Vue.set(state.selectedPrerecordedListValues, name, values.slice(0, 10).map(el => { return { label: el };}));
}
},
actions: {
GET_PROJECT_FEATURE_TYPES({ commit }, project_slug) {
return axios
.get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}projects/${project_slug}/feature-types/`)
.get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}v2/feature-types/?project__slug=${project_slug}`)
.then((response) => {
if (response.status === 200 && response.data) {
commit('SET_FEATURE_TYPES', response.data.feature_types);
commit('SET_FEATURE_TYPES', response.data);
return response;
}
})
......@@ -100,63 +109,75 @@ const feature_type = {
});
},
async GET_PRERECORDED_LISTS({ commit }) {
try {
const response = await axios.get(
`${this.state.configuration.VUE_APP_DJANGO_API_BASE}prerecorded-list-values/`
);
if (response.status === 200) {
commit('SET_PRERECORDED_LISTS', response.data.map(el => el.name));
}
} catch (err) {
console.error(err);
}
},
async GET_SELECTED_PRERECORDED_LIST_VALUES({ commit }, { name, pattern }) {
try {
let url = `${this.state.configuration.VUE_APP_DJANGO_API_BASE}prerecorded-list-values/${name}/`;
if (pattern) {
url += `?pattern=${pattern}`;
}
const response = await axios.get(url);
if (response.status === 200) {
commit('SET_SELECTED_PRERECORDED_LIST_VALUES', {
name,
values: response.data
});
}
} catch (err) {
console.error(err);
}
return;
},
async SEND_FEATURE_TYPE({ state, getters, rootState }, requestType) {
const data = {
title: state.form.title.value,
title_optional: state.form.title_optional.value,
enable_key_doc_notif: state.form.enable_key_doc_notif.value,
disable_notification: state.form.disable_notification.value,
geom_type: state.form.geom_type.value,
color: state.form.color.value,
colors_style: state.form.colors_style.value,
project: rootState.projects.project.slug,
customfield_set: state.customForms.map(el => {
return {
position: el.position,
label: el.label,
name: el.name,
field_type: el.field_type,
options: el.options,
};
}),
//'is_editable': true,
customfield_set: state.customForms
};
if (requestType === 'post') {
return axios
.post(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}feature-types/`, data)
.then((response) => {
if (response) {
const feature_type_slug = response.data.slug;
const status = response.status;
return { feature_type_slug, status };
}
})
.catch((error) => {
throw (error);
});
} else if (requestType === 'put') {
return axios
.put(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}feature-types/${getters.feature_type.slug}/`, data)
.then((response) => {
if (response) {
const feature_type_slug = response.data.slug;
const status = response.status;
return { feature_type_slug, status };
}
})
.catch((error) => {
throw (error);
});
}
let url = `${this.state.configuration.VUE_APP_DJANGO_API_BASE}v2/feature-types/`;
if (requestType === 'put') url += `${getters.feature_type.slug}/`;
return axios({
url,
method: requestType,
data,
}).then((response) => {
if (response) {
const feature_type_slug = response.data.slug;
const status = response.status;
return { feature_type_slug, status };
}
})
.catch((error) => error.response);
},
async SEND_FEATURE_SYMBOLOGY({ getters, rootState }, symbology) {
async SEND_FEATURE_DISPLAY_CONFIG({ getters, rootState }, displayConfig) {
const data = {
title: getters.feature_type.title,
project: rootState.projects.project.slug,
...symbology
...displayConfig
};
return axios
.put(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}feature-types/${getters.feature_type.slug}/`, data)
.put(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}v2/feature-types/${getters.feature_type.slug}/`, data)
.then((response) => {
if (response) {
const feature_type_slug = response.data.slug;
......@@ -180,16 +201,15 @@ const feature_type = {
if (!name && state.fileToImport) {
name = state.fileToImport.name;
}
if (rootState.projects.project.moderation) {
if (state.fileToImport && state.fileToImport.size > 0) { //* if data in a binary file, read it as text
const textFile = await state.fileToImport.text();
geojson = JSON.parse(textFile);
}
const unmoderatedFeatures = pending2draftFeatures(geojson.features);
geojson= {
const unmoderatedFeatures = pending2draftFeatures(geojson.features || geojson);
geojson = geojson.features ? {
type: 'FeatureCollection', features: unmoderatedFeatures
};
} : unmoderatedFeatures;
}
const fileToImport = new File([JSON.stringify(geojson)], name, { type });
......@@ -197,7 +217,7 @@ const feature_type = {
formData.append('feature_type_slug', feature_type_slug);
const url =
this.state.configuration.VUE_APP_DJANGO_API_BASE +
'import-tasks/';
'v2/import-tasks/';
return axios
.post(url, formData, {
headers: {
......@@ -227,7 +247,7 @@ const feature_type = {
formData.append('csv_file', state.fileToImport);
formData.append('feature_type_slug', feature_type_slug);
const url = `${this.state.configuration.VUE_APP_DJANGO_API_BASE}import-tasks/`;
const url = `${this.state.configuration.VUE_APP_DJANGO_API_BASE}v2/import-tasks/`;
return axios
.post(url, formData, {
......@@ -248,8 +268,8 @@ const feature_type = {
});
},
GET_IMPORTS({ commit }, { project_slug, feature_type }) {
let url = `${this.state.configuration.VUE_APP_DJANGO_API_BASE}import-tasks/`;
GET_IMPORTS({ state, commit, dispatch }, { project_slug, feature_type }) {
let url = `${this.state.configuration.VUE_APP_DJANGO_API_BASE}v2/import-tasks/`;
if (project_slug) {
url = url.concat('', `${url.includes('?') ? '&' : '?'}project_slug=${project_slug}`);
}
......@@ -260,6 +280,31 @@ const feature_type = {
.get(url)
.then((response) => {
if (response) {
const diffStatus = [];
if (state.importFeatureTypeData) {
for (const data of response.data) {
const index =
state.importFeatureTypeData
.findIndex(el => el.geojson_file_name === data.geojson_file_name);
if (index !== -1 && state.importFeatureTypeData[index].status !== data.status && data.status === 'finished') {
diffStatus.push(data);
}
}
}
if (diffStatus.length > 0 && project_slug && feature_type) {
try {
dispatch(
'feature/GET_PROJECT_FEATURES',
{
project_slug: project_slug,
feature_type__slug: feature_type,
},
{ root: true }
);
} catch (err) {
console.error(err);
}
}
commit('SET_IMPORT_FEATURE_TYPES_DATA', response.data);
}
return response;
......@@ -271,4 +316,4 @@ const feature_type = {
}
};
export default feature_type;
\ No newline at end of file
export default feature_type;
import axios from '@/axios-client.js';
import router from '../../router';
import { objIsEmpty, findXformValue, activateFieldsNforceValues } from'@/utils';
const feature = {
namespaced: true,
......@@ -8,32 +9,14 @@ const feature = {
attachmentsToDelete: [],
checkedFeatures: [],
clickedFeatures: [],
extra_form: [],
extra_forms: [],
features: [],
features_count: 0,
currentFeature: null,
form: null,
linkedFormset: [], //* used to edit in feature_edit
linked_features: [], //* used to display in feature_detail
massMode: 'modify',
statusChoices: [
{
name: 'Brouillon',
value: 'draft',
},
{
name: 'En attente de publication',
value: 'pending',
},
{
name: 'Publié',
value: 'published',
},
{
name: 'Archivé',
value: 'archived',
},
],
massMode: 'edit-status',
},
mutations: {
SET_FEATURES(state, features) {
......@@ -50,17 +33,30 @@ const feature = {
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;
INIT_FORM(state) {
state.form = {
title: state.currentFeature.properties.title,
description: { value: state.currentFeature.properties.description },
status: { value: state.currentFeature.properties.status },
assigned_member: { value: state.currentFeature.properties.assigned_member },
};
},
UPDATE_FORM_FIELD(state, field) {
if (state.form[field.name].value !== undefined) {
state.form[field.name].value = field.value;
} else {
state.form[field.name] = field.value;
}
},
SET_EXTRA_FORM(state, extra_form) {
state.extra_form = extra_form;
UPDATE_EXTRA_FORM(state, extra_form) {
const updatedExtraForms = state.extra_forms.map((field) => field.name === extra_form.name ? extra_form : field);
state.extra_forms = activateFieldsNforceValues(updatedExtraForms);
},
SET_EXTRA_FORMS(state, extra_forms) {
state.extra_forms = extra_forms;
},
CLEAR_EXTRA_FORM(state) {
state.extra_form = [];
state.extra_forms = [];
},
ADD_ATTACHMENT_FORM(state, attachmentFormset) {
state.attachmentFormset = [...state.attachmentFormset, attachmentFormset];
......@@ -114,29 +110,21 @@ const feature = {
},
},
getters: {
},
actions: {
async GET_PROJECT_FEATURES({ commit, rootState }, {
async GET_PROJECT_FEATURES({ commit, dispatch, rootState }, {
project_slug,
feature_type__slug,
ordering,
search,
limit,
geojson = false
}) {
if (rootState.cancellableSearchRequest.length > 0) {
const currentRequestCancelToken =
rootState.cancellableSearchRequest[rootState.cancellableSearchRequest.length - 1];
currentRequestCancelToken.cancel();
}
geojson = false
}) {
dispatch('CANCEL_CURRENT_SEARCH_REQUEST', null, { root: true });
const cancelToken = axios.CancelToken.source();
commit('SET_CANCELLABLE_SEARCH_REQUEST', cancelToken, { root: true });
commit('SET_FEATURES', []);
commit('SET_FEATURES_COUNT', 0);
let url = `${rootState.configuration.VUE_APP_DJANGO_API_BASE}projects/${project_slug}/feature/`;
let url = `${rootState.configuration.VUE_APP_DJANGO_API_BASE}v2/features/?project__slug=${project_slug}`;
if (feature_type__slug) {
url = url.concat('', `${url.includes('?') ? '&' : '?'}feature_type__slug=${feature_type__slug}`);
}
......@@ -163,89 +151,148 @@ const feature = {
}
return response;
} catch (error) {
console.error(error);
return error;
if (error.message) {
console.error(error);
}
throw error; // 'throw' instead of 'return', in order to pass inside the 'catch' error instead of 'then', to avoid initiating map in another component after navigation
}
},
GET_PROJECT_FEATURE({ commit, rootState }, { project_slug, feature_id }) {
if (rootState.cancellableSearchRequest.length > 0) {
const currentRequestCancelToken =
rootState.cancellableSearchRequest[rootState.cancellableSearchRequest.length - 1];
currentRequestCancelToken.cancel();
}
GET_PROJECT_FEATURE({ commit, dispatch, rootState }, { project_slug, feature_id }) {
dispatch('CANCEL_CURRENT_SEARCH_REQUEST', null, { root: true });
const cancelToken = axios.CancelToken.source();
commit('SET_CANCELLABLE_SEARCH_REQUEST', cancelToken, { root: true });
//commit('SET_CURRENT_FEATURE', null); //? Est-ce que c'est nécessaire ? -> fait sauter l'affichage au clic sur un signalement lié (feature_detail)
const url = `${rootState.configuration.VUE_APP_DJANGO_API_BASE}projects/${project_slug}/feature/?id=${feature_id}`;
const url = `${rootState.configuration.VUE_APP_DJANGO_API_BASE}v2/features/${feature_id}/?project__slug=${project_slug}`;
return axios
.get(url, { cancelToken: cancelToken.token })
.then((response) => {
if (response.status === 200 && response.data.features) {
const feature = response.data.features[0];
commit('SET_CURRENT_FEATURE', feature);
if (response.status === 200 && response.data) {
commit('SET_CURRENT_FEATURE', response.data);
}
return response;
})
.catch((error) => {
console.error('Error while getting feature for id = ', feature_id, error);
throw error;
});
},
SEND_FEATURE({ state, rootState, commit, dispatch }, routeName) {
commit('DISPLAY_LOADER', 'Le signalement est en cours de création', { root: true });
function redirect(featureId) {
dispatch(
'GET_PROJECT_FEATURE',
/**
* Handles the entire lifecycle of a feature submission, from sending data to handling additional forms
* and managing redirections based on the operation performed (create or update).
* @param {Object} context - Vuex action context, including state and dispatch functions.
* @param {Object} payload - Contains parameters like routeName, query, and extraForms for form handling.
*/
SEND_FEATURE({ state, rootState, rootGetters, commit, dispatch }, { routeName, query, extraForms }) {
/**
* Handles redirection after a feature operation, updating URL queries or navigating to new routes.
* @param {string} featureName - The name of the feature being handled.
* @param {Object} response - The server response object.
* @return {Object} - Either the server response or a string to trigger page reload.
*/
function redirect(featureName, response) {
// when modifying more than 2 features, exit this function (to avoid conflict with next feature call to GET_PROJECT_FEATURE)
if (routeName === 'editer-attribut-signalement') return response;
let newQuery = { ...query }; // create a copy of query from the route to avoid redundant navigation error since the router object would be modified
// Display a success message in the UI.
commit(
'DISPLAY_MESSAGE',
{
project_slug: rootState.projects.project.slug,
feature_id: featureId
comment: routeName === 'ajouter-signalement' ?
'Le signalement a été crée' :
`Le signalement ${featureName} a été mis à jour`,
level: 'positive'
},
{ root: true },
);
// Construct the query for navigation based on the current state and feature details.
const slug_type_signal = rootState['feature-type'].current_feature_type_slug;
const project = rootState.projects.project;
if (routeName === 'ajouter-signalement' && !query.ordering) {
newQuery = {
ordering: project.feature_browsing_default_sort,
offset: 0,// if feature was just created, in both ordering it would be the first in project features list
};
if (project.feature_browsing_default_filter === 'feature_type_slug') {
newQuery['feature_type_slug'] = slug_type_signal;
}
)
.then(() => {
commit('DISCARD_LOADER', null, { root: true });
router.push({
name: 'details-signalement',
params: {
slug_type_signal: rootState['feature-type'].current_feature_type_slug,
slug_signal: featureId,
message: routeName === 'editer-signalement' ? 'Le signalement a été mis à jour' : 'Le signalement a été crée'
},
});
dispatch('projects/GET_ALL_PROJECTS', null, { root:true }); //* & refresh project list
}
if (query && query.ordering === '-updated_on') { // if the list is ordered by update time
newQuery.offset = 0;// it would be in first position (else, if ordered by creation, the position won't change anyway)
}
// in fast edition avoid redundant navigation if query didn't change
if (routeName === 'details-signalement-filtre' && parseInt(query.offset) === parseInt(newQuery.offset)) {
return 'reloadPage';
}
// Perform the actual route navigation if needed.
if (!objIsEmpty(newQuery)) {
router.push({
name: 'details-signalement-filtre',
params: { slug_type_signal },
query: newQuery,
});
} else {
router.push({
name: 'details-signalement',
params: { slug_type_signal },
});
}
return response;
}
async function handleOtherForms(featureId) {
/**
* Manages the uploading of attachments and linked features after the main feature submission.
* @param {number} featureId - The ID of the feature to which attachments and linked features relate.
* @param {string} featureName - The name of the feature for messaging purposes.
* @param {Object} response - The server response from the main feature submission.
* @return {Object} - Redirect response or a string to trigger page reload.
*/
async function handleOtherForms(featureId, featureName, response) {
await dispatch('SEND_ATTACHMENTS', featureId);
await dispatch('PUT_LINKED_FEATURES', featureId);
redirect(featureId);
return redirect(featureName, response);
}
/**
* Prepares a GeoJSON object from the current state and extra forms provided in the payload.
* @return {Object} - A GeoJSON object representing the feature with additional properties.
*/
function createGeojson() { //* prepare feature data to send
const extraFormObject = {}; //* prepare an object to be flatten in properties of geojson
for (const field of state.extra_form) {
extraFormObject[field.name] = field.value;
// use extraForms from argument if defined, overiding data from the store, in order to not use mutation (in case of multiple features)
for (const field of extraForms || state.extra_forms) {
// send extra form only if there is a value defined or if no value, if there was a value before, in order to avoid sending empty value when user didn't touch the extraform
if (field.value !== null ||
(state.currentFeature.properties && state.currentFeature.properties[field.name])) {
extraFormObject[field.name] = field.value;
}
}
return {
id: state.form.feature_id,
let geojson = {
id: state.form.feature_id || state.currentFeature.id,
type: 'Feature',
geometry: state.form.geometry,
properties: {
title: state.form.title,
description: state.form.description.value,
status: state.form.status.value,
status: state.form.status.value.value || state.form.status.value,
project: rootState.projects.project.slug,
feature_type: rootState['feature-type'].current_feature_type_slug,
assigned_member: state.form.assigned_member.value,
...extraFormObject
}
};
// if not in the case of a non geographical feature type, add geometry to geojson, else send without geometry
if (rootGetters['feature-type/feature_type'].geom_type !== 'none') {
geojson['geometry'] = state.form.geometry || state.form.geom ||
state.currentFeature.geometry || state.currentFeature.properties.geom;
}
return geojson;
}
const geojson = createGeojson();
let url = `${rootState.configuration.VUE_APP_DJANGO_API_BASE}features/`;
if (routeName === 'editer-signalement') {
url += `${state.form.feature_id}/?
const geojson = createGeojson(); // Construct the GeoJSON from current state.
let url = `${rootState.configuration.VUE_APP_DJANGO_API_BASE}v2/features/`;
if (routeName !== 'ajouter-signalement') {
url += `${geojson.id}/?
feature_type__slug=${rootState['feature-type'].current_feature_type_slug}
&project__slug=${rootState.projects.project.slug}`;
}
......@@ -255,54 +302,61 @@ const feature = {
//* which could create regression
return axios({
url,
method: routeName === 'editer-signalement' ? 'PUT' : 'POST',
method: routeName === 'ajouter-signalement' ? 'POST' : 'PUT',
data: geojson
}).then((response) => {
if ((response.status === 200 || response.status === 201) && response.data) {
const featureId = response.data.id;
const featureName = response.data.properties.title;
// Handle additional forms if needed.
if (state.attachmentFormset.length > 0 ||
state.linkedFormset.length > 0 ||
state.attachmentsToDelete.length > 0) {
handleOtherForms(response.data.id);
state.linkedFormset.length > 0 ||
state.attachmentsToDelete.length > 0) {
return handleOtherForms(featureId, featureName, response);
} else {
redirect(response.data.id);
return redirect(featureName, response);
}
}
})
.catch((error) => {
commit('DISCARD_LOADER', null, { root: true });
if (error.message === 'Network Error' || !rootState.isOnline) {
let arraysOffline = [];
const localStorageArray = localStorage.getItem('geocontrib_offline');
if (localStorageArray) {
arraysOffline = JSON.parse(localStorageArray);
}
const updateMsg = {
project: rootState.projects.project.slug,
type: routeName === 'editer-signalement' ? 'put' : 'post',
featureId: state.form.feature_id,
geojson: geojson
};
arraysOffline.push(updateMsg);
localStorage.setItem('geocontrib_offline', JSON.stringify(arraysOffline));
router.push({
name: 'offline-signalement',
params: {
slug_type_signal: rootState['feature-type'].current_feature_type_slug
},
});
}
else {
console.error(error);
throw error;
}).catch((error) => {
// If offline, store the edited feature in localeStorage to send them when back online
if (error.message === 'Network Error' || !rootState.isOnline) {
let arraysOffline = [];
const localStorageArray = localStorage.getItem('geocontrib_offline');
if (localStorageArray) {
arraysOffline = JSON.parse(localStorageArray);
}
throw error;
});
const updateMsg = {
project: rootState.projects.project.slug,
type: routeName === 'ajouter-signalement' ? 'post' : 'put',
featureId: geojson.id,
geojson: geojson
};
arraysOffline.push(updateMsg);
localStorage.setItem('geocontrib_offline', JSON.stringify(arraysOffline));
router.push({
name: 'offline-signalement',
params: {
slug_type_signal: rootState['feature-type'].current_feature_type_slug
},
});
} else {
console.error('Error while sending feature', error);
throw error; // Re-throw the error for further handling.
}
throw error; // Ensure any error is thrown to be handled by calling code.
});
},
async SEND_ATTACHMENTS({ state, rootState, dispatch }, featureId) {
const DJANGO_API_BASE = rootState.configuration.VUE_APP_DJANGO_API_BASE;
function addFile(attachment, attchmtId) {
/**
* Adds a file to an existing attachment by uploading it to the server.
* @param {Object} attachment - The attachment object containing the file and other details.
* @param {number} attchmtId - The ID of the attachment to which the file is being added.
* @return {Promise<Object>} - The server's response to the file upload.
*/
function addFileToRequest(attachment, attchmtId) {
const formdata = new FormData();
formdata.append('file', attachment.fileToImport, attachment.fileToImport.name);
return axios
......@@ -316,10 +370,16 @@ const feature = {
});
}
/**
* Handles creating or updating an attachment, optionally uploading a file if included.
* @param {Object} attachment - The attachment data, including title, info, and optional file.
* @return {Promise<Object>} - The server response, either from creating/updating the attachment or from file upload.
*/
function putOrPostAttachement(attachment) {
const formdata = new FormData();
formdata.append('title', attachment.title);
formdata.append('info', attachment.info);
formdata.append('is_key_document', attachment.is_key_document);
let url = `${DJANGO_API_BASE}features/${featureId}/attachments/`;
if (attachment.id) {
......@@ -332,16 +392,21 @@ const feature = {
data: formdata
}).then((response) => {
if (response && (response.status === 200 || response.status === 201) && attachment.fileToImport) {
return addFile(attachment, response.data.id);
return addFileToRequest(attachment, response.data.id);
}
return response;
})
.catch((error) => {
console.error(error);
return error;
});
}).catch((error) => {
console.error(error);
return error;
});
}
/**
* Deletes attachments by dispatching a Vuex action.
* @param {number[]} attachmentsId - The IDs of the attachments to be deleted.
* @param {number} featureId - The ID of the feature related to the attachments.
* @return {Promise<Object>} - The server response to the deletion request.
*/
function deleteAttachement(attachmentsId, featureId) {
const payload = {
attachmentsId: attachmentsId,
......@@ -354,13 +419,11 @@ const feature = {
const promisesResult = await Promise.all([
...state.attachmentFormset.map((attachment) => putOrPostAttachement(attachment)),
...state.attachmentsToDelete.map((attachmentsId) => deleteAttachement(attachmentsId, featureId))
]
);
]);
state.attachmentsToDelete = [];
return promisesResult;
},
DELETE_ATTACHMENTS({ commit }, payload) {
const url = `${this.state.configuration.VUE_APP_DJANGO_API_BASE}features/${payload.featureId}/attachments/${payload.attachmentsId}/`;
return axios
......@@ -392,7 +455,7 @@ const feature = {
DELETE_FEATURE({ rootState }, payload) {
const { feature_id, noFeatureType } = payload;
let url = `${rootState.configuration.VUE_APP_DJANGO_API_BASE}features/${feature_id}/?` +
let url = `${rootState.configuration.VUE_APP_DJANGO_API_BASE}v2/features/${feature_id}/?` +
`project__slug=${rootState.projects.project.slug}`;
if (!noFeatureType) {
url +=`&feature_type__slug=${rootState['feature-type'].current_feature_type_slug}`;
......@@ -404,8 +467,36 @@ const feature = {
return false;
});
},
},
/**
* Initializes extra forms based on the current feature type and its custom fields.
* This function retrieves custom fields for the current feature type, assigns values to them based on the current feature's properties,
* and commits them to the store to be displayed in the form.
*
* @param {Object} context - The Vuex action context, including state, rootGetters, and commit function.
*/
INIT_EXTRA_FORMS({ state, rootGetters, commit }) {
const feature = state.currentFeature; // Current feature being edited or viewed.
const featureType = rootGetters['feature-type/feature_type']; // Retrieves the feature type from root getters.
const customFields = featureType.customfield_set; // Custom fields defined for the feature type.
if (customFields) {
commit('SET_EXTRA_FORMS',
activateFieldsNforceValues( // A hypothetical function to activate fields and enforce their values.
customFields.map((field) => {
// Determines the initial value for the field
let value = feature.properties ? feature.properties[field.name] : findXformValue(feature, field);
// If the field is a boolean and the value is null, sets it to false
if (field.field_type === 'boolean' && value === null) {
value = false;
}
// Returns a new object with the updated value and the rest of the field's properties
return { ...field, value };
})
).sort((a, b) => a.position - b.position) // Sorts fields by their user-defined position.
);
}
},
},
};
export default feature;
......@@ -83,7 +83,7 @@ const map = {
actions: {
GET_AVAILABLE_LAYERS({ commit }) {
return axios
.get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}layers/`)
.get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}v2/layers/`)
.then((response) => (commit('SET_LAYERS', response.data)))
.catch((error) => {
throw error;
......@@ -92,7 +92,7 @@ const map = {
GET_BASEMAPS({ commit }, project_slug) {
return axios
.get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}base-maps/?project__slug=${project_slug}`)
.get(`${this.state.configuration.VUE_APP_DJANGO_API_BASE}v2/base-maps/?project__slug=${project_slug}`)
.then((response) => {
if (response.status === 200 && response.data) {
commit('SET_BASEMAPS', response.data);
......@@ -104,41 +104,46 @@ const map = {
});
},
INITIATE_MAP({ commit }, el) { //todo: since this function is not anymore called in different components, it would better to move it in project_details.vue
const mapDefaultViewCenter = [46, 2]; // defaultMapView.center;
const mapDefaultViewZoom = 5; // defaultMapView.zoom;
mapService.createMap(el, {
mapDefaultViewCenter,
mapDefaultViewZoom,
INITIATE_MAP({ commit, rootState }, options) {
var mapDefaultViewCenter =
this.state.configuration.DEFAULT_MAP_VIEW.center;
var mapDefaultViewZoom =
this.state.configuration.DEFAULT_MAP_VIEW.zoom;
mapService.createMap(options.el, {
mapDefaultViewZoom: options.zoom || mapDefaultViewZoom || 5,
mapDefaultViewCenter: options.center || mapDefaultViewCenter || [46.0, 2.0],
maxZoom: options.maxZoom || rootState.projects.project.map_max_zoom_level,
controls: options.controls,
zoomControl: options.zoomControl,
interactions : { doubleClickZoom :false, mouseWheelZoom:true, dragPan:true , ...options.interactions },
geolocationControl: true,
});
commit('SET_MAP', mapService.getMap());
mapService.addLayers(
null,
this.state.configuration.DEFAULT_BASE_MAP_SERVICE,
this.state.configuration.DEFAULT_BASE_MAP_OPTIONS,
this.state.configuration.DEFAULT_BASE_MAP_SCHEMA_TYPE,
);
const map = { ...mapService.getMap() };
commit('SET_MAP', map);
},
async SAVE_BASEMAPS({ state, rootState, dispatch }, newBasemapIds) {
const DJANGO_API_BASE = this.state.configuration.VUE_APP_DJANGO_API_BASE;
function postOrPut(basemap) {
basemap['project'] = rootState.projects.project.slug;
if (newBasemapIds.includes(basemap.id)) {
return axios
.post(`${DJANGO_API_BASE}base-maps/`, basemap)
.then((response) => response)
.catch((error) => {
console.error(error);
return error;
});
} else {
return axios
.put(`${DJANGO_API_BASE}base-maps/${basemap.id}/`, basemap)
.then((response) => response)
//* send new basemaps synchronously to create their ids in the order they were created in the form
let promisesResult = [];
function postOrPut(basemapsToSend) {
if (basemapsToSend.length > 0) { //* execute the function recursively as long as there is still a basemap to send
let basemap = basemapsToSend.shift(); //* remove and return first item in array
basemap['project'] = rootState.projects.project.slug;
let url = `${rootState.configuration.VUE_APP_DJANGO_API_BASE}v2/base-maps/`;
if (!newBasemapIds.includes(basemap.id)) url += `${basemap.id}/`;
axios({
url,
method: newBasemapIds.includes(basemap.id) ? 'POST' : 'PUT',
data: basemap,
})
.then((response) => {
postOrPut(basemapsToSend);
promisesResult.push(response);
})
.catch((error) => {
console.error(error);
return error;
postOrPut(basemapsToSend);
promisesResult.push(error);
});
}
}
......@@ -148,19 +153,17 @@ const map = {
return dispatch('DELETE_BASEMAP', basemapId)
.then((response) => response);
}
const promisesResult = await Promise.all(
[
...state.basemaps.map((basemap) => postOrPut(basemap)),
...state.basemapsToDelete.map((basemapId) => deleteBMap(basemapId))
]
);
//* save new or modifed basemap
postOrPut([...state.basemaps]);
//* delete basemaps
const deletedResult = await Promise.all(state.basemapsToDelete.map((basemapId) => deleteBMap(basemapId)));
state.basemapsToDelete = [];
return promisesResult;
//* return promises results
return [...promisesResult, ...deletedResult];
},
DELETE_BASEMAP({ commit }, basemapId) {
const url = `${this.state.configuration.VUE_APP_DJANGO_API_BASE}base-maps/` + basemapId;
DELETE_BASEMAP({ commit, rootState }, basemapId) {
const url = `${rootState.configuration.VUE_APP_DJANGO_API_BASE}v2/base-maps/${basemapId}/`;
return axios
.delete(url)
.then((response) => {
......@@ -176,4 +179,4 @@ const map = {
}
},
};
export default map;
\ No newline at end of file
export default map;
......@@ -8,7 +8,36 @@ const initialFilters = {
accessible: null
};
const projects = {
/**
* Constructs the URL for the search request, appending search text and any active filters.
*
* @param {Object} rootState - The root state to access global configuration settings.
* @param {Object} filters - The current state of filters applied to the search.
* @param {String} text - The current search text.
* @returns {String} The fully constructed URL for the search request.
*/
function constructSearchUrl({ baseUrl, filters, text, page }) {
let url = `${baseUrl}v2/projects/?`;
// Append page number if provided.
if (page) {
url += `page=${page}`;
}
// Append search text if provided.
if (text) {
url += `&search=${encodeURIComponent(text)}`;
}
// Append each active filter to the URL.
Object.entries(filters).forEach(([key, value]) => {
if (value) {
url += `&${key}=${encodeURIComponent(value)}`;
}
});
return url;
}
const projectsStore = {
namespaced: true,
......@@ -20,7 +49,7 @@ const projects = {
last_comments: [],
projects: [],
project: null,
project_slug: null,
projectUsers: [],
searchProjectsFilter: null,
},
......@@ -47,12 +76,12 @@ const projects = {
state.project = project;
},
SET_PROJECTS_FILTER(state, payload) {
state.filters[payload.filter] = payload.value;
SET_PROJECT_USERS(state, users) {
state.projectUsers = users;
},
RESET_PROJECTS_FILTER(state) {
state.filters = { ...initialFilters };
SET_PROJECTS_FILTER(state, payload) {
state.filters[payload.filter] = payload.value;
},
SET_PROJECTS_SEARCH_STATE(state, payload) {
......@@ -66,19 +95,6 @@ const projects = {
},
actions: {
async GET_ALL_PROJECTS({ rootState, commit }) {
try {
const response = await axios
.get(`${rootState.configuration.VUE_APP_DJANGO_API_BASE}projects/`);
if (response.status === 200 && response.data) {
commit('SET_PROJECTS', response.data);
}
} catch (error) {
console.error(error);
throw error;
}
},
async GET_PROJECTS({ state, rootState, commit }, payload) {
let { page, myaccount, projectSlug } = payload || {};
if (!page) {
......@@ -91,6 +107,7 @@ const projects = {
page,
projectSlug,
myaccount,
text: state.searchProjectsFilter
});
commit('SET_PROJECTS', projects);
return;
......@@ -115,14 +132,19 @@ const projects = {
return project;
},
async GET_PROJECT_INFO({ rootState, dispatch }, slug) {
async GET_PROJECT_USERS({ rootState, commit }, projectSlug) {
const baseUrl = rootState.configuration.VUE_APP_DJANGO_API_BASE;
const users = await projectAPI.getProjectUsers(baseUrl, projectSlug);
commit('SET_PROJECT_USERS', users);
return users;
},
async GET_PROJECT_INFO({ dispatch }, slug) {
const promises = [
dispatch('GET_PROJECT_LAST_MESSAGES', slug).then(response => response),
dispatch('feature-type/GET_PROJECT_FEATURE_TYPES', slug, { root: true }).then(response => response),
dispatch('map/GET_BASEMAPS', slug, { root: true }).then(response => response)
];
if (rootState.user) {
promises.push(dispatch('map/GET_BASEMAPS', slug, { root: true }).then(response => response));
}
const promiseResult = await Promise.all(promises);
return promiseResult;
......@@ -142,47 +164,52 @@ const projects = {
});
},
async HANDLE_PROJECTS_SEARCH_REQUEST({ state, rootState, commit }, text) {
/**
* Asynchronously handles the search request for projects, incorporating search text and applied filters.
* Cancels any ongoing search request to ensure that only the latest request is processed,
* which enhances the responsiveness of search functionality.
*
* @param {Object} context - Destructured to gain access to Vuex state, rootState, and commit function.
* @param {String} text - The search text used for filtering projects.
*/
async HANDLE_PROJECTS_SEARCH_REQUEST({ state, rootState, commit }, { page, text }) {
// Cancel any ongoing search request.
if (rootState.cancellableSearchRequest.length > 0) {
const currentRequestCancelToken =
rootState.cancellableSearchRequest[rootState.cancellableSearchRequest.length - 1];
currentRequestCancelToken.cancel();
}
// Prepare the cancel token for the new request and store it.
const cancelToken = axios.CancelToken.source();
commit('SET_CANCELLABLE_SEARCH_REQUEST', cancelToken, { root: true });
const url = `${rootState.configuration.VUE_APP_DJANGO_API_BASE}projects/?search=${text}`;
let filteredUrl;
if (Object.values(state.filters).some(el => el && el.length > 0)) {
filteredUrl = url;
for (const filter in state.filters) {
if (state.filters[filter]) {
filteredUrl = filteredUrl.concat('', `&${filter}=${state.filters[filter]}`);
}
}
}
const response = await axios.get(
filteredUrl ? filteredUrl : url,
{
cancelToken: cancelToken.token,
}
);
if (response.status === 200) {
const projects = response.data;
if (projects) {
commit('SET_PROJECTS', projects);
// Construct the search URL with any applied filters.
const searchUrl = constructSearchUrl({
baseUrl: rootState.configuration.VUE_APP_DJANGO_API_BASE,
filters: state.filters,
text,
page
});
try {
// Perform the search request.
const response = await axios.get(searchUrl, { cancelToken: cancelToken.token });
// Process successful response.
if (response.status === 200 && response.data) {
commit('SET_PROJECTS', response.data);
commit('SET_PROJECTS_SEARCH_STATE', {
isSearched: true,
text: text
});
}
} catch (error) {
// Handle potential errors, such as request cancellation.
console.error('Search request canceled or failed', error);
}
},
}
}
};
export default projects;
export default projectsStore;
import featureAPI from '@/services/feature-api';
import { isEqual, isNil } from 'lodash';
export function formatStringDate(stringDate) {
const date = new Date(stringDate);
const formatted_date = date.getFullYear() + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + ('0' + date.getDate()).slice(-2) + ' ' +
('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
return formatted_date;
if (date instanceof Date && !isNaN(date.valueOf())) {
const formatted_date = date.getFullYear() + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + ('0' + date.getDate()).slice(-2) + ' ' +
('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
return formatted_date;
}
return stringDate;
}
export function allowedStatus2change(statusChoices, isModerate, userStatus, isOwnFeature, currentRouteName) {
if ( //* si admin, modérateur ou super contributeur, statuts toujours disponibles: Brouillon, Publié, Archivé
userStatus === 'Modérateur' ||
export const statusChoices = [
{
name: 'Brouillon',
value: 'draft',
},
{
name: 'En attente de publication',
value: 'pending',
},
{
name: 'Publié',
value: 'published',
},
{
name: 'Archivé',
value: 'archived',
},
];
export function allowedStatus2change(user, isModerate, userStatus, isOwnFeature, currentRouteName) {
if ( //* si 'super-admin'(superuser) admin, modérateur ou super contributeur, statuts toujours disponibles: Brouillon, Publié, Archivé
user.is_superuser ||
userStatus === 'Modérateur' ||
userStatus === 'Administrateur projet' ||
(userStatus === 'Super Contributeur' && !isModerate)
) {
......@@ -19,6 +45,7 @@ export function allowedStatus2change(statusChoices, isModerate, userStatus, isOw
} else if (userStatus === 'Contributeur') { //* cas particuliers du contributeur
if (currentRouteName === 'ajouter-signalement' || !isOwnFeature) {
//* même cas à l'ajout d'une feature ou si feature n'a pas été créé par le contributeur
//? Incohérence / Inutile ? Un contributeur ne peut pas modifier un signalement d'un autre utilisateur
return isModerate
? statusChoices.filter(
(el) => el.value === 'draft' || el.value === 'pending'
......@@ -38,4 +65,230 @@ export function allowedStatus2change(statusChoices, isModerate, userStatus, isOw
}
}
return [];
}
/**
* Determines the type of a property based on its value.
*
* This function inspects a given property and returns a string indicating its type,
* such as 'boolean', 'integer', 'decimal', 'date', 'text', or 'char'.
* It uses various checks to determine the appropriate type for different value formats.
*
* @param {any} prop - The property value to be evaluated.
* @returns {string} The determined type of the property ('boolean', 'integer', 'decimal', 'date', 'text', or 'char').
*/
export function transformProperties(prop) {
const type = typeof prop;
const regInteger = /^-?\d+$/; // Regular expression to match integer numbers
const regFloat = /^-?\d*\.\d+$/; // Regular expression to match decimal numbers
const regText = /[\r\n]/; // Regular expression to detect multiline text (newlines)
const regDate = /^\d{4}-\d{2}-\d{2}$|^\d{2}\/\d{2}\/\d{4}$/; // Regular expression to match common date formats
// Check if the property is a boolean or a string that represents a boolean
if (type === 'boolean' || (type === 'string' && (prop.toLowerCase() === 'true' || prop.toLowerCase() === 'false'))) {
return 'boolean';
} else if (regInteger.test(prop) || (type === 'number' && Number.isSafeInteger(prop))) {
// Check if the property is an integer or a string that represents an integer
return 'integer';
} else if (type === 'string' && regDate.test(prop.trim())) {
// More specific check for date strings using regular expressions
return 'date';
} else if (regFloat.test(prop) || (type === 'number' && !Number.isSafeInteger(prop))) {
// Check if the property is a decimal number or a string that represents a decimal
return 'decimal';
} else if (regText.test(prop) || (type === 'string' && prop.length > 255)) {
// Check if the property contains newline characters or is a long text
return 'text';
}
// Default case for all other types: assume it is a short text or character field
return 'char';
}
export function objIsEmpty(obj) {
for(const prop in obj) {
if(Object.hasOwn(obj, prop)) {
return false;
}
}
return true;
}
export const reservedKeywords = [
// todo : add keywords for mapstyle (strokewidth...)
'id',
'title',
'description',
'status',
'created_on',
'updated_on',
'archived_on',
'deletion_on',
'feature_type',
'feature_id',
'display_creator',
'display_last_editor',
'project',
'creator',
'lat',
'lon'
];
export const customFieldTypeChoices = [
{ name: 'Booléen', value: 'boolean' },
{ name: 'Chaîne de caractères', value: 'char' },
{ name: 'Date', value: 'date' },
{ name: 'Liste de valeurs', value: 'list' },
{ name: 'Liste de valeurs pré-enregistrées', value: 'pre_recorded_list' },
{ name: 'Liste à choix multiples', value: 'multi_choices_list' },
{ name: 'Nombre entier', value: 'integer' },
{ name: 'Nombre décimal', value: 'decimal' },
{ name: 'Texte multiligne', value: 'text' },
{ name: 'Notification à un groupe', value: 'notif_group' },
];
export const featureNativeFields = [
{ name: 'status', label: 'Statut', field_type: 'Champ GéoContrib' },
{ name: 'feature_type', label: 'Type', field_type: 'Champ GéoContrib' },
{ name: 'updated_on', label: 'Dernière mise à jour', field_type: 'Champ GéoContrib' },
{ name: 'created_on', label: 'Date de création', field_type: 'Champ GéoContrib' },
{ name: 'display_creator', label: 'Auteur', field_type: 'Champ GéoContrib' },
{ name: 'display_last_editor', label: 'Dernier éditeur', field_type: 'Champ GéoContrib' },
];
export const formatDate = (current_datetime) => {
let formatted_date = current_datetime.getFullYear() + '-' + ('0' + (current_datetime.getMonth() + 1)).slice(-2) + '-' + ('0' + current_datetime.getDate()).slice(-2) + '&nbsp;' +
('0' + current_datetime.getHours()).slice(-2) + ':' + ('0' + current_datetime.getMinutes()).slice(-2);
return formatted_date;
};
export const retrieveFeatureProperties = async (feature, featureTypes, projectSlug) => {
const properties = feature.getProperties();
let { feature_type, status, updated_on, created_on, creator, display_last_editor, index } = properties;
if (creator) {
creator = creator.full_name ? `${creator.first_name} ${creator.last_name}` : creator.username;
} else if (properties.feature_id) {
//* if *** MVT *** feature, retrieve display_creator and display_last_editor by fetching the feature details from API
const fetchedFeature = await featureAPI.getProjectFeature(projectSlug, properties.feature_id);
if (fetchedFeature) {
creator = fetchedFeature.properties.display_creator;
display_last_editor = fetchedFeature.properties.display_last_editor;
feature_type = fetchedFeature.properties.feature_type;
}
}
if (featureTypes && feature_type) {
feature_type = featureTypes.find((el) => el.slug === (feature_type.slug || feature_type));
}
if (updated_on && !isNaN(new Date(updated_on))) { //* check if date is already formatted
updated_on = formatDate(new Date(updated_on));
}
if (created_on && !isNaN(new Date(created_on))) { //* check if date is already formatted
created_on = formatDate(new Date(created_on));
}
if (status) {
if (status.label) { //* when the label is already in the feature
status = status.label;
} else if (featureTypes) { //* if not, retrieve the name/label from the list
status = statusChoices.find((el) => el.value === status).name;
}
}
return { feature_type, status, updated_on, created_on, creator, display_last_editor, index };
};
export function findXformValue(feature, customField) {
if (!feature) return null;
if (feature.properties) {
return feature.properties[customField.name] || null;
} else if (feature.feature_data) {
const field = feature.feature_data.find((el) => el.label === customField.label);
return field ? field.value : null;
}
return null;
}
export function isXtraFormActive(extraForms, config) { // return true if no config or if the condition is fullfilled
if (config) { // if conditional field configuration is not null
// get name and value in condition
const { conditionField, conditionValue } = config;
// get the customForm which activates conditional field
const conditioningXForm = extraForms.find((xForm) => xForm.name === conditionField);
// check if the conditioning extraform value match the condition value
if (conditioningXForm) {
// if the values to compare are null or undefined the field can't be activated
if (isNil(conditioningXForm.value) || isNil(conditionValue)) {
return false;
} else if (Array.isArray(conditionValue) && Array.isArray(conditioningXForm.value)) { // case of multiple list or prerecorded values list
return conditioningXForm.value.some((value) => conditionValue.includes(value));
} else if (typeof conditioningXForm.value === 'object' && conditioningXForm.value.label) { // case of simple list
return conditioningXForm.value.label === conditionValue.label;
} else {
return conditioningXForm.value === conditionValue; // more simple case of other fields
}
}
}
return true;
}
export function checkDeactivatedValues(extraForms) {
// if changes occured, update extraForms array with freshly checked active customForms
let newExtraForms = extraForms.map((xForm) => { // we use 'deactivate' instead of 'activate' because at initialization this property cannot be evaluated ...
const isDeactivated = !isXtraFormActive(extraForms, xForm.conditional_field_config); // ... if the component is not created to set this property, thus no extra form would appear at all
// toggle value to null to deactivate other fields conditioned by it
if (isDeactivated) {
xForm['value'] = null;
}
return { ...xForm, ['isDeactivated']: isDeactivated };
});
return newExtraForms;
}
export function checkFieldForcedValue(field, extraForms) {
field['disabled'] = false; //* create a property disabled and (re)set to false by default
if (field.forced_value_config) {
//* loop over each forced value config for this extraForm
for (const config of field.forced_value_config) {
//* find the extraForm field conditioning the forced value
const conditioningField = extraForms.find((xtraForm) => xtraForm.name === config.conditionField);
//* if found check that its value match the condtionValue
if (conditioningField && isEqual(conditioningField.value, config.conditionValue)) {
//* set this value with the forced value and disable the form field
field.value = config.forcedValue;
field.disabled = true;
}
}
}
return field;
}
export function activateFieldsNforceValues(extraForms) {
for (const [index, field] of extraForms.entries()) {
const checkedField = checkFieldForcedValue(field, extraForms);
//* each time a value changes, call this function recursively, until there is no more change
if (checkedField.value !== field.value) {
extraForms[index] = checkedField; //* update the value in extraForms
activateFieldsNforceValues(extraForms); //* call the function with new extraForms
}
}
//* when no more changes detected in the loop, check for deactivated extraForms
extraForms = checkDeactivatedValues(extraForms);
//* return extraForms from the lastly called function
return extraForms;
}
export function formatUserOption(user) {
let name = user.first_name || '';
if (user.last_name) {
name = name + ' ' + user.last_name;
}
return {
name: [name, user.username],
value: user.id,
};
}
\ No newline at end of file
<template>
<div
id="account"
class="page"
>
<div id="account">
<h1>Mon compte</h1>
<div class="ui stackable grid">
......
<template>
<div
v-if="(configuration.VUE_APP_SSO_LOGIN_URL_WITH_REDIRECT && !user) || !currentFeature"
class="no-access"
>
<h3>
🔒&nbsp;Vous n'avez pas accès à ce signalement
<span v-if="!user"> en tant qu'utilisateur anonyme&nbsp;🥸</span>
</h3>
<p v-if="!user">
Veuillez vous connectez afin de pouvoir visualiser le document
</p>
</div>
<div
v-else
:class="['preview', { is_pdf }]"
>
<embed
v-if="is_pdf"
:src="src"
type="application/pdf"
>
<div v-else>
<img
:src="src"
alt="Aperçu de l'image"
>
</div>
</div>
</template>
<script>
import { mapState } from 'vuex';
export default {
name: 'AttachmentPreview',
computed: {
...mapState([
'configuration',
'user'
]),
...mapState('feature', [
'currentFeature'
]),
src() {
return this.$route.query.file;
},
is_pdf() {
return this.src && this.src.includes('pdf');
},
},
watch: {
user() {
/**
* Specific for platform with login by token
* When the user is setted, fetching again the feature with the cookies setted
* since automatic authentification can take time to return the response
* setting the cookies, while the app is loading already
*/
this.getFeature();
}
},
mounted() {
this.getFeature();
},
methods: {
getFeature() {
console.log('getFeature'); // Keeping for debugging after deployment
this.$store.dispatch('feature/GET_PROJECT_FEATURE', {
project_slug: this.$route.params.slug,
feature_id: this.$route.params.slug_signal,
});
}
}
};
</script>
<style scoped lang="less">
.no-access {
> h1 {
margin: 2em 0;
}
height: 60vh;
display: flex;
justify-content: center;
flex-direction: column;
> * {
text-align: center;
}
}
.preview {
width: 100vw;
&.is_pdf {
padding: 0;
@media screen and (min-width: 726px) {
height: calc(100vh - 70px - 1em);
margin: .5em auto;
box-shadow: 1px 2px 10px grey;
}
@media screen and (max-width: 725px) {
height: calc(100vh - 110px);
margin: 0 auto;
}
}
> * {
height: 100%;
width: 100%;
}
> div {
display: flex;
justify-content: center;
img {
max-width: 100%;
}
}
}
</style>
\ No newline at end of file
<template>
<div
id="feature-detail"
class="page"
>
<div id="feature-detail">
<div
v-if="currentFeature"
class="ui grid stackable"
>
<div class="row">
<div class="sixteen wide column">
<FeatureHeader />
<FeatureHeader
v-if="project"
:features-count="featuresCount"
:slug-signal="slugSignal"
:feature-type="feature_type"
:fast-edition-mode="project.fast_edition_mode"
:is-feature-creator="isFeatureCreator"
:can-edit-feature="canEditFeature"
:can-delete-feature="canDeleteFeature"
@fastEditFeature="validateFastEdition"
@setIsDeleting="isDeleting = true"
@tofeature="pushNgo"
/>
</div>
</div>
<div class="row">
<div class="eight wide column">
<FeatureTable
@pushNGo="pushNgo"
v-if="project"
ref="featureTable"
:feature-type="feature_type"
:fast-edition-mode="project.fast_edition_mode"
:can-edit-feature="canEditFeature"
/>
</div>
<div class="eight wide column">
<div
id="map"
ref="map"
/>
<div
id="popup"
class="ol-popup"
>
<a
id="popup-closer"
href="#"
class="ol-popup-closer"
/>
<div
id="popup-content"
/>
<div
v-if="feature_type && feature_type.geom_type !== 'none'"
class="eight wide column"
>
<div class="map-container">
<div
id="map"
ref="map"
>
<SidebarLayers
v-if="basemaps && map"
ref="sidebar"
/>
<Geolocation />
</div>
<div
id="popup"
class="ol-popup"
>
<a
id="popup-closer"
href="#"
class="ol-popup-closer"
/>
<div
id="popup-content"
/>
</div>
</div>
</div>
</div>
......@@ -47,32 +71,38 @@
<div class="eight wide column">
<FeatureComments
:events="events"
:enable-key-doc-notif="feature_type.enable_key_doc_notif"
@fetchEvents="getFeatureEvents"
/>
</div>
</div>
<div
v-if="isCanceling"
class="ui dimmer modals page transition visible active"
style="display: flex !important"
v-if="isDeleting"
class="ui dimmer modals visible active"
>
<div
:class="[
'ui mini modal subscription',
{ 'active visible': isCanceling },
'ui mini modal',
{ 'active visible': isDeleting },
]"
>
<i
class="close icon"
aria-hidden="true"
@click="isCanceling = false"
@click="isDeleting = false"
/>
<div class="ui icon header">
<div
v-if="isDeleting"
class="ui icon header"
>
<i
class="trash alternate icon"
aria-hidden="true"
/>
Supprimer le signalement
</div>
<div class="actions">
<button
type="button"
......@@ -84,7 +114,60 @@
</div>
</div>
</div>
<div
v-if="isLeaving"
class="ui dimmer modals visible active"
>
<div
:class="[
'ui mini modal',
{ 'active visible': isLeaving },
]"
>
<i
class="close icon"
aria-hidden="true"
@click="isLeaving = false"
/>
<div class="ui icon header">
<i
class="sign-out icon"
aria-hidden="true"
/>
Abandonner les modifications
</div>
<div class="content">
Les modifications apportées au signalement ne seront pas sauvegardées, continuer ?
</div>
<div class="actions">
<button
type="button"
class="ui green compact button"
@click="stayOnPage"
>
<i
class="close icon"
aria-hidden="true"
/>
Annuler
</button>
<button
type="button"
class="ui red compact button"
@click="leavePage"
>
Continuer
<i
class="arrow right icon"
aria-hidden="true"
/>
</button>
</div>
</div>
</div>
</div>
<div v-else>
Pas de signalement correspondant trouvé
</div>
......@@ -92,7 +175,8 @@
</template>
<script>
import { mapState, mapActions, mapMutations } from 'vuex';
import { isEqual } from 'lodash';
import { mapState, mapActions, mapMutations, mapGetters } from 'vuex';
import mapService from '@/services/map-service';
import axios from '@/axios-client.js';
......@@ -102,6 +186,9 @@ import FeatureHeader from '@/components/Feature/Detail/FeatureHeader';
import FeatureTable from '@/components/Feature/Detail/FeatureTable';
import FeatureAttachements from '@/components/Feature/Detail/FeatureAttachements';
import FeatureComments from '@/components/Feature/Detail/FeatureComments';
import SidebarLayers from '@/components/Map/SidebarLayers';
import Geolocation from '@/components/Map/Geolocation';
import { buffer } from 'ol/extent';
export default {
......@@ -111,7 +198,25 @@ export default {
FeatureHeader,
FeatureTable,
FeatureAttachements,
FeatureComments
FeatureComments,
SidebarLayers,
Geolocation,
},
beforeRouteUpdate (to, from, next) {
if (this.hasUnsavedChange && !this.isSavingChanges) {
this.confirmLeave(next); // prompt user that there is unsaved changes or that features order might change
} else {
next(); // continue navigation
}
},
beforeRouteLeave (to, from, next) {
if (this.hasUnsavedChange && !this.isSavingChanges) {
this.confirmLeave(next); // prompt user that there is unsaved changes or that features order might change
} else {
next(); // continue navigation
}
},
data() {
......@@ -131,63 +236,130 @@ export default {
},
},
events: [],
isCanceling: false,
projectSlug: this.$route.params.slug,
featuresCount: null,
isDeleting: false,
isLeaving: false,
isSavingChanges: false,
map: null,
slug: this.$route.params.slug,
slugSignal: '',
};
},
computed: {
...mapState([
'USER_LEVEL_PROJECTS',
'user'
]),
...mapState('projects', [
'project'
]),
...mapState('feature-type', [
'feature_types'
'feature_types',
]),
...mapState('feature', [
'currentFeature'
'currentFeature',
'form',
]),
...mapGetters('feature-type', [
'feature_type',
]),
...mapGetters([
'permissions',
]),
...mapState('map', [
'basemaps',
]),
/**
* Checks if there are any unsaved changes in the form compared to the current feature's properties.
* This function is useful for prompting the user before they navigate away from a page with unsaved changes.
*
* @returns {boolean} - Returns true if there are unsaved changes; otherwise, returns false.
*/
hasUnsavedChange() {
// Ensure we are in edition mode and all required objects are present.
if (this.project && this.project.fast_edition_mode &&
this.form && this.currentFeature && this.currentFeature.properties) {
// Check for changes in title, description, and status.
if (this.form.title !== this.currentFeature.properties.title) return true;
if (this.form.description.value !== this.currentFeature.properties.description) return true;
if (this.form.status.value !== this.currentFeature.properties.status) return true;
if (this.form.assigned_member.value !== this.currentFeature.properties.assigned_member) return true;
// Iterate over extra forms to check for any changes.
for (const xForm of this.$store.state.feature.extra_forms) {
const originalValue = this.currentFeature.properties[xForm.name];
// Check if the form value has changed, considering edge cases for undefined, null, or empty values.
if (
!isEqual(xForm.value, originalValue) && // Check if values have changed.
!(!xForm.value && !originalValue) // Ensure both aren't undefined/null/empty, treating null as equivalent to false for unactivated conditionals or unset booleans.
) {
// Log the difference for debugging purposes.
console.log(`In custom form [${xForm.name}], the current form value [${xForm.value}] differs from original value [${originalValue}]`);
return true;
}
}
}
// If none of the above conditions are met, return false indicating no unsaved changes.
return false;
},
isFeatureCreator() {
if (this.currentFeature && this.currentFeature.properties && this.user) {
return this.currentFeature.properties.creator === this.user.id ||
this.currentFeature.properties.creator.username === this.user.username;
}
return false;
},
isModerator() {
return this.USER_LEVEL_PROJECTS && this.USER_LEVEL_PROJECTS[this.slug] === 'Modérateur';
},
isAdministrator() {
return this.USER_LEVEL_PROJECTS && this.USER_LEVEL_PROJECTS[this.slug] === 'Administrateur projet';
},
canEditFeature() {
return (this.permissions && this.permissions.can_update_feature) ||
this.isFeatureCreator ||
this.isModerator ||
this.user.is_superuser;
},
canDeleteFeature() {
return (this.permissions && this.permissions.can_delete_feature && this.isFeatureCreator) ||
this.isFeatureCreator ||
this.isModerator ||
this.isAdministrator ||
this.user.is_superuser;
},
},
watch: {
/**
* To navigate back or forward to the previous or next URL, the query params in url are updated
* since the route doesn't change, mounted is not called, then the page isn't updated
* To reload page infos we need to call initPage() when query changes
*/
'$route.query'(newValue, oldValue) {
if (newValue !== oldValue) {
this.initPage();
}
},
},
created() {
this.SET_CURRENT_FEATURE_TYPE_SLUG(this.$route.params.slug_type_signal);
this.getFeatureEvents();
this.getFeatureAttachments();
this.getLinkedFeatures();
this.$store.dispatch('GET_USERS_GROUPS'); // récupére les groupes d'utilisateurs pour extra_forms
},
mounted() {
this.DISPLAY_LOADER('Recherche du signalement');
if (!this.project) {
// Chargements des features et infos projet en cas d'arrivée directe sur la page ou de refresh
axios.all([
this.GET_PROJECT(this.$route.params.slug),
this.GET_PROJECT_INFO(this.$route.params.slug),
this.GET_PROJECT_FEATURE({
project_slug: this.$route.params.slug,
feature_id: this.$route.params.slug_signal
})])
.then(() => {
this.DISCARD_LOADER();
this.initMap();
});
}
if (!this.currentFeature || this.currentFeature.feature_id !== this.$route.params.slug_signal) {
this.GET_PROJECT_FEATURE({
project_slug: this.$route.params.slug,
feature_id: this.$route.params.slug_signal
})
.then(() => {
this.DISCARD_LOADER();
this.initMap();
});
} else {
this.DISCARD_LOADER();
this.initMap();
}
this.initPage();
},
beforeDestroy() {
this.$store.commit('CLEAR_MESSAGES');
this.$store.dispatch('CANCEL_CURRENT_SEARCH_REQUEST');
},
methods: {
......@@ -195,6 +367,9 @@ export default {
'DISPLAY_LOADER',
'DISCARD_LOADER'
]),
...mapMutations('feature', [
'SET_CURRENT_FEATURE'
]),
...mapMutations('feature-type', [
'SET_CURRENT_FEATURE_TYPE_SLUG'
]),
......@@ -207,154 +382,245 @@ export default {
'GET_PROJECT_FEATURES'
]),
pushNgo(link) {
this.$router.push({
name: 'details-signalement',
params: {
slug_type_signal: link.feature_to.feature_type_slug,
slug_signal: link.feature_to.feature_id,
},
});
this.getFeatureEvents();
this.getFeatureAttachments();
this.getLinkedFeatures();
this.addFeatureToMap();
async initPage() {
await this.getPageInfo();
if(this.feature_type && this.feature_type.geom_type === 'none') {
// setting map to null to ensure map would be created when navigating next to a geographical feature
this.map = null;
} else if (this.currentFeature) {
this.initMap();
}
},
async getPageInfo() {
if (this.$route.params.slug_signal && this.$route.params.slug_type_signal) { // if coming from the route with an id
this.SET_CURRENT_FEATURE_TYPE_SLUG(this.$route.params.slug_type_signal);
this.slugSignal = this.$route.params.slug_signal;
} //* else it would be retrieve after fetchFilteredFeature with offset
this.DISPLAY_LOADER('Recherche du signalement');
let promises = [];
//* Récupération du projet, en cas d'arrivée directe sur la page ou de refresh
if (!this.project) {
promises.push(this.GET_PROJECT(this.slug));
}
//* Récupération des types de signalement, en cas de redirection page détails signalement avec id (projet déjà récupéré) ou cas précédent
if (!this.featureType || !this.basemaps) {
promises.push(
this.GET_PROJECT_INFO(this.slug),
);
}
//* changement de requête selon s'il y a un id ou un offset(dans le cas du parcours des signalements filtrés)
if (this.$route.query.offset >= 0) {
promises.push(this.fetchFilteredFeature());
} else if (!this.currentFeature || this.currentFeature.id !== this.slugSignal) {
promises.push(
this.GET_PROJECT_FEATURE({
project_slug: this.slug,
feature_id: this.slugSignal,
})
);
}
await axios.all(promises);
this.DISCARD_LOADER();
if (this.currentFeature) {
this.getFeatureEvents();
this.getFeatureAttachments();
this.getLinkedFeatures();
if (this.project.fast_edition_mode) {
this.$store.commit('feature/INIT_FORM');
this.$store.dispatch('feature/INIT_EXTRA_FORMS');
}
}
},
confirmLeave(next) {
this.next = next;
this.isLeaving = true;
},
stayOnPage() {
this.isLeaving = false;
},
leavePage() {
this.isLeaving = false;
this.next();
},
pushNgo(newEntry) {
//* update the params or queries in the route/url
this.$router.push(newEntry)
//* catch error if navigation get aborted (in beforeRouteUpdate)
.catch(() => true);
},
goBackToProject(message) {
this.$router.push({
name: 'project_detail',
params: {
slug: this.$route.params.slug,
slug: this.slug,
message,
},
});
},
deleteFeature() {
this.isDeleting = false;
this.DISPLAY_LOADER('Suppression du signalement en cours...');
this.$store
.dispatch('feature/DELETE_FEATURE', { feature_id: this.currentFeature.feature_id })
.then((response) => {
if (response.status === 204) {
this.GET_PROJECT_FEATURES({
project_slug: this.$route.params.slug
});
this.goBackToProject();
.dispatch('feature/DELETE_FEATURE', { feature_id: this.currentFeature.id })
.then(async (response) => {
this.DISCARD_LOADER();
if (response.status === 200) {
this.goBackToProject({ comment: 'Le signalement a bien été supprimé', level: 'positive' });
} else {
this.$store.commit('DISPLAY_MESSAGE', { comment: 'Une erreur est survenue pendant la suppression du signalement', level: 'negative' });
}
});
},
fetchFilteredFeature() { // TODO : if no query for sort, use project default ones
const queryString = new URLSearchParams({ ...this.$route.query });
const url = `${this.$store.state.configuration.VUE_APP_DJANGO_API_BASE}projects/${this.slug}/feature-paginated/?limit=1&${queryString}&output=geojson`;
return featureAPI.getPaginatedFeatures(url)
.then((data) => {
if (data && data.results && data.results.features && data.results.features[0]) {
this.featuresCount = data.count;
this.previous = data.previous;
this.next = data.next;
const currentFeature = data.results.features[0];
this.slugSignal = currentFeature.id;
this.SET_CURRENT_FEATURE(currentFeature);
this.SET_CURRENT_FEATURE_TYPE_SLUG(currentFeature.properties.feature_type.slug);
return { feature_id: currentFeature.id };
}
return;
});
},
initMap() {
var mapDefaultViewCenter =
this.$store.state.configuration.DEFAULT_MAP_VIEW.center;
var mapDefaultViewZoom =
this.$store.state.configuration.DEFAULT_MAP_VIEW.zoom;
this.map = mapService.createMap(this.$refs.map, {
mapDefaultViewCenter,
mapDefaultViewZoom,
interactions : { doubleClickZoom :false,mouseWheelZoom:false,dragPan:false }
});
// Update link to feature list with map zoom and center
mapService.addMapEventListener('moveend', function () {
// update link to feature list with map zoom and center
/*var $featureListLink = $("#feature-list-link")
var baseUrl = $featureListLink.attr("href").split("?")[0]
$featureListLink.attr("href", baseUrl +`?zoom=${this.map.getZoom()}&lat=${this.map.getCenter().lat}&lng=${this.map.getCenter().lng}`)*/
});
// Load the layers.
// - if one basemap exists, we load the layers of the first one
// - if not, load the default map and service options
let layersToLoad = null;
var baseMaps = this.$store.state.map.basemaps;
var layers = this.$store.state.map.availableLayers;
if (baseMaps && baseMaps.length > 0) {
const basemapIndex = 0;
layersToLoad = baseMaps[basemapIndex].layers;
layersToLoad.forEach((layerToLoad) => {
layers.forEach((layer) => {
if (layer.id === layerToLoad.id) {
layerToLoad = Object.assign(layerToLoad, layer);
}
});
if (this.map) {
mapService.removeFeatures();
} else {
this.map = mapService.createMap(this.$refs.map, {
mapDefaultViewCenter,
mapDefaultViewZoom,
maxZoom: this.project.map_max_zoom_level,
interactions : {
doubleClickZoom :false,
mouseWheelZoom: true,
dragPan: true
},
fullScreenControl: true,
geolocationControl: true,
});
layersToLoad.reverse();
}
mapService.addLayers(
layersToLoad,
this.$store.state.configuration.DEFAULT_BASE_MAP_SERVICE,
this.$store.state.configuration.DEFAULT_BASE_MAP_OPTIONS,
this.$store.state.configuration.DEFAULT_BASE_MAP_SCHEMA_TYPE,
);
this.addFeatureToMap();
},
addFeatureToMap() {
const url = `${this.$store.state.configuration.VUE_APP_DJANGO_API_BASE}projects/${this.$route.params.slug}/feature/` +
`?feature_id=${this.$route.params.slug_signal}&output=geojson`;
axios
.get(url)
.then((response) => {
if (response.data.features.length > 0) {
const featureGroup = mapService.addFeatures(
response.data.features,
{},
true,
this.feature_types
);
mapService.fitExtent(buffer(featureGroup.getExtent(),200));
}
})
.catch((error) => {
throw error;
});
const featureGroup = mapService.addFeatures({
project_slug: this.slug,
features: [this.currentFeature],
featureTypes: this.feature_types,
addToMap: true,
});
mapService.fitExtent(buffer(featureGroup.getExtent(),200));
},
getFeatureEvents() {
featureAPI
.getFeatureEvents(this.$route.params.slug_signal)
.getFeatureEvents(this.slugSignal)
.then((data) => (this.events = data));
},
getFeatureAttachments() {
featureAPI
.getFeatureAttachments(this.$route.params.slug_signal)
.getFeatureAttachments(this.slugSignal)
.then((data) => (this.attachments = data));
},
getLinkedFeatures() {
featureAPI
.getFeatureLinks(this.$route.params.slug_signal)
.getFeatureLinks(this.slugSignal)
.then((data) =>
this.$store.commit('feature/SET_LINKED_FEATURES', data)
);
},
checkAddedForm() {
let isValid = true; //* fallback if all customForms returned true
if (this.$refs.featureTable && this.$refs.featureTable.$refs.extraForm) {
for (const extraForm of this.$refs.featureTable.$refs.extraForm) {
if (extraForm.checkForm() === false) {
isValid = false;
}
}
}
return isValid;
},
validateFastEdition() {
let is_valid = true;
is_valid = this.checkAddedForm();
if (is_valid) {
this.isSavingChanges = true; // change the value to avoid confirmation popup after redirection with new query
this.$store.dispatch(
'feature/SEND_FEATURE',
{
routeName: this.$route.name,
query: this.$route.query
}
).then((response) => {
if (response === 'reloadPage') {
// when query doesn't change we need to reload the page infos with initPage(),
// since it would not be called from the watcher'$route.query' when the query does change
this.initPage();
}
});
}
}
},
};
</script>
<style scoped>
.map-container {
height: 100%;
max-height: 70vh;
position: relative;
overflow: hidden;
background-color: #fff;
}
#map {
width: 100%;
height: 100%;
min-height: 250px;
max-height: 70vh;
}
#feed-event .event {
margin-bottom: 1em;
}
#feed-event .event .date {
margin-right: 1em !important;
border: 1px solid grey;
}
#feed-event .event .extra.text {
margin-left: 107px;
margin-top: 0;
div.geolocation-container {
/* each button have (more or less depends on borders) .5em space between */
/* zoom buttons are 60px high, geolocation and full screen button is 34px high with borders */
top: calc(1.3em + 60px + 34px);
}
.prewrap {
white-space: pre-wrap;
}
.ui.active.dimmer {
position: fixed;
}
.ui.modal > .content {
text-align: center;
}
.ui.modal > .actions {
display: flex;
justify-content: space-evenly;
}
</style>
\ No newline at end of file
<template>
<div
id="feature-edit"
class="page"
>
<h1 v-if="feature && currentRouteName === 'editer-signalement'">
Mise à jour du signalement "{{ feature.title || feature.feature_id }}"
</h1>
<h1
v-else-if="feature_type && currentRouteName === 'ajouter-signalement'"
>
Création d'un signalement <small>[{{ feature_type.title }}]</small>
<div id="feature-edit">
<h1>
<span v-if="feature_type && isCreation">
Création d'un signalement <small>[{{ feature_type.title }}]</small>
</span>
<span v-else-if="currentFeature && currentRouteName === 'editer-signalement'">
Mise à jour du signalement "{{ currentFeature.properties ?
currentFeature.properties.title : currentFeature.id }}"
</span>
<span v-else-if="feature_type && currentRouteName === 'editer-attribut-signalement'">
Mise à jour des attributs de {{ checkedFeatures.length }} signalements
</span>
</h1>
<form
id="form-feature-edit"
action=""
method="post"
enctype="multipart/form-data"
class="ui form"
>
<!-- Feature Fields -->
<div class="two fields">
<div :class="field_title">
<div
v-if="currentRouteName !== 'editer-attribut-signalement'"
:class="[ project && project.feature_assignement ? 'three' : 'two', 'fields']"
>
<div :class="['field', {'required': !titleIsOptional}]">
<label :for="form.title.id_for_label">{{ form.title.label }}</label>
<input
:id="form.title.id_for_label"
v-model="form.title.value"
type="text"
required
:required="!titleIsOptional"
:maxlength="form.title.field.max_length"
:name="form.title.html_name"
@blur="updateStore"
>
<ul
id="infoslist-title"
class="infoslist"
>
<li
v-for="info in form.title.infos"
:key="info"
>
{{ info }}
</li>
</ul>
<ul
id="errorlist-title"
class="errorlist"
......@@ -54,9 +67,22 @@
:selection.sync="selected_status"
/>
</div>
<div
v-if="project && project.feature_assignement"
class="field"
>
<label for="assigned_member">Membre assigné</label>
<ProjectMemberSelect
:selected-user-id="form.assigned_member.value"
@update:user="setMemberAssigned($event)"
/>
</div>
</div>
<div class="field">
<div
v-if="currentRouteName !== 'editer-attribut-signalement'"
class="field"
>
<label :for="form.description.id_for_label">{{
form.description.label
}}</label>
......@@ -69,7 +95,11 @@
</div>
<!-- Geom Field -->
<div class="field">
<div
v-if="currentRouteName !== 'editer-attribut-signalement'
&& feature_type && feature_type.geom_type !== 'none'"
class="field"
>
<label :for="form.geom.id_for_label">{{ form.geom.label }}</label>
<!-- Import GeoImage -->
<div
......@@ -229,7 +259,16 @@
<div
id="map"
ref="map"
/>
tabindex="0"
>
<SidebarLayers v-if="basemaps && map" />
<Geolocation />
<Geocoder />
<EditingToolbar
v-if="isEditable"
:map="map"
/>
</div>
<div
id="popup"
class="ol-popup"
......@@ -243,9 +282,6 @@
id="popup-content"
/>
</div>
<SidebarLayers v-if="basemaps && map" />
<EditingToolbar v-if="basemaps && map" />
</div>
</div>
......@@ -254,16 +290,22 @@
DONNÉES MÉTIER
</div>
<div
v-for="(field, index) in orderedCustomFields"
:key="field.field_type + index"
class="field"
v-for="field in extra_forms"
:key="field.name"
class="extraform"
>
<FeatureExtraForm :field="field" />
<ExtraForm
v-if="!field.isDeactivated"
:id="field.label"
ref="extraForm"
:field="field"
class="field"
/>
{{ field.errors }}
</div>
<!-- Pièces jointes -->
<div v-if="isOnline">
<div v-if="isOnline && currentRouteName !== 'editer-attribut-signalement'">
<div class="ui horizontal divider">
PIÈCES JOINTES
</div>
......@@ -276,6 +318,7 @@
:key="attachForm.dataKey"
ref="attachementForm"
:attachment-form="attachForm"
:enable-key-doc-notif="feature_type && feature_type.enable_key_doc_notif"
/>
</div>
<button
......@@ -293,7 +336,7 @@
</div>
<!-- Signalements liés -->
<div v-if="isOnline">
<div v-if="isOnline && currentRouteName !== 'editer-attribut-signalement'">
<div class="ui horizontal divider">
SIGNALEMENTS LIÉS
</div>
......@@ -320,9 +363,10 @@
</div>
<div class="ui divider" />
<button
id="save-changes"
type="button"
class="ui teal icon button"
@click="postForm"
:class="['ui teal icon button', { loading: sendingFeature }]"
@click="onSave"
>
<i
class="white save icon"
......@@ -336,20 +380,23 @@
<script>
import { mapState, mapGetters } from 'vuex';
import { GeoJSON } from 'ol/format';
import FeatureAttachmentForm from '@/components/Feature/FeatureAttachmentForm';
import FeatureLinkedForm from '@/components/Feature/FeatureLinkedForm';
import FeatureExtraForm from '@/components/Feature/Edit/FeatureExtraForm';
import ExtraForm from '@/components/ExtraForm';
import Dropdown from '@/components/Dropdown.vue';
import SidebarLayers from '@/components/Map/SidebarLayers';
import EditingToolbar from '@/components/Map/EditingToolbar';
import featureAPI from '@/services/feature-api';
import Geocoder from '@/components/Map/Geocoder';
import Geolocation from '@/components/Map/Geolocation';
import ProjectMemberSelect from '@/components/ProjectMemberSelect';
import featureAPI from '@/services/feature-api';
import mapService from '@/services/map-service';
import editionService from '@/services/edition-service';
import { allowedStatus2change } from '@/utils';
import { statusChoices, allowedStatus2change } from '@/utils';
import axios from '@/axios-client.js';
import { GeoJSON } from 'ol/format';
export default {
......@@ -360,14 +407,18 @@ export default {
FeatureLinkedForm,
Dropdown,
SidebarLayers,
Geocoder,
Geolocation,
EditingToolbar,
FeatureExtraForm,
ExtraForm,
ProjectMemberSelect
},
data() {
return {
map: null,
mapLoading: false,
sendingFeature: false,
baseUrl: this.$store.state.configuration.BASE_URL,
file: null,
showGeoRef: false,
......@@ -379,9 +430,10 @@ export default {
form: {
title: {
errors: [],
infos: [],
id_for_label: 'name',
field: {
max_length: 30,
max_length: 128,
},
html_name: 'name',
label: 'Nom',
......@@ -396,6 +448,9 @@ export default {
name: 'Brouillon',
},
},
assigned_member: {
value: null,
},
description: {
errors: [],
id_for_label: 'description',
......@@ -426,10 +481,11 @@ export default {
]),
...mapState('feature', [
'attachmentFormset',
'linkedFormset',
'checkedFeatures',
'currentFeature',
'extra_forms',
'features',
'extra_form',
'statusChoices',
'linkedFormset',
]),
...mapState('feature-type', [
'feature_types'
......@@ -442,25 +498,16 @@ export default {
'feature_type'
]),
field_title() {
if (this.feature_type) {
if (this.feature_type.title_optional) {
return 'field';
}
}
return 'required field';
titleIsOptional() {
return this.feature_type && this.feature_type.title_optional;
},
currentRouteName() {
return this.$route.name;
},
feature() {
return this.$store.state.feature.currentFeature;
},
orderedCustomFields() {
return [...this.extra_form].sort((a, b) => a.position - b.position);
isCreation() {
return this.currentRouteName === 'ajouter-signalement';
},
geoRefFileLabel() {
......@@ -473,6 +520,7 @@ export default {
selected_status: {
get() {
return this.form.status.value;
},
set(newValue) {
this.form.status.value = newValue;
......@@ -480,24 +528,47 @@ export default {
},
},
isFeatureCreator() {
if (this.currentFeature && this.currentFeature.properties && this.user) {
return this.currentFeature.properties.creator === this.user.id ||
this.currentFeature.properties.creator.username === this.user.username;
}
return false;
},
allowedStatusChoices() {
if (this.project && this.feature && this.user) {
if (this.project && this.USER_LEVEL_PROJECTS && this.user) {
const isModerate = this.project.moderation;
const userStatus = this.USER_LEVEL_PROJECTS[this.project.slug];
const isOwnFeature = this.feature.creator === this.user.id; //* si le contributeur est l'auteur du signalement
return allowedStatus2change(this.statusChoices, isModerate, userStatus, isOwnFeature, this.currentRouteName);
return allowedStatus2change(this.user, isModerate, userStatus, this.isFeatureCreator, this.currentRouteName);
}
return [];
},
isEditable() {
return this.basemaps && this.map && (this.feature_type && !this.feature_type.geom_type.includes('multi'));
}
},
watch: {
'form.title.value': function(newValue) {
if (newValue && newValue.length === 128) {
this.form.title.infos.push('Le nombre de caractères et limité à 128.');
} else {
this.form.title.infos = [];
}
}
},
created() {
this.$store.dispatch('GET_USERS_GROUPS'); // récupére les groupes d'utilisateurs pour extra_forms
this.$store.commit('feature/CLEAR_EXTRA_FORM');
this.$store.commit(
'feature-type/SET_CURRENT_FEATURE_TYPE_SLUG',
this.$route.params.slug_type_signal
);
//* empty previous feature data, not emptying by itself since it doesn't update by itself anymore
if (this.currentRouteName === 'ajouter-signalement') {
if (this.currentRouteName === 'ajouter-signalement' || this.currentRouteName === 'editer-attribut-signalement') {
this.$store.commit('feature/SET_CURRENT_FEATURE', []);
}
......@@ -508,10 +579,13 @@ export default {
},
mounted() {
const promises = [
this.$store.dispatch('projects/GET_PROJECT', this.$route.params.slug),
this.$store.dispatch('projects/GET_PROJECT_INFO', this.$route.params.slug),
];
const promises = [];
if (!this.project) {
promises.push(
this.$store.dispatch('projects/GET_PROJECT', this.$route.params.slug),
this.$store.dispatch('projects/GET_PROJECT_INFO', this.$route.params.slug),
);
}
if (this.$route.params.slug_signal) {
promises.push(
this.$store.dispatch('feature/GET_PROJECT_FEATURE', {
......@@ -522,14 +596,27 @@ export default {
}
Promise.all(promises).then(() => {
this.initForm();
this.initMap();
this.onFeatureTypeLoaded();
this.initExtraForms(this.feature);
if (this.currentRouteName !== 'editer-attribut-signalement') {
this.initForm();
// if not in the case of a non geographical feature type, init map
if (this.feature_type.geom_type !== 'none') {
this.initMap();
this.initMapTools();
this.initDeleteFeatureOnKey();
}
}
this.$store.dispatch('feature/INIT_EXTRA_FORMS');
});
},
beforeDestroy() {
this.$store.dispatch('CANCEL_CURRENT_SEARCH_REQUEST');
},
destroyed() {
editionService.removeActiveFeatures();
// emptying to enable adding event listener at feature edition straight after creation
editionService.selectForDeletion = null;
//* be sure that previous Formset have been cleared for creation
this.$store.commit('feature/CLEAR_ATTACHMENT_FORM');
this.$store.commit('feature/CLEAR_LINKED_FORM');
......@@ -538,22 +625,24 @@ export default {
methods: {
initForm() {
if (this.currentRouteName === 'editer-signalement') {
for (const key in this.feature) {
if (this.currentRouteName.includes('editer')) {
for (const key in this.currentFeature.properties) {
if (key && this.form[key]) {
if (key === 'status') {
const value = this.feature[key];
this.form[key].value = this.statusChoices.find(
const value = this.currentFeature.properties[key];
this.form[key].value = statusChoices.find(
(key) => key.value === value
);
} else {
this.form[key].value = this.feature[key];
this.form[key].value = this.currentFeature.properties[key];
}
}
}
this.form.geom.value = this.currentFeature.geometry;
this.updateStore();
}
},
addPointToCoordinates(coordinates){
let json = {
type: 'Feature',
......@@ -568,6 +657,7 @@ export default {
this.showGeoPositionBtn = false;
this.erreurGeolocalisationMessage = '';
},
create_point_geoposition() {
function success(position) {
this.addPointToCoordinates([position.coords.longitude, position.coords.latitude]);
......@@ -625,10 +715,10 @@ export default {
this.addAttachment({
title: 'Localisation',
info: '',
id: 'loc',
attachment_file: this.file.name,
fileToImport: this.file,
});
this.toggleGeoRefModal();
}
})
......@@ -643,24 +733,6 @@ export default {
});
},
initExtraForms(feature) {
function findCurrentValue(label) {
const field = feature.feature_data.find((el) => el.label === label);
return field ? field.value : null;
}
const extraForm = this.feature_type.customfield_set.map((field) => {
return {
...field,
//* add value field to extra forms from feature_type and existing values if feature is defined
value:
feature && feature.feature_data
? findCurrentValue(field.label)
: null,
};
});
this.$store.commit('feature/SET_EXTRA_FORM', extraForm);
},
add_attachement_formset() {
this.$store.commit('feature/ADD_ATTACHMENT_FORM', {
dataKey: this.attachmentDataKey,
......@@ -671,11 +743,7 @@ export default {
addAttachment(attachment) {
this.$store.commit('feature/ADD_ATTACHMENT_FORM', {
dataKey: this.attachmentDataKey,
title: attachment.title,
attachment_file: attachment.attachment_file,
info: attachment.info,
fileToImport: attachment.fileToImport,
id: attachment.id,
...attachment
});
this.attachmentDataKey += 1;
},
......@@ -704,12 +772,13 @@ export default {
},
updateStore() {
this.$store.commit('feature/UPDATE_FORM', {
return this.$store.commit('feature/UPDATE_FORM', {
title: this.form.title.value,
status: this.form.status.value,
description: this.form.description,
assigned_member: this.form.assigned_member,
geometry: this.form.geom.value,
feature_id: this.feature ? this.feature.feature_id : '',
feature_id: this.currentFeature ? this.currentFeature.id : '',
});
},
......@@ -745,6 +814,13 @@ export default {
checkAddedForm() {
let isValid = true; //* fallback if all customForms returned true
if (this.$refs.extraForm) {
for (const extraForm of this.$refs.extraForm) {
if (extraForm.checkForm() === false) {
isValid = false;
}
}
}
if (this.$refs.attachementForm) {
for (const attachementForm of this.$refs.attachementForm) {
if (attachementForm.checkForm() === false) {
......@@ -762,22 +838,30 @@ export default {
return isValid;
},
postForm() {
let is_valid = true;
if (!this.feature_type.title_optional) {
is_valid =
this.checkFormTitle() &&
this.checkFormGeom() &&
this.checkAddedForm();
onSave() {
if (this.currentRouteName === 'editer-attribut-signalement') {
this.postMultipleFeatures();
} else {
is_valid = this.checkFormGeom() && this.checkAddedForm();
this.postForm();
}
},
async postForm(extraForms) {
let response;
let is_valid = this.checkAddedForm();
// if not in the case of a non geographical feature type, check geometry's validity
if (this.feature_type && this.feature_type.geom_type !== 'none') {
is_valid = is_valid && this.checkFormGeom();
}
if (!this.feature_type.title_optional) {
is_valid = is_valid && this.checkFormTitle();
}
if (is_valid) {
//* in a moderate project, at edition of a published feature by someone else than admin or moderator, switch published status to draft.
if (
this.project.moderation &&
this.currentRouteName === 'editer-signalement' &&
this.currentRouteName.includes('editer') &&
this.form.status.value.value === 'published' &&
!this.permissions.is_project_administrator &&
!this.permissions.is_project_moderator
......@@ -785,18 +869,73 @@ export default {
this.form.status.value = { name: 'Brouillon', value: 'draft' };
this.updateStore();
}
this.$store.dispatch('feature/SEND_FEATURE', this.currentRouteName);
this.sendingFeature = true;
response = await this.$store.dispatch(
'feature/SEND_FEATURE',
{
routeName: this.currentRouteName,
query: this.$route.query,
extraForms// if multiple features, pass directly extraForms object to avoid mutating the store
}
);
this.sendingFeature = false;
return response;
}
},
async postMultipleFeatures() {
this.$store.commit('DISPLAY_LOADER', 'Envoi des signalements en cours...');
const responses = [];
// loop over each selected feature id
for (const featureId of this.checkedFeatures) {
// get other infos from this feature to feel the form
const response = await this.$store.dispatch('feature/GET_PROJECT_FEATURE', {
project_slug: this.$route.params.slug,
feature_id: featureId,
});
if (response.status === 200) {
// fill title, status & description in store, required to send feature update request
this.initForm();
// create a new object of custom form to send directly with the request, to avoid multiple asynchronous mutation in store
const newXtraForms = [];
// parse each current custom form values to update the new custom form for this feature
for (const extraForm of this.extra_forms) {
// copy current custom form to prevent modifying the original one
let newXtForm = { ...extraForm };
// if value wasn't changed in this page, get back previous value of the feature (rather than using feature orginal form, which is missing information to send in request)
if (newXtForm.value === null) {
newXtForm.value = this.currentFeature.properties[newXtForm.name];
}
newXtraForms.push(newXtForm);
}
const response = await this.postForm(newXtraForms);
responses.push(response);
}
}
this.$store.commit('DISCARD_LOADER');
const errors = responses.filter((res) => res === undefined || res.status !== 200).length > 0;
const message = {
comment: errors ? 'Des signalements n\'ont pas pu être mis à jour' : 'Les signalements ont été mis à jour',
level: errors ? 'negative' : 'positive'
};
this.$store.commit('DISPLAY_MESSAGE', message);
this.$router.push({
name: 'liste-signalements',
params: {
slug: this.$route.params.slug,
},
});
},
//* ************* MAP *************** *//
onFeatureTypeLoaded() {
var geomType = this.feature_type.geom_type;
initMapTools() {
const geomType = this.feature_type.geom_type;
editionService.addEditionControls(geomType);
editionService.draw.on('drawend', (evt) => {
var feature = evt.feature;
const feature = evt.feature;
this.updateGeomField(new GeoJSON().writeGeometry(feature.getGeometry(),{ dataProjection:'EPSG:4326',featureProjection:'EPSG:3857' }));
if (this.feature_type.geomType === 'point') {
this.showGeoPositionBtn = false;
......@@ -807,8 +946,6 @@ export default {
let feature = evt.features.getArray()[0];
this.updateGeomField(new GeoJSON().writeGeometry(feature.getGeometry(),{ dataProjection:'EPSG:4326',featureProjection:'EPSG:3857' }));
});
//this.changeMobileBtnOrder();
this.map.on(
'draw:deleted',
......@@ -830,7 +967,7 @@ export default {
}
if (geomFeatureJSON) {
let retour = new GeoJSON().readFeature(geomFeatureJSON,{ dataProjection:'EPSG:4326',featureProjection:'EPSG:3857' });
editionService.startEditFeature(retour);
editionService.initFeatureToEdit(retour);
} else {
this.map.setView(
......@@ -840,9 +977,9 @@ export default {
}
},
updateGeomField(newGeom) {
async updateGeomField(newGeom) {
this.form.geom.value = newGeom;
this.updateStore();
await this.updateStore();
},
initMap() {
......@@ -852,33 +989,34 @@ export default {
var mapDefaultViewZoom =
this.$store.state.configuration.DEFAULT_MAP_VIEW.zoom;
// Create the map, then init the layers and features
// Create the map, then init features
this.map = mapService.createMap(this.$refs.map, {
mapDefaultViewCenter,
mapDefaultViewZoom,
interactions : { doubleClickZoom :false, mouseWheelZoom:true, dragPan:true }
maxZoom: this.project.map_max_zoom_level,
interactions : { doubleClickZoom :false, mouseWheelZoom:true, dragPan:true },
fullScreenControl: true,
geolocationControl: true,
});
const currentFeatureId = this.$route.params.slug_signal;
const url = `${this.$store.state.configuration.VUE_APP_DJANGO_API_BASE}projects/${this.$route.params.slug}/feature/?feature_type__slug=${this.$route.params.slug_type_signal}&output=geojson`;
const url = `${this.$store.state.configuration.VUE_APP_DJANGO_API_BASE}v2/features/?feature_type__slug=${this.$route.params.slug_type_signal}&project__slug=${this.$route.params.slug}&output=geojson`;
axios
.get(url)
.then((response) => {
const features = response.data.features;
if (features) {
if (features.length > 0) {
const allFeaturesExceptCurrent = features.filter(
(feat) => feat.id !== currentFeatureId
);
mapService.addFeatures(
allFeaturesExceptCurrent,
{},
true,
this.feature_types
);
mapService.addFeatures({
addToMap: true,
project_slug: this.project.slug,
features: allFeaturesExceptCurrent,
featureTypes: this.feature_types,
});
if (this.currentRouteName === 'editer-signalement') {
const currentFeature = features.filter(
(feat) => feat.id === currentFeatureId
)[0];
this.updateMap(currentFeature);
editionService.setFeatureToEdit(this.currentFeature);
this.updateMap(this.currentFeature);
}
}
this.mapLoading = false;
......@@ -887,35 +1025,14 @@ export default {
this.mapLoading = false;
throw error;
});
},
document.addEventListener('change-layers-order', (event) => {
// Reverse is done because the first layer in order has to be added in the map in last.
// Slice is done because reverse() changes the original array, so we make a copy first
mapService.updateOrder(event.detail.layers.slice().reverse());
});
enableSnap() {
editionService.addSnapInteraction(this.map);
},
// TODO DDS voir adaptations
changeMobileBtnOrder() { //* move large toolbar for polygon creation, cutting map in the middle
function changeDisplay() {
const buttons = document.querySelector('.leaflet-draw-actions.leaflet-draw-actions-top.leaflet-draw-actions-bottom');
if (buttons && buttons.style) {
buttons.style.display = 'flex';
buttons.style['flex-direction'] = 'column';
}
}
if (window.screen.availWidth < 767) { //* change button order all the time to keep homogeinity on mobile
const wrapper = document.querySelector('.leaflet-top.leaflet-right');
if (wrapper) {
wrapper.appendChild(wrapper.children[0]);
}
if (this.feature_type.geom_type === 'polygon') { //* if it's a polygon, change tools direction to vertical
let polygonBtn = document.querySelector('.leaflet-draw-draw-polygon'); //* since elements are generated
if (polygonBtn) {
polygonBtn.addEventListener('click', changeDisplay); //* it should be done at each click
}
}
}
disableSnap() {
editionService.removeSnapInteraction(this.map);
},
getFeatureAttachments() {
......@@ -929,6 +1046,25 @@ export default {
.getFeatureLinks(this.$route.params.slug_signal)
.then((data) => this.addExistingLinkedFormset(data));
},
/**
* Deletes the selected feature when the "Delete" or "Escape" key is pressed.
* The map element has been made focusable by adding tabindex=0.
*/
initDeleteFeatureOnKey() {
// Add an event listener for key presses
document.addEventListener('keydown', function(event) {
// Check if the element with the ID "map" has focus
if ((event.key === 'Delete' || event.key === 'Escape') && document.activeElement.id === 'map') {
// If the conditions are met, call the deleteSelectedFeature function
editionService.removeFeatureFromMap();
}
});
},
setMemberAssigned(e) {
this.form.assigned_member.value = e;
this.updateStore();
}
},
};
</script>
......@@ -939,6 +1075,13 @@ export default {
width: 100%;
border: 1px solid grey;
}
div.geolocation-container {
/* each button have .5em space between, zoom buttons are 60px high and full screen button is 34px high */
top: calc(1.3em + 60px + 34px);
}
#get-geom-from-image-file {
margin-bottom: 5px;
}
......@@ -966,4 +1109,7 @@ export default {
.leaflet-bottom {
z-index: 800;
}
.extraform {
margin-bottom: 1em;
}
</style>