Skip to content

Commit

Permalink
Merge pull request #2892 from tchak/carte-rpg
Browse files Browse the repository at this point in the history
Add RPG carte source
  • Loading branch information
tchak authored Oct 23, 2018
2 parents 546b4b7 + 4abcffe commit f0610c4
Show file tree
Hide file tree
Showing 29 changed files with 404 additions and 86 deletions.
8 changes: 8 additions & 0 deletions app/controllers/champs/carte_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@ def show
qp
end
end

if @champ.parcelles_agricoles?
parcelles_agricoles = ModuleApiCartoService.generate_rpg(geo_json)
geo_areas += parcelles_agricoles.map do |parcelle_agricole|
parcelle_agricole[:source] = GeoArea.sources.fetch(:parcelle_agricole)
parcelle_agricole
end
end
end

@champ.geo_areas = geo_areas.map do |geo_area|
Expand Down
3 changes: 2 additions & 1 deletion app/helpers/champ_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ def geo_data(champ)
position: champ.position,
selection: champ.value.present? ? JSON.parse(champ.value) : [],
quartiersPrioritaires: champ.quartiers_prioritaires? ? champ.quartiers_prioritaires : [],
cadastres: champ.cadastres? ? champ.cadastres : []
cadastres: champ.cadastres? ? champ.cadastres : [],
parcellesAgricoles: champ.parcelles_agricoles? ? champ.parcelles_agricoles : []
}.to_json)
# rubocop:enable Rails/OutputSafety
end
Expand Down
2 changes: 2 additions & 0 deletions app/javascript/new_design/champs/carte.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
geocodeAddress,
drawCadastre,
drawQuartiersPrioritaires,
drawParcellesAgricoles,
drawUserSelection,
addFreeDrawEvents
} from '../../shared/carte';
Expand All @@ -30,6 +31,7 @@ function diplayMap(element, data, initial = false) {
// draw external polygons
drawCadastre(map, data, editable);
drawQuartiersPrioritaires(map, data, editable);
drawParcellesAgricoles(map, data, editable);

// draw user polygon
if (initial) {
Expand Down
17 changes: 17 additions & 0 deletions app/javascript/shared/carte.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,19 @@ export function drawQuartiersPrioritaires(
);
}

export function drawParcellesAgricoles(
map,
{ parcellesAgricoles },
editable = false
) {
drawLayer(
map,
parcellesAgricoles,
editable ? RPG_POLYGON_STYLE : noEditStyle(RPG_POLYGON_STYLE),
'parcellesAgricoles'
);
}

export function drawUserSelection(map, { selection }, editable = false) {
let hasSelection = selection && selection.length > 0;

Expand Down Expand Up @@ -170,6 +183,10 @@ const QP_POLYGON_STYLE = Object.assign({}, POLYGON_STYLE, {
fillColor: '#31708f'
});

const RPG_POLYGON_STYLE = Object.assign({}, POLYGON_STYLE, {
fillColor: '#31708f'
});

delegate('click', '.carte.edit', event => {
let element = event.target;
let isPath = element.matches('.leaflet-container g path');
Expand Down
40 changes: 33 additions & 7 deletions app/lib/api_geo/api.rb
Original file line number Diff line number Diff line change
@@ -1,23 +1,49 @@
class ApiGeo::API
TIMEOUT = 15

def self.regions
url = [API_GEO_URL, "regions"].join("/")
call(url)
call(url, { fields: :nom })
end

def self.departements
url = [API_GEO_URL, "departements"].join("/")
call(url)
call(url, { fields: :nom })
end

def self.pays
File.open('app/lib/api_geo/pays.json').read
parse(File.open('app/lib/api_geo/pays.json').read)
end

def self.search_rpg(geojson)
url = [API_GEO_SANDBOX_URL, "rpg", "parcelles", "search"].join("/")
call(url, geojson, :post)
end

private

def self.call(url)
RestClient.get(url, params: { fields: :nom })
rescue RestClient::ServiceUnavailable
nil
def self.parse(body)
JSON.parse(body, symbolize_names: true)
end

def self.call(url, body, method = :get)
response = Typhoeus::Request.new(
url,
method: method,
params: method == :get ? body : nil,
body: method == :post ? body : nil,
timeout: TIMEOUT,
accept_encoding: 'gzip',
headers: {
'Accept' => 'application/json',
'Accept-Encoding' => 'gzip, deflate'
}.merge(method == :post ? { 'Content-Type' => 'application/json' } : {})
).run

if response.success?
parse(response.body)
else
nil
end
end
end
24 changes: 24 additions & 0 deletions app/lib/api_geo/rpg_adapter.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
class ApiGeo::RPGAdapter
def initialize(coordinates)
@coordinates = GeojsonService.to_json_polygon_for_rpg(coordinates)
end

def data_source
@data_source ||= ApiGeo::API.search_rpg(@coordinates)
end

def results
data_source[:features].map do |feature|
feature[:properties]
.stringify_keys
.transform_keys(&:underscore)
.symbolize_keys
.slice(
:culture,
:code_culture,
:surface,
:bio
).merge({ geometry: feature[:geometry] })
end
end
end
10 changes: 10 additions & 0 deletions app/models/champs/carte_champ.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ def quartiers_prioritaires
end
end

def parcelles_agricoles
geo_areas.select do |area|
area.source == GeoArea.sources.fetch(:parcelle_agricole)
end
end

def cadastres?
type_de_champ&.cadastres && type_de_champ.cadastres != '0'
end
Expand All @@ -23,6 +29,10 @@ def quartiers_prioritaires?
type_de_champ&.quartiers_prioritaires && type_de_champ.quartiers_prioritaires != '0'
end

def parcelles_agricoles?
type_de_champ&.parcelles_agricoles && type_de_champ.parcelles_agricoles != '0'
end

def position
if dossier.present?
dossier.geo_position
Expand Down
2 changes: 1 addition & 1 deletion app/models/champs/departement_champ.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class Champs::DepartementChamp < Champs::TextChamp
def self.departements
JSON.parse(ApiGeo::API.departements).map { |liste| "#{liste['code']} - #{liste['nom']}" }.push('99 - Étranger')
ApiGeo::API.departements.map { |liste| "#{liste[:code]} - #{liste[:nom]}" }.push('99 - Étranger')
end
end
2 changes: 1 addition & 1 deletion app/models/champs/pays_champ.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class Champs::PaysChamp < Champs::TextChamp
def self.pays
JSON.parse(ApiGeo::API.pays).pluck("nom")
ApiGeo::API.pays.pluck(:nom)
end
end
2 changes: 1 addition & 1 deletion app/models/champs/region_champ.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class Champs::RegionChamp < Champs::TextChamp
def self.regions
JSON.parse(ApiGeo::API.regions).sort_by { |e| e['nom'] }.pluck("nom")
ApiGeo::API.regions.sort_by { |e| e[:nom] }.pluck(:nom)
end
end
10 changes: 8 additions & 2 deletions app/models/geo_area.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,20 @@ class GeoArea < ApplicationRecord
:code_arr,
:code,
:nom,
:commune
:commune,
:culture,
:code_culture,
:surface,
:bio
]

enum source: {
quartier_prioritaire: 'quartier_prioritaire',
cadastre: 'cadastre'
cadastre: 'cadastre',
parcelle_agricole: 'parcelle_agricole'
}

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)) }
end
2 changes: 1 addition & 1 deletion app/models/type_de_champ.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class TypeDeChamp < ApplicationRecord

