Expose multiple user selections on champ carte

This commit is contained in:
Paul Chavard 2020-04-09 17:32:20 +02:00
parent 55e99a323c
commit 22604013d0
14 changed files with 230 additions and 245 deletions

View file

@ -39,9 +39,10 @@ class Champs::CarteController < ApplicationController
end
end
selection_utilisateur = ApiCartoService.generate_selection_utilisateur(coordinates)
selection_utilisateur[:source] = GeoArea.sources.fetch(:selection_utilisateur)
geo_areas << selection_utilisateur
selections_utilisateur = legacy_selections_utilisateur_to_polygons(coordinates)
geo_areas += selections_utilisateur.map do |selection_utilisateur|
selection_utilisateur.merge(source: GeoArea.sources.fetch(:selection_utilisateur))
end
@champ.geo_areas = geo_areas.map do |geo_area|
GeoArea.new(geo_area)
@ -58,4 +59,17 @@ class Champs::CarteController < ApplicationController
flash.alert = 'Les données cartographiques sont temporairement indisponibles. Réessayez dans un instant.'
response.status = 503
end
private
def legacy_selections_utilisateur_to_polygons(coordinates)
coordinates.map do |lat_longs|
{
geometry: {
type: 'Polygon',
coordinates: [lat_longs.map { |lat_long| [lat_long['lng'], lat_long['lat']] }]
}
}
end
end
end

View file

@ -37,4 +37,18 @@ module ChampHelper
champs_piece_justificative_url(object.id)
end
end
def geo_area_label(geo_area)
case geo_area.source
when GeoArea.sources.fetch(:cadastre)
capture do
concat "Parcelle n° #{geo_area.numero} - Feuille #{geo_area.code_arr} #{geo_area.section} #{geo_area.feuille} - #{geo_area.surface_parcelle.round} m"
concat content_tag(:sup, "2")
end
when GeoArea.sources.fetch(:quartier_prioritaire)
"#{geo_area.commune} : #{geo_area.nom}"
when GeoArea.sources.fetch(:parcelle_agricole)
"Culture : #{geo_area.culture} - Surface : #{geo_area.surface} ha"
end
end
end

View file

