@@ -75,34 +75,39 @@ def getObservationsMaillesChilds(session, cd_ref, year_min=None, year_max=None):
7575
7676def territoryObservationsMailles (connection ):
7777 sql = """
78+ WITH obs_in_area AS (
79+ SELECT
80+ obs.id_observation,
81+ obs.cd_ref,
82+ date_part('year', obs.dateobs) AS annee
83+ FROM atlas.vm_observations obs
84+ )
7885SELECT
79- obs.id_maille,
80- obs.nbr AS obs_nbr,
81- obs.type_code,
82- area.area_geojson,
83- MAX(extract(YEAR FROM o.dateobs)) AS last_observation
84- FROM atlas.vm_observations_mailles obs
85- JOIN atlas.vm_l_areas area ON area.id_area=obs.id_maille
86- JOIN atlas.vm_observations AS o ON o.id_observation = ANY(obs.id_observations)
87- GROUP BY obs.id_maille, obs.nbr, obs.type_code, area.area_geojson
86+ json_build_object(
87+ 'type', 'FeatureCollection',
88+ 'features', json_agg(ST_AsGeoJSON(features.*)::json)
89+ ) AS observations_features
90+ FROM (
91+ SELECT
92+ COUNT(obs_in_area.id_observation) AS nb_observations,
93+ COUNT(DISTINCT obs_in_area.cd_ref) AS nb_cd_ref,
94+ json_agg(DISTINCT jsonb_build_object(
95+ 'name', (COALESCE(t.nom_vern || ' | ', '') || t.lb_nom),
96+ 'cdRef', t.cd_ref)) AS taxons,
97+ obs.type_code,
98+ obs.id_maille,
99+ vla.the_geom,
100+ MAX(obs_in_area.annee)
101+ FROM obs_in_area
102+ JOIN atlas.vm_observations_mailles obs ON obs_in_area.id_observation = ANY(obs.id_observations)
103+ JOIN atlas.vm_l_areas vla ON vla.id_area=obs.id_maille
104+ JOIN atlas.vm_taxons AS t ON t.cd_ref = obs_in_area.cd_ref
105+ GROUP BY obs.type_code, obs.id_maille, vla.the_geom) AS features
88106 """
89107
90- observations = connection .execute (text (sql ))
91- return FeatureCollection (
92- [
93- Feature (
94- id = o .id_maille ,
95- geometry = json .loads (o .area_geojson ),
96- properties = {
97- "id_maille" : o .id_maille ,
98- "type_code" : o .type_code ,
99- "nb_observations" : int (o .obs_nbr ),
100- "last_observation" : o .last_observation ,
101- },
102- )
103- for o in observations
104- ]
105- )
108+ query = connection .execute (text (sql ))
109+ return dict (query .all ()[0 ])
110+
106111
107112
108113# last observation for index.html
0 commit comments