belongs_to :procedure

store :options, accessors: [:cadastres, :quartiers_prioritaires]
store :options, accessors: [:cadastres, :quartiers_prioritaires, :parcelles_agricoles]

after_initialize :set_dynamic_type

Expand Down
46 changes: 32 additions & 14 deletions app/serializers/geo_area_serializer.rb
Original file line number Diff line number Diff line change
@@ -1,16 +1,34 @@
class GeoAreaSerializer < ActiveModel::Serializer
attributes :geometry,
:source,
:surface_intersection,
:surface_parcelle,
:numero,
:feuille,
:section,
:code_dep,
:nom_com,
:code_com,
:code_arr,
:code,
:nom,
:commune
attributes :geometry, :source

attribute :surface_intersection, if: :include_cadastre?
attribute :surface_parcelle, if: :include_cadastre?
attribute :numero, if: :include_cadastre?
attribute :feuille, if: :include_cadastre?
attribute :section, if: :include_cadastre?
attribute :code_dep, if: :include_cadastre?
attribute :nom_com, if: :include_cadastre?
attribute :code_com, if: :include_cadastre?
attribute :code_arr, if: :include_cadastre?

attribute :code, if: :include_quartier_prioritaire?
attribute :nom, if: :include_quartier_prioritaire?
attribute :commune, if: :include_quartier_prioritaire?

attribute :culture, if: :include_parcelle_agricole?
attribute :code_culture, if: :include_parcelle_agricole?
attribute :surface, if: :include_parcelle_agricole?
attribute :bio, if: :include_parcelle_agricole?

def include_cadastre?
object.source == GeoArea.sources.fetch(:cadastre)
end

def include_quartier_prioritaire?
object.source == GeoArea.sources.fetch(:quartier_prioritaire)
end