@ -1,48 +1,36 @@
import React from 'react';
import ReactMapboxGl, { ZoomControl, GeoJSONLayer } from 'react-mapbox-gl';
import mapboxgl, { LngLatBounds } from 'mapbox-gl';
import mapboxgl from 'mapbox-gl';
import PropTypes from 'prop-types';
const Map = ReactMapboxGl({});
const MapReader = ({ geoData }) => {
let [selectionCollection, cadastresCollection] = [[], []];
const MapReader = ({ featureCollection }) => {
const [a1, a2, b1, b2] = featureCollection.bbox;
const boundData = [
[a1, a2],
[b1, b2]
];
for (let selection of geoData.selection.coordinates) {
selectionCollection.push({
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: selection
}
});
}
for (let cadastre of geoData.cadastres) {
cadastresCollection.push({
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: cadastre.geometry.coordinates[0]
}
});
}
const selectionData = {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: selectionCollection
}
const selectionsFeatureCollection = {
type: 'FeatureCollection',
features: []
};
const cadastresFeatureCollection = {
type: 'FeatureCollection',
features: []
};
const cadastresData = {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: cadastresCollection
for (let feature of featureCollection.features) {
switch (feature.properties.source) {
case 'selection_utilisateur':
selectionsFeatureCollection.features.push(feature);
break;
case 'cadastre':
cadastresFeatureCollection.features.push(feature);
break;
}
};
}
const polygonSelectionFill = {
'fill-color': '#EC3323',
@ -65,19 +53,6 @@ const MapReader = ({ geoData }) => {
'line-dasharray': [1, 1]
};
let bounds = new LngLatBounds();
for (let selection of selectionCollection) {
for (let coordinate of selection.geometry.coordinates[0]) {
bounds.extend(coordinate);
}
}
let [swCoords, neCoords] = [
Object.values(bounds._sw),
Object.values(bounds._ne)
];
const boundData = [swCoords, neCoords];
if (!mapboxgl.supported()) {
return (
<p>
@ -99,12 +74,12 @@ const MapReader = ({ geoData }) => {
}}
>
<GeoJSONLayer
data={selectionData.data}
data={selectionsFeatureCollection}
fillPaint={polygonSelectionFill}
linePaint={polygonSelectionLine}
/>
<GeoJSONLayer
data={cadastresData.data}
data={cadastresFeatureCollection}
fillPaint={polygonCadastresFill}
linePaint={polygonCadastresLine}
/>
@ -114,10 +89,10 @@ const MapReader = ({ geoData }) => {
};
MapReader.propTypes = {
geoData: PropTypes.shape({
position: PropTypes.object,
selection: PropTypes.object,
cadastres: PropTypes.array
featureCollection: PropTypes.shape({
type: PropTypes.string,
bbox: PropTypes.array,
features: PropTypes.array
})
};

View file

@ -19,8 +19,10 @@ class Champs::CarteChamp < Champ
end
end
def selection_utilisateur
geo_areas.find(&:selection_utilisateur?)
def selections_utilisateur
geo_areas.filter do |area|
area.source == GeoArea.sources.fetch(:selection_utilisateur)
end
end
def cadastres?
@ -47,68 +49,73 @@ class Champs::CarteChamp < Champ
end
end
def geo_json
@geo_json ||= begin
geo_area = selection_utilisateur
def bounding_box
factory = RGeo::Geographic.simple_mercator_factory
bounding_box = RGeo::Cartesian::BoundingBox.new(factory)
if geo_area
geo_area.geometry
else
geo_json_from_value
if geo_areas.present?
geo_areas.each do |area|
bounding_box.add(area.rgeo_geometry)
end
elsif dossier.present?
point = dossier.geo_position
bounding_box.add(factory.point(point[:lon], point[:lat]))
else
bounding_box.add(factory.point(2.428462, 46.538192))
end
[bounding_box.max_point, bounding_box.min_point].compact.flat_map(&:coordinates)
end
def to_feature_collection
{
type: 'FeatureCollection',
bbox: bounding_box,
features: (legacy_selections_utilisateur + except_selections_utilisateur).map(&:to_feature)
}
end
def geometry?
geo_areas.present?
end
def selection_utilisateur_legacy_geometry
if selection_utilisateur_legacy?
selections_utilisateur.first.geometry
elsif selections_utilisateur.present?
{
type: 'MultiPolygon',
coordinates: selections_utilisateur.filter do |selection_utilisateur|
selection_utilisateur.geometry['type'] == 'Polygon'
end.map do |selection_utilisateur|
selection_utilisateur.geometry['coordinates']
end
}
else
nil
end
end
def selection_utilisateur_size
if geo_json.present?
geo_json['coordinates'].size
else
0
def selection_utilisateur_legacy_geo_area
geometry = selection_utilisateur_legacy_geometry
if geometry.present?
GeoArea.new(
source: GeoArea.sources.fetch(:selection_utilisateur),
geometry: geometry
)
end
end
def to_render_data
{
position: position,
selection: user_geo_area&.geometry,
selection: selection_utilisateur_legacy_geometry,
quartiersPrioritaires: quartiers_prioritaires? ? quartiers_prioritaires.as_json(except: :properties) : [],
cadastres: cadastres? ? cadastres.as_json(except: :properties) : [],
parcellesAgricoles: parcelles_agricoles? ? parcelles_agricoles.as_json(except: :properties) : []
}
end
def user_geo_area
geo_area = selection_utilisateur
if geo_area.present?
geo_area
elsif geo_json_from_value.present?
GeoArea.new(
geometry: geo_json_from_value,
source: GeoArea.sources.fetch(:selection_utilisateur)
)
end
end
def geo_json_from_value
@geo_json_from_value ||= begin
parsed_value = value.blank? ? nil : JSON.parse(value)
# We used to store in the value column a json array with coordinates.
if parsed_value.is_a?(Array)
# Empty array is sent instead of blank to distinguish between empty and error
if parsed_value.empty?
nil
else
# If it is a coordinates array, format it as a GEO-JSON
JSON.parse(GeojsonService.to_json_polygon_for_selection_utilisateur(parsed_value))
end
else
# It is already a GEO-JSON
parsed_value
end
end
end
def for_api
nil
end
@ -116,4 +123,38 @@ class Champs::CarteChamp < Champ
def for_export
nil
end
private
def selection_utilisateur_legacy?
if selections_utilisateur.size == 1
geometry = selections_utilisateur.first.geometry
return geometry && geometry['type'] == 'MultiPolygon'
end
false
end
def legacy_selections_utilisateur
if selection_utilisateur_legacy?
selections_utilisateur.first.geometry['coordinates'].map do |coordinates|
GeoArea.new(
geometry: {
type: 'Polygon',
coordinates: coordinates
},
properties: {},
source: GeoArea.sources.fetch(:selection_utilisateur)
)
end
else
selections_utilisateur
end
end
def except_selections_utilisateur
geo_areas.filter do |area|
area.source != GeoArea.sources.fetch(:selection_utilisateur)
end
end
end

View file

@ -27,11 +27,20 @@ class GeoArea < ApplicationRecord
selection_utilisateur: 'selection_utilisateur'
}
scope :selections_utilisateur, -> { where(source: sources.fetch(:selection_utilisateur)) }
scope :quartiers_prioritaires, -> { where(source: sources.fetch(:quartier_prioritaire)) }
scope :cadastres, -> { where(source: sources.fetch(:cadastre)) }
scope :parcelles_agricoles, -> { where(source: sources.fetch(:parcelle_agricole)) }
def selection_utilisateur?
source == self.class.sources.fetch(:selection_utilisateur)
def to_feature
{
type: 'Feature',
geometry: geometry,
properties: properties.merge(source: source)
}
end
def rgeo_geometry
RGeo::GeoJSON.decode(geometry.to_json, geo_factory: RGeo::Geographic.simple_mercator_factory)
end
end

View file

@ -38,11 +38,12 @@ class DossierSerializer < ActiveModel::Serializer
end
if champ_carte.present?
carto_champs = champ_carte.geo_areas.to_a
if !carto_champs.find(&:selection_utilisateur?)
carto_champs << champ_carte.user_geo_area
champs_geo_areas = geo_areas.filter do |geo_area|
geo_area.source != GeoArea.sources.fetch(:selection_utilisateur)
end
champs += carto_champs.compact
champs_geo_areas << champ_carte.selection_utilisateur_legacy_geo_area
champs += champs_geo_areas.compact
end
end

View file

@ -22,10 +22,4 @@ class ApiCartoService
).results
end
end
def self.generate_selection_utilisateur(coordinates)
{
geometry: JSON.parse(GeojsonService.to_json_polygon_for_selection_utilisateur(coordinates))
}
end
end

View file

@ -14,21 +14,4 @@ class GeojsonService
polygon.to_json
end
def self.to_json_polygon_for_selection_utilisateur(coordinates)
coordinates = coordinates.map do |lat_longs|
outbounds = lat_longs.map do |lat_long|
[lat_long['lng'], lat_long['lat']]
end
[outbounds]
end
polygon = {
type: 'MultiPolygon',
coordinates: coordinates
}
polygon.to_json
end
end

View file

@ -86,7 +86,7 @@ def render_single_champ(pdf, champ)
when 'Champs::ExplicationChamp'
format_in_2_lines(pdf, champ.libelle, champ.description)
when 'Champs::CarteChamp'
format_in_2_lines(pdf, champ.libelle, champ.geo_json.to_s)
format_in_2_lines(pdf, champ.libelle, champ.to_feature_collection.to_json)
when 'Champs::SiretChamp'
pdf.font 'liberation serif', style: :bold, size: 12 do
pdf.text champ.libelle

View file

@ -3,39 +3,39 @@
.areas
- if error.present?
.error Merci de dessiner une surface plus petite afin de récupérer les quartiers prioritaires.
- elsif champ.value.blank?
- elsif !champ.geometry?
Aucune zone tracée
- elsif champ.quartiers_prioritaires.blank?
= t('errors.messages.quartiers_prioritaires_empty', count: champ.selection_utilisateur_size)
= t('errors.messages.quartiers_prioritaires_empty', count: champ.selections_utilisateur.size)
- else
%ul
- champ.quartiers_prioritaires.each do |qp|
%li #{qp.commune} : #{qp.nom}
- champ.quartiers_prioritaires.each do |geo_area|
%li= geo_area_label(geo_area)
- if champ.cadastres?
.areas-title Parcelles cadastrales
.areas
- if error.present?
.error Merci de dessiner une surface plus petite afin de récupérer les parcelles cadastrales.
- elsif champ.value.blank?
- elsif !champ.geometry?
Aucune zone tracée
- elsif champ.cadastres.blank?
= t('errors.messages.cadastres_empty', count: champ.selection_utilisateur_size)
= t('errors.messages.cadastres_empty', count: champ.selections_utilisateur.size)
- else
%ul
- champ.cadastres.each do |pc|
%li Parcelle n° #{pc.numero} - Feuille #{pc.code_arr} #{pc.section} #{pc.feuille} - #{pc.surface_parcelle.round} m<sup>2</sup>
- champ.cadastres.each do |geo_area|
%li= geo_area_label(geo_area)
- if champ.parcelles_agricoles?
.areas-title Parcelles agricoles (RPG)
.areas
- if error.present?
.error Merci de dessiner une surface plus petite afin de récupérer les parcelles agricoles.
- elsif champ.value.blank?
- elsif !champ.geometry?
Aucune zone tracée
- elsif champ.parcelles_agricoles.blank?
= t('errors.messages.parcelles_agricoles_empty', count: champ.selection_utilisateur_size)
= t('errors.messages.parcelles_agricoles_empty', count: champ.selections_utilisateur.size)
- else
%ul
- champ.parcelles_agricoles.each do |pa|
%li Culture : #{pa.culture} - Surface : #{pa.surface} ha
- champ.parcelles_agricoles.each do |geo_area|
%li= geo_area_label(geo_area)

View file

@ -1,4 +1,4 @@
- if champ.to_s.present?
= react_component("MapReader", { geoData: champ.to_render_data } )
- if champ.geometry?
= react_component("MapReader", { featureCollection: champ.to_feature_collection } )
.geo-areas
= render partial: 'shared/champs/carte/geo_areas', locals: { champ: champ, error: false }

View file

@ -13,11 +13,10 @@ describe Champs::CarteController, type: :controller do
champ_id: champ.id
}
end
let(:geojson) { [] }
let(:champ) do
create(:type_de_champ_carte, options: {
cadastres: true
}).champ.create(dossier: dossier, value: geojson.to_json)
}).champ.create(dossier: dossier)
end
describe 'POST #show' do
@ -31,7 +30,7 @@ describe Champs::CarteController, type: :controller do
allow_any_instance_of(ApiCarto::CadastreAdapter)
.to receive(:results)
.and_return([{ code: "QPCODE1234", surface_parcelle: 4, geometry: { type: "MultiPolygon", coordinates: [[[[2.38715792094576, 48.8723062632126], [2.38724851642619, 48.8721392348061]]]] } }])
.and_return([{ code: "QPCODE1234", surface_parcelle: 4, geometry: { type: "MultiPolygon", coordinates: [[[[2.38715792094576, 48.8723062632126], [2.38724851642619, 48.8721392348061], [2.38724851642620, 48.8721392348064], [2.38715792094576, 48.8723062632126]]]] } }])
post :show, params: params, format: 'js'
end
@ -43,7 +42,7 @@ describe Champs::CarteController, type: :controller do
expect(assigns(:error)).to eq(nil)
expect(champ.reload.value).to eq(nil)
expect(champ.reload.geo_areas).to eq([])
expect(response.body).to include("DS.fire('carte:update', {\"selector\":\".carte-1\",\"data\":{\"position\":{\"lon\":\"2.428462\",\"lat\":\"46.538192\",\"zoom\":\"13\"},\"selection\":null,\"quartiersPrioritaires\":[],\"cadastres\":[],\"parcellesAgricoles\":[]}});")
expect(response.body).to include("DS.fire('carte:update'")
}
end
@ -56,7 +55,6 @@ describe Champs::CarteController, type: :controller do
end
context 'when error' do
let(:geojson) { [[{ "lat": 48.87442541960633, "lng": 2.3859214782714844 }, { "lat": 48.87273183590832, "lng": 2.3850631713867183 }, { "lat": 48.87081237174292, "lng": 2.3809432983398438 }, { "lat": 48.8712640169951, "lng": 2.377510070800781 }, { "lat": 48.87510283703279, "lng": 2.3778533935546875 }, { "lat": 48.87544154230615, "lng": 2.382831573486328 }, { "lat": 48.87442541960633, "lng": 2.3859214782714844 }]] }
let(:value) { '' }
it {

View file

@ -1,9 +1,19 @@
describe Champs::CarteChamp do
let(:champ) { Champs::CarteChamp.new(value: value) }
let(:champ) { Champs::CarteChamp.new(geo_areas: geo_areas) }
let(:value) { '' }
let(:coordinates) { [[{ "lat" => 48.87442541960633, "lng" => 2.3859214782714844 }, { "lat" => 48.87273183590832, "lng" => 2.3850631713867183 }, { "lat" => 48.87081237174292, "lng" => 2.3809432983398438 }, { "lat" => 48.8712640169951, "lng" => 2.377510070800781 }, { "lat" => 48.87510283703279, "lng" => 2.3778533935546875 }, { "lat" => 48.87544154230615, "lng" => 2.382831573486328 }, { "lat" => 48.87442541960633, "lng" => 2.3859214782714844 }]] }
let(:geo_json_as_string) { GeojsonService.to_json_polygon_for_selection_utilisateur(coordinates) }
let(:geo_json) { JSON.parse(geo_json_as_string) }
let(:coordinates) { [[2.3859214782714844, 48.87442541960633], [2.3850631713867183, 48.87273183590832], [2.3809432983398438, 48.87081237174292], [2.3859214782714844, 48.87442541960633]] }
let(:geo_json) do
{
"type" => 'Polygon',
"coordinates" => coordinates
}
end
let(:legacy_geo_json) do
{
type: 'MultiPolygon',
coordinates: [coordinates]
}
end
describe '#to_render_data' do
subject { champ.to_render_data }
@ -18,78 +28,44 @@ describe Champs::CarteChamp do
}
}
context 'when the value is nil' do
let(:value) { nil }
context 'when has no geo_areas' do
let(:geo_areas) { [] }
let(:selection) { nil }
it { is_expected.to eq(render_data) }
end
context 'when the value is blank' do
let(:value) { '' }
let(:selection) { nil }
it { is_expected.to eq(render_data) }
end
context 'when the value is empty array' do
let(:value) { '[]' }
let(:selection) { nil }
it { is_expected.to eq(render_data) }
end
context 'when the value is coordinates' do
let(:value) { coordinates.to_json }
let(:selection) { geo_json }
it { is_expected.to eq(render_data) }
end
context 'when the value is geojson' do
let(:value) { geo_json.to_json }
let(:selection) { geo_json }
context 'when has one geo_area' do
let(:geo_areas) { [build(:geo_area, :selection_utilisateur, geometry: geo_json)] }
let(:selection) { legacy_geo_json }
it { is_expected.to eq(render_data) }
end
end
describe '#selection_utilisateur_size' do
subject { champ.selection_utilisateur_size }
describe '#to_feature_collection' do
subject { champ.to_feature_collection }
context 'when the value is nil' do
let(:value) { nil }
let(:feature_collection) {
{
type: 'FeatureCollection',
bbox: champ.bounding_box,
features: features
}
}
it { is_expected.to eq(0) }
context 'when has no geo_areas' do
let(:geo_areas) { [] }
let(:features) { [] }
it { is_expected.to eq(feature_collection) }
end
context 'when the value is blank' do
let(:value) { '' }
context 'when has one geo_area' do
let(:geo_areas) { [build(:geo_area, :selection_utilisateur, geometry: geo_json)] }
let(:features) { geo_areas.map(&:to_feature) }
it { is_expected.to eq(0) }
end
context 'when the value is empty array' do
let(:value) { '[]' }
it { is_expected.to eq(0) }
end
context 'when the value is coordinates' do
let(:value) { coordinates.to_json }
it { is_expected.to eq(1) }
end
context 'when the value is geojson' do
let(:value) { geo_json.to_json }
it { is_expected.to eq(1) }
it { is_expected.to eq(feature_collection) }
end
end
end