def include_parcelle_agricole?
object.source == GeoArea.sources.fetch(:parcelle_agricole)
end
end
11 changes: 11 additions & 0 deletions app/services/geojson_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,15 @@ def self.to_json_polygon_for_cadastre(coordinates)

polygon.to_json
end

def self.to_json_polygon_for_rpg(coordinates)
polygon = {
polygonIntersects: {
type: "Polygon",
coordinates: [coordinates]
}
}

polygon.to_json
end
end
8 changes: 8 additions & 0 deletions app/services/module_api_carto_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,12 @@ def self.generate_cadastre(coordinates)
).results
end
end

def self.generate_rpg(coordinates)
coordinates.flat_map do |coordinate|
ApiGeo::RPGAdapter.new(
coordinate.map { |element| [element['lng'], element['lat']] }
).results
end
end
end
1 change: 1 addition & 0 deletions app/services/types_de_champ_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ def self.create_update_procedure_params(params, private = false)
:piece_justificative_template,
:quartiers_prioritaires,
:cadastres,
:parcelles_agricoles,
drop_down_list_attributes: [:value, :id]
])

Expand Down
4 changes: 4 additions & 0 deletions app/views/admin/types_de_champ/_fields.html.haml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@
%label
= ff.check_box :cadastres
Cadastre
%br
%label
= ff.check_box :parcelles_agricoles
Parcelles Agricoles

- hide_mandatory = (ff.object.object.private? || type_champ == TypeDeChamp.type_champs.fetch(:explication))
.form-group.mandatory{ style: hide_mandatory ? 'visibility: hidden;' : nil }
Expand Down
14 changes: 14 additions & 0 deletions app/views/shared/champs/carte/_geo_areas.html.haml
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,17 @@
%ul
- champ.cadastres.each do |pc|
%li Parcelle n° #{pc.numero} - Feuille #{pc.code_arr} #{pc.section} #{pc.feuille}

- 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?
Aucune zone tracée
- elsif champ.parcelles_agricoles.blank?
= t('errors.messages.parcelles_agricoles_empty', count: champ.zones.size)
- else
%ul
- champ.parcelles_agricoles.each do |pa|
%li Culture : #{pa.culture} - Surface : #{pa.surface} ha
1 change: 1 addition & 0 deletions config/initializers/typhoeus.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Typhoeus::Config.user_agent = "demarches-simplifiees.fr"
1 change: 1 addition & 0 deletions config/initializers/urls.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
API_CARTO_URL = "https://apicarto.sgmap.fr"
API_ENTREPRISE_URL = "https://entreprise.api.gouv.fr/v2"
API_GEO_URL = "https://geo.api.gouv.fr"
API_GEO_SANDBOX_URL = "https://sandbox.geo.api.gouv.fr"
HELPSCOUT_API_URL = "https://api.helpscout.net/v2"
PIPEDRIVE_API_URL = "https://api.pipedrive.com/v1"

Expand Down
3 changes: 3 additions & 0 deletions config/locales/fr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,9 @@ fr:
quartiers_prioritaires_empty:
one: "Aucun quartier prioritaire sur la zone séléctionnée"
other: "Aucun quartier prioritaire sur les zones séléctionnées"
parcelles_agricoles_empty:
one: "Aucune parcelle agricole sur la zone séléctionnée"
other: "Aucune parcelle agricole sur les zones séléctionnées"

date:
abbr_day_names:
Expand Down
2 changes: 1 addition & 1 deletion spec/controllers/champs/carte_controller_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
context 'when coordinates are empty' do
let(:selection) { [] }

it { expect(response.body).to include("DS.drawMapData(\".carte-1\", {\"position\":{\"lon\":\"2.428462\",\"lat\":\"46.538192\",\"zoom\":\"13\"},\"selection\":[],\"quartiersPrioritaires\":[],\"cadastres\":[]});") }
it { expect(response.body).to include("DS.drawMapData(\".carte-1\", {\"position\":{\"lon\":\"2.428462\",\"lat\":\"46.538192\",\"zoom\":\"13\"},\"selection\":[],\"quartiersPrioritaires\":[],\"cadastres\":[],\"parcellesAgricoles\":[]});") }
end

context 'when coordinates are informed' do
Expand Down
6 changes: 6 additions & 0 deletions spec/factories/geo_area.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,11 @@
source { GeoArea.sources.fetch(:cadastre) }
numero { '42' }
feuille { 'A11' }

trait :quartier_prioritaire do
source { GeoArea.sources.fetch(:quartier_prioritaire) }
nom { 'XYZ' }
commune { 'Paris' }
end
end
end
Loading

0 comments on commit f0610c4

Please sign in to comment.