View file

@ -27,9 +27,13 @@ describe ChampSerializer do
let(:champ) { create(:champ_carte, value: value, geo_areas: [geo_area].compact) }
let(:value) { nil }
let(:geo_area) { create(:geo_area, geometry: geo_json) }
let(:geo_json_as_string) { GeojsonService.to_json_polygon_for_selection_utilisateur(coordinates) }
let(:geo_json) { JSON.parse(geo_json_as_string) }
let(:coordinates) { [[{ "lat" => 48.87442541960633, "lng" => 2.3859214782714844 }, { "lat" => 48.87273183590832, "lng" => 2.3850631713867183 }, { "lat" => 48.87081237174292, "lng" => 2.3809432983398438 }, { "lat" => 48.8712640169951, "lng" => 2.377510070800781 }, { "lat" => 48.87510283703279, "lng" => 2.3778533935546875 }, { "lat" => 48.87544154230615, "lng" => 2.382831573486328 }, { "lat" => 48.87442541960633, "lng" => 2.3859214782714844 }]] }
let(:geo_json) do
{
"type" => 'MultiPolygon',
"coordinates" => coordinates
}
end
let(:coordinates) { [[[2.3859214782714844, 48.87442541960633], [2.3850631713867183, 48.87273183590832], [2.3809432983398438, 48.87081237174292], [2.3859214782714844, 48.87442541960633]]] }
let(:serialized_champ) {
{
@ -60,19 +64,19 @@ describe ChampSerializer do
context 'when value is nil' do
let(:value) { nil }
it { expect(champ.user_geo_area).to be_nil }
it { expect(champ.selection_utilisateur_legacy_geo_area).to be_nil }
end
context 'when value is empty array' do
let(:value) { '[]' }
it { expect(champ.user_geo_area).to be_nil }
it { expect(champ.selection_utilisateur_legacy_geo_area).to be_nil }
end
context 'when value is blank' do
let(:value) { '' }
it { expect(champ.user_geo_area).to be_nil }
it { expect(champ.selection_utilisateur_legacy_geo_area).to be_nil }
end
end
@ -80,7 +84,7 @@ describe ChampSerializer do
let(:serialized_libelle) { "user geometry" }
let(:serialized_type_champ) { "user_geometry" }
let(:serializable_object) { champ.user_geo_area }
let(:serializable_object) { champ.selection_utilisateur_legacy_geo_area }
context 'when value is coordinates' do
let(:value) { coordinates.to_json }
@ -167,30 +171,6 @@ describe ChampSerializer do
it { expect(subject).to eq(serialized_champ) }
end
end
context 'and geo_area is quartier_prioritaire' do
let(:geo_area) { create(:geo_area, :quartier_prioritaire, geometry: geo_json) }
context 'new_api' do
it {
expect(subject[:geo_areas].first).to include(
source: GeoArea.sources.fetch(:quartier_prioritaire),
geometry: geo_json,
nom: 'XYZ',
commune: 'Paris'
)
expect(subject[:geo_areas].first.key?(:numero)).to be_falsey
}
end
context 'old_api' do
let(:serializable_object) { champ.geo_areas.first }
let(:serialized_libelle) { "quartier prioritaire" }
let(:serialized_type_champ) { "quartier_prioritaire" }
it { expect(subject).to eq(serialized_champ) }
end
end
end
context 'when type champ is siret' do