-
Notifications
You must be signed in to change notification settings - Fork 102
/
routes.py
1729 lines (1496 loc) · 59.2 KB
/
routes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import datetime
import re
from collections import OrderedDict
from warnings import warn
from flask import (
Blueprint,
abort,
request,
Response,
current_app,
send_from_directory,
render_template,
jsonify,
g,
)
from geonature.core.gn_synthese.schemas import ReportSchema, SyntheseSchema
from geonature.core.gn_synthese.synthese_config import MANDATORY_COLUMNS
from pypnusershub.db.models import User
from pypnnomenclature.models import BibNomenclaturesTypes, TNomenclatures
from werkzeug.exceptions import Forbidden, NotFound, BadRequest, Conflict
from werkzeug.datastructures import MultiDict
from sqlalchemy import distinct, func, desc, asc, select, case, or_
from sqlalchemy.orm import joinedload, lazyload, selectinload, contains_eager
from geojson import FeatureCollection, Feature
import sqlalchemy as sa
from sqlalchemy.orm import load_only, aliased, Load, with_expression
from sqlalchemy.exc import NoResultFound
from utils_flask_sqla.generic import serializeQuery, GenericTable
from utils_flask_sqla.response import to_csv_resp, to_json_resp, json_resp
from utils_flask_sqla_geo.generic import GenericTableGeo
from geonature.utils import filemanager
from geonature.utils.env import db, DB
from geonature.utils.errors import GeonatureApiError
from geonature.utils.utilsgeometrytools import export_as_geo_file
from geonature.core.gn_meta.models import TDatasets
from geonature.core.notifications.utils import dispatch_notifications
import geonature.core.gn_synthese.module
from geonature.core.gn_synthese.models import (
BibReportsTypes,
CorAreaSynthese,
DefaultsNomenclaturesValue,
Synthese,
TSources,
VSyntheseForWebApp,
VColorAreaTaxon,
TReport,
SyntheseLogEntry,
)
from geonature.core.gn_synthese.synthese_config import MANDATORY_COLUMNS
from geonature.core.gn_synthese.utils.blurring import (
build_allowed_geom_cte,
build_blurred_precise_geom_queries,
build_synthese_obs_query,
split_blurring_precise_permissions,
)
from geonature.core.gn_synthese.utils.query_select_sqla import SyntheseQuery
from geonature.core.gn_synthese.utils.orm import is_already_joined
from geonature.core.gn_permissions import decorators as permissions
from geonature.core.gn_permissions.decorators import login_required, permissions_required
from geonature.core.gn_permissions.tools import get_scopes_by_action, get_permissions
from geonature.core.sensitivity.models import cor_sensitivity_area_type
from ref_geo.models import LAreas, BibAreasTypes
from apptax.taxonomie.models import (
Taxref,
bdc_statut_cor_text_area,
Taxref,
TaxrefBdcStatutCorTextValues,
TaxrefBdcStatutTaxon,
TaxrefBdcStatutText,
TaxrefBdcStatutType,
TaxrefBdcStatutValues,
VMTaxrefListForautocomplete,
)
routes = Blueprint("gn_synthese", __name__)
############################################
########### GET OBSERVATIONS ##############
############################################
@routes.route("/for_web", methods=["GET", "POST"])
@permissions_required("R", module_code="SYNTHESE")
def get_observations_for_web(permissions):
"""Optimized route to serve data for the frontend with all filters.
.. :quickref: Synthese; Get filtered observations
Query filtered by any filter, returning all the fields of the
view v_synthese_for_export::
properties = {
"id": r["id_synthese"],
"date_min": str(r["date_min"]),
"cd_nom": r["cd_nom"],
"nom_vern_or_lb_nom": r["nom_vern"] if r["nom_vern"] else r["lb_nom"],
"lb_nom": r["lb_nom"],
"dataset_name": r["dataset_name"],
"observers": r["observers"],
"url_source": r["url_source"],
"unique_id_sinp": r["unique_id_sinp"],
"entity_source_pk_value": r["entity_source_pk_value"],
}
geojson = json.loads(r["st_asgeojson"])
geojson["properties"] = properties
:qparam str limit: Limit number of synthese returned. Defaults to NB_MAX_OBS_MAP.
:qparam str cd_ref_parent: filtre tous les taxons enfants d'un TAXREF cd_ref.
:qparam str cd_ref: Filter by TAXREF cd_ref attribute
:qparam str taxonomy_group2_inpn: Filter by TAXREF group2_inpn attribute
:qparam str taxonomy_id_hab: Filter by TAXREF id_habitat attribute
:qparam str taxhub_attribut*: filtre générique TAXREF en fonction de l'attribut et de la valeur.
:qparam str *_red_lists: filtre générique de listes rouges. Filtre sur les valeurs. Voir config.
:qparam str *_protection_status: filtre générique de statuts (BdC Statuts). Filtre sur les types. Voir config.
:qparam str observers: Filter on observer
:qparam str id_organism: Filter on organism
:qparam str date_min: Start date
:qparam str date_max: End date
:qparam str id_acquisition_framework: *tbd*
:qparam str geoIntersection: Intersect with the geom send from the map
:qparam str period_start: *tbd*
:qparam str period_end: *tbd*
:qparam str area*: Generic filter on area
:qparam str *: Generic filter, given by colname & value
:>jsonarr array data: Array of synthese with geojson key, see above
:>jsonarr int nb_total: Number of observations
:>jsonarr bool nb_obs_limited: Is number of observations capped
"""
filters = request.json if request.is_json else {}
if type(filters) != dict:
raise BadRequest("Bad filters")
result_limit = request.args.get(
"limit", current_app.config["SYNTHESE"]["NB_MAX_OBS_MAP"], type=int
)
output_format = request.args.get("format", "ungrouped_geom")
if output_format not in ["ungrouped_geom", "grouped_geom", "grouped_geom_by_areas"]:
raise BadRequest(f"Bad format '{output_format}'")
# Get Column Frontend parameter to return only the needed columns
param_column_list = {
col["prop"]
for col in current_app.config["SYNTHESE"]["LIST_COLUMNS_FRONTEND"]
+ current_app.config["SYNTHESE"]["ADDITIONAL_COLUMNS_FRONTEND"]
}
# Init with compulsory columns
columns = []
for col in MANDATORY_COLUMNS:
columns.extend([col, getattr(VSyntheseForWebApp, col)])
if "count_min_max" in param_column_list:
count_min_max = case(
(
VSyntheseForWebApp.count_min != VSyntheseForWebApp.count_max,
func.concat(VSyntheseForWebApp.count_min, " - ", VSyntheseForWebApp.count_max),
),
(
VSyntheseForWebApp.count_min != None,
func.concat(VSyntheseForWebApp.count_min),
),
else_="",
)
columns += ["count_min_max", count_min_max]
param_column_list.remove("count_min_max")
if "nom_vern_or_lb_nom" in param_column_list:
nom_vern_or_lb_nom = func.coalesce(
func.nullif(VSyntheseForWebApp.nom_vern, ""), VSyntheseForWebApp.lb_nom
)
columns += ["nom_vern_or_lb_nom", nom_vern_or_lb_nom]
param_column_list.remove("nom_vern_or_lb_nom")
for column in param_column_list:
columns += [column, getattr(VSyntheseForWebApp, column)]
observations = func.json_build_object(*columns).label("obs_as_json")
# Need to check if there are blurring permissions so that the blurring process
# does not affect the performance if there is no blurring permissions
blurring_permissions, precise_permissions = split_blurring_precise_permissions(permissions)
if not blurring_permissions:
# No need to apply blurring => same path as before blurring feature
obs_query = (
select(observations)
.where(VSyntheseForWebApp.the_geom_4326.isnot(None))
.order_by(VSyntheseForWebApp.date_min.desc())
.limit(result_limit)
)
# Add filters to observations CTE query
synthese_query_class = SyntheseQuery(
VSyntheseForWebApp,
obs_query,
dict(filters),
)
synthese_query_class.apply_all_filters(g.current_user, permissions)
obs_query = synthese_query_class.build_query()
geojson_column = VSyntheseForWebApp.st_asgeojson
else:
# Build 2 queries that will be UNIONed
# Select size hierarchy if mesh mode is selected
select_size_hierarchy = output_format == "grouped_geom_by_areas"
blurred_geom_query, precise_geom_query = build_blurred_precise_geom_queries(
filters, select_size_hierarchy=select_size_hierarchy
)
allowed_geom_cte = build_allowed_geom_cte(
blurring_permissions=blurring_permissions,
precise_permissions=precise_permissions,
blurred_geom_query=blurred_geom_query,
precise_geom_query=precise_geom_query,
limit=result_limit,
)
obs_query = build_synthese_obs_query(
observations=observations,
allowed_geom_cte=allowed_geom_cte,
limit=result_limit,
)
geojson_column = func.st_asgeojson(allowed_geom_cte.c.geom)
if output_format == "grouped_geom_by_areas":
obs_query = obs_query.add_columns(VSyntheseForWebApp.id_synthese)
# Need to select the size_hierarchy to use is after (only if blurring permissions are found)
if blurring_permissions:
obs_query = obs_query.add_columns(
allowed_geom_cte.c.size_hierarchy.label("size_hierarchy")
)
obs_query = obs_query.cte("OBS")
agg_areas = (
select(CorAreaSynthese.id_synthese, LAreas.id_area)
.join(CorAreaSynthese, CorAreaSynthese.id_area == LAreas.id_area)
.join(BibAreasTypes, BibAreasTypes.id_type == LAreas.id_type)
.where(CorAreaSynthese.id_synthese == obs_query.c.id_synthese)
.where(
BibAreasTypes.type_code == current_app.config["SYNTHESE"]["AREA_AGGREGATION_TYPE"]
)
)
if blurring_permissions:
# Do not select cells which size_hierarchy is bigger than AREA_AGGREGATION_TYPE
# It means that we do not aggregate obs that have a blurring geometry greater in
# size than the aggregation area
agg_areas = agg_areas.where(obs_query.c.size_hierarchy <= BibAreasTypes.size_hierarchy)
agg_areas = agg_areas.lateral("agg_areas")
obs_query = (
select(func.ST_AsGeoJSON(LAreas.geom_4326).label("geojson"), obs_query.c.obs_as_json)
.select_from(
obs_query.outerjoin(
agg_areas, agg_areas.c.id_synthese == obs_query.c.id_synthese
).outerjoin(LAreas, LAreas.id_area == agg_areas.c.id_area)
)
.cte("OBSERVATIONS")
)
else:
obs_query = obs_query.add_columns(geojson_column.label("geojson")).cte("OBSERVATIONS")
if output_format == "ungrouped_geom":
query = select(obs_query.c.geojson, obs_query.c.obs_as_json)
else:
# Group geometries with main query
grouped_properties = func.json_build_object(
"observations", func.json_agg(obs_query.c.obs_as_json).label("observations")
)
query = select(obs_query.c.geojson, grouped_properties).group_by(obs_query.c.geojson)
results = DB.session.execute(query)
# Build final GeoJson
geojson_features = []
for geom_as_geojson, properties in results:
geojson_features.append(
Feature(
geometry=json.loads(geom_as_geojson) if geom_as_geojson else None,
properties=properties,
)
)
return jsonify(FeatureCollection(geojson_features))
@routes.route("/vsynthese/<id_synthese>", methods=["GET"])
@permissions_required("R", module_code="SYNTHESE")
def get_one_synthese(permissions, id_synthese):
"""Get one synthese record for web app with all decoded nomenclature"""
synthese_query = Synthese.join_nomenclatures().options(
joinedload("dataset").options(
selectinload("acquisition_framework").options(
joinedload("creator"),
joinedload("nomenclature_territorial_level"),
joinedload("nomenclature_financing_type"),
),
),
# Used to check the sensitivity after
joinedload("nomenclature_sensitivity"),
)
##################
fields = [
"dataset",
"dataset.acquisition_framework",
"dataset.acquisition_framework.bibliographical_references",
"dataset.acquisition_framework.cor_af_actor",
"dataset.acquisition_framework.cor_objectifs",
"dataset.acquisition_framework.cor_territories",
"dataset.acquisition_framework.cor_volets_sinp",
"dataset.acquisition_framework.creator",
"dataset.acquisition_framework.nomenclature_territorial_level",
"dataset.acquisition_framework.nomenclature_financing_type",
"dataset.cor_dataset_actor",
"dataset.cor_dataset_actor.role",
"dataset.cor_dataset_actor.organism",
"dataset.cor_territories",
"dataset.nomenclature_source_status",
"dataset.nomenclature_resource_type",
"dataset.nomenclature_dataset_objectif",
"dataset.nomenclature_data_type",
"dataset.nomenclature_data_origin",
"dataset.nomenclature_collecting_method",
"dataset.creator",
"dataset.modules",
"validations",
"validations.validation_label",
"validations.validator_role",
"cor_observers",
"cor_observers.organisme",
"source",
"habitat",
"medias",
"areas",
"areas.area_type",
]
# get reports info only if activated by admin config
if "SYNTHESE" in current_app.config["SYNTHESE"]["ALERT_MODULES"]:
fields.append("reports.report_type.type")
synthese_query = synthese_query.options(
lazyload(Synthese.reports).joinedload(TReport.report_type)
)
try:
synthese = (
db.session.execute(synthese_query.filter_by(id_synthese=id_synthese))
.unique()
.scalar_one()
)
except NoResultFound:
raise NotFound()
if not synthese.has_instance_permission(permissions=permissions):
raise Forbidden()
_, precise_permissions = split_blurring_precise_permissions(permissions)
# If blurring permissions and obs sensitive.
if (
not synthese.has_instance_permission(precise_permissions)
and synthese.nomenclature_sensitivity.cd_nomenclature != "0"
):
# Use a cte to have the areas associated with the current id_synthese
cte = select(CorAreaSynthese).where(CorAreaSynthese.id_synthese == id_synthese).cte()
# Blurred area of the observation
BlurredObsArea = aliased(LAreas)
# Blurred area type of the observation
BlurredObsAreaType = aliased(BibAreasTypes)
# Types "larger" or equal in area hierarchy size that the blurred area type
BlurredAreaTypes = aliased(BibAreasTypes)
# Areas associates with the BlurredAreaTypes
BlurredAreas = aliased(LAreas)
# Inner join that retrieve the blurred area of the obs and the bigger areas
# used for "Zonages" in Synthese. Need to have size_hierarchy from ref_geo
inner = (
sa.join(CorAreaSynthese, BlurredObsArea)
.join(BlurredObsAreaType)
.join(
cor_sensitivity_area_type,
cor_sensitivity_area_type.c.id_area_type == BlurredObsAreaType.id_type,
)
.join(
BlurredAreaTypes,
BlurredAreaTypes.size_hierarchy >= BlurredObsAreaType.size_hierarchy,
)
.join(BlurredAreas, BlurredAreaTypes.id_type == BlurredAreas.id_type)
.join(cte, cte.c.id_area == BlurredAreas.id_area)
)
# Outer join to join CorAreaSynthese taking into account the sensitivity
outer = (
inner,
sa.and_(
Synthese.id_synthese == CorAreaSynthese.id_synthese,
Synthese.id_nomenclature_sensitivity
== cor_sensitivity_area_type.c.id_nomenclature_sensitivity,
),
)
synthese_query = (
synthese_query.outerjoin(*outer)
# contains_eager: to populate Synthese.areas directly
.options(contains_eager(Synthese.areas.of_type(BlurredAreas)))
.options(
with_expression(
Synthese.the_geom_authorized,
func.coalesce(BlurredObsArea.geom_4326, Synthese.the_geom_4326),
)
)
.order_by(BlurredAreaTypes.size_hierarchy)
)
else:
synthese_query = synthese_query.options(
lazyload("areas").options(
joinedload("area_type"),
),
with_expression(Synthese.the_geom_authorized, Synthese.the_geom_4326),
)
synthese = (
db.session.execute(synthese_query.filter(Synthese.id_synthese == id_synthese))
.unique()
.scalar_one()
)
synthese_schema = SyntheseSchema(
only=Synthese.nomenclature_fields + fields,
exclude=["areas.geom"],
as_geojson=True,
feature_geometry="the_geom_authorized",
)
return synthese_schema.dump(synthese)
################################
########### EXPORTS ############
################################
@routes.route("/export_taxons", methods=["POST"])
@permissions_required("E", module_code="SYNTHESE")
def export_taxon_web(permissions):
"""Optimized route for taxon web export.
.. :quickref: Synthese;
This view is customisable by the administrator
Some columns are mandatory: cd_ref
POST parameters: Use a list of cd_ref (in POST parameters)
to filter the v_synthese_taxon_for_export_view
:query str export_format: str<'csv'>
"""
taxon_view = GenericTable(
tableName="v_synthese_taxon_for_export_view",
schemaName="gn_synthese",
engine=DB.engine,
)
columns = taxon_view.tableDef.columns
# Test de conformité de la vue v_synthese_for_export_view
try:
assert hasattr(taxon_view.tableDef.columns, "cd_ref")
except AssertionError as e:
return (
{
"msg": """
View v_synthese_taxon_for_export_view
must have a cd_ref column \n
trace: {}
""".format(
str(e)
)
},
500,
)
id_list = request.get_json()
sub_query = (
select(
VSyntheseForWebApp.cd_ref,
func.count(distinct(VSyntheseForWebApp.id_synthese)).label("nb_obs"),
func.min(VSyntheseForWebApp.date_min).label("date_min"),
func.max(VSyntheseForWebApp.date_max).label("date_max"),
)
.where(VSyntheseForWebApp.id_synthese.in_(id_list))
.group_by(VSyntheseForWebApp.cd_ref)
)
synthese_query_class = SyntheseQuery(
VSyntheseForWebApp,
sub_query,
{},
)
synthese_query_class.filter_query_all_filters(g.current_user, permissions)
subq = synthese_query_class.query.alias("subq")
query = select(*columns, subq.c.nb_obs, subq.c.date_min, subq.c.date_max).join(
subq, subq.c.cd_ref == columns.cd_ref
)
return to_csv_resp(
datetime.datetime.now().strftime("%Y_%m_%d_%Hh%Mm%S"),
data=serializeQuery(db.session.execute(query).all(), query.column_descriptions),
separator=";",
columns=[db_col.key for db_col in columns] + ["nb_obs", "date_min", "date_max"],
)
@routes.route("/export_observations", methods=["POST"])
@permissions_required("E", module_code="SYNTHESE")
def export_observations_web(permissions):
"""Optimized route for observations web export.
.. :quickref: Synthese;
This view is customisable by the administrator
Some columns are mandatory: id_synthese, geojson and geojson_local to generate the exported files
POST parameters: Use a list of id_synthese (in POST parameters) to filter the v_synthese_for_export_view
:query str export_format: str<'csv', 'geojson', 'shapefiles', 'gpkg'>
:query str export_format: str<'csv', 'geojson', 'shapefiles', 'gpkg'>
"""
params = request.args
# set default to csv
export_format = params.get("export_format", "csv")
view_name_param = params.get("view_name", "gn_synthese.v_synthese_for_export")
# Test export_format
if export_format not in current_app.config["SYNTHESE"]["EXPORT_FORMAT"]:
raise BadRequest("Unsupported format")
config_view = {
"view_name": "gn_synthese.v_synthese_for_web_app",
"geojson_4326_field": "geojson_4326",
"geojson_local_field": "geojson_local",
}
# Test export view name is config params for security reason
if view_name_param != "gn_synthese.v_synthese_for_export":
try:
config_view = next(
_view
for _view in current_app.config["SYNTHESE"]["EXPORT_OBSERVATIONS_CUSTOM_VIEWS"]
if _view["view_name"] == view_name_param
)
except StopIteration:
raise Forbidden("This view is not available for export")
geojson_4326_field = config_view["geojson_4326_field"]
geojson_local_field = config_view["geojson_local_field"]
try:
schema_name, view_name = view_name_param.split(".")
except ValueError:
raise BadRequest("view_name parameter must be a string with schema dot view_name")
# get list of id synthese from POST
id_list = request.get_json()
# Get the SRID for the export
local_srid = DB.session.execute(
func.Find_SRID("gn_synthese", "synthese", "the_geom_local")
).scalar()
blurring_permissions, precise_permissions = split_blurring_precise_permissions(permissions)
# Get the view for export
# Useful to have geom column so that they can be replaced by blurred geoms
# (only if the user has sensitive permissions)
export_view = GenericTableGeo(
tableName=view_name,
schemaName=schema_name,
engine=DB.engine,
geometry_field=None,
srid=local_srid,
)
mandatory_columns = {"id_synthese", geojson_4326_field, geojson_local_field}
if not mandatory_columns.issubset(set(map(lambda col: col.name, export_view.db_cols))):
print(set(map(lambda col: col.name, export_view.db_cols)))
raise BadRequest(
f"The view {view_name} miss one of required columns {str(mandatory_columns)}"
)
# If there is no sensitive permissions => same path as before blurring implementation
if not blurring_permissions:
# Get the CTE for synthese filtered by user permissions
synthese_query_class = SyntheseQuery(
Synthese,
select(Synthese.id_synthese),
{},
)
synthese_query_class.filter_query_all_filters(g.current_user, permissions)
cte_synthese_filtered = synthese_query_class.build_query().cte("cte_synthese_filtered")
selectable_columns = [export_view.tableDef]
else:
# Use slightly the same process as for get_observations_for_web()
# Add a where_clause to filter the id_synthese provided to reduce the
# UNION queries
where_clauses = [Synthese.id_synthese.in_(id_list)]
blurred_geom_query, precise_geom_query = build_blurred_precise_geom_queries(
filters={}, where_clauses=where_clauses
)
cte_synthese_filtered = build_allowed_geom_cte(
blurring_permissions=blurring_permissions,
precise_permissions=precise_permissions,
blurred_geom_query=blurred_geom_query,
precise_geom_query=precise_geom_query,
limit=current_app.config["SYNTHESE"]["NB_MAX_OBS_EXPORT"],
)
# Overwrite geometry columns to compute the blurred geometry from the blurring cte
columns_with_geom_excluded = [
col
for col in export_view.tableDef.columns
if col.name
not in [
"geometrie_wkt_4326", # FIXME: hardcoded column names?
"x_centroid_4326",
"y_centroid_4326",
geojson_4326_field,
geojson_local_field,
]
]
# Recomputed the blurred geometries
blurred_geom_columns = [
func.st_astext(cte_synthese_filtered.c.geom).label("geometrie_wkt_4326"),
func.st_x(func.st_centroid(cte_synthese_filtered.c.geom)).label("x_centroid_4326"),
func.st_y(func.st_centroid(cte_synthese_filtered.c.geom)).label("y_centroid_4326"),
func.st_asgeojson(cte_synthese_filtered.c.geom).label(geojson_4326_field),
func.st_asgeojson(func.st_transform(cte_synthese_filtered.c.geom, local_srid)).label(
geojson_local_field
),
]
# Finally provide all the columns to be selected in the export query
selectable_columns = columns_with_geom_excluded + blurred_geom_columns
# Get the query for export
export_query = (
select(*selectable_columns)
.select_from(
export_view.tableDef.join(
cte_synthese_filtered,
cte_synthese_filtered.c.id_synthese == export_view.tableDef.columns["id_synthese"],
)
)
.where(export_view.tableDef.columns["id_synthese"].in_(id_list))
)
# Get the results for export
results = DB.session.execute(
export_query.limit(current_app.config["SYNTHESE"]["NB_MAX_OBS_EXPORT"])
)
db_cols_for_shape = []
columns_to_serialize = []
# loop over synthese config to exclude columns if its default export
for db_col in export_view.db_cols:
if view_name_param == "gn_synthese.v_synthese_for_export":
if db_col.key in current_app.config["SYNTHESE"]["EXPORT_COLUMNS"]:
db_cols_for_shape.append(db_col)
columns_to_serialize.append(db_col.key)
else:
# remove geojson fields of serialization
if db_col.key not in [geojson_4326_field, geojson_local_field]:
db_cols_for_shape.append(db_col)
columns_to_serialize.append(db_col.key)
file_name = datetime.datetime.now().strftime("%Y_%m_%d_%Hh%Mm%S")
file_name = filemanager.removeDisallowedFilenameChars(file_name)
if export_format == "csv":
formated_data = [export_view.as_dict(d, fields=columns_to_serialize) for d in results]
return to_csv_resp(file_name, formated_data, separator=";", columns=columns_to_serialize)
elif export_format == "geojson":
features = []
for r in results:
geometry = json.loads(getattr(r, geojson_4326_field))
feature = Feature(
geometry=geometry,
properties=export_view.as_dict(r, fields=columns_to_serialize),
)
features.append(feature)
results = FeatureCollection(features)
return to_json_resp(results, as_file=True, filename=file_name, indent=4)
else:
try:
dir_name, file_name = export_as_geo_file(
export_format=export_format,
export_view=export_view,
db_cols=db_cols_for_shape,
geojson_col=geojson_local_field,
data=results,
file_name=file_name,
)
return send_from_directory(dir_name, file_name, as_attachment=True)
except GeonatureApiError as e:
message = str(e)
return render_template(
"error.html",
error=message,
redirect=current_app.config["URL_APPLICATION"] + "/#/synthese",
)
# TODO: Change the following line to set method as "POST" only ?
@routes.route("/export_metadata", methods=["GET", "POST"])
@permissions_required("E", module_code="SYNTHESE")
def export_metadata(permissions):
"""Route to export the metadata in CSV
.. :quickref: Synthese;
The table synthese is join with gn_synthese.v_metadata_for_export
The column jdd_id is mandatory in the view gn_synthese.v_metadata_for_export
TODO: Remove the following comment line ? or add the where clause for id_synthese in id_list ?
POST parameters: Use a list of id_synthese (in POST parameters) to filter the v_synthese_for_export_view
"""
filters = request.json if request.is_json else {}
metadata_view = GenericTable(
tableName="v_metadata_for_export",
schemaName="gn_synthese",
engine=DB.engine,
)
# Test de conformité de la vue v_metadata_for_export
try:
assert hasattr(metadata_view.tableDef.columns, "jdd_id")
except AssertionError as e:
return (
{
"msg": """
View v_metadata_for_export
must have a jdd_id column \n
trace: {}
""".format(
str(e)
)
},
500,
)
q = select(distinct(VSyntheseForWebApp.id_dataset), metadata_view.tableDef)
synthese_query_class = SyntheseQuery(
VSyntheseForWebApp,
q,
filters,
)
synthese_query_class.add_join(
metadata_view.tableDef,
getattr(
metadata_view.tableDef.columns,
current_app.config["SYNTHESE"]["EXPORT_METADATA_ID_DATASET_COL"],
),
VSyntheseForWebApp.id_dataset,
)
# Filter query with permissions (scope, sensitivity, ...)
synthese_query_class.filter_query_all_filters(g.current_user, permissions)
data = DB.session.execute(synthese_query_class.query)
# Define the header of the csv file
columns = [db_col.key for db_col in metadata_view.tableDef.columns]
columns[columns.index("nombre_obs")] = "nombre_total_obs"
# Retrieve the data to write in the csv file
data = [metadata_view.as_dict(d) for d in data]
for d in data:
d["nombre_total_obs"] = d.pop("nombre_obs")
return to_csv_resp(
datetime.datetime.now().strftime("%Y_%m_%d_%Hh%Mm%S"),
data=data,
separator=";",
columns=columns,
)
@routes.route("/export_statuts", methods=["POST"])
@permissions_required("E", module_code="SYNTHESE")
def export_status(permissions):
"""Route to get all the protection status of a synthese search
.. :quickref: Synthese;
Get the CRUVED from 'R' action because we don't give observations X/Y but only statuts
and to be consistent with the data displayed in the web interface.
Parameters:
- HTTP-GET: the same that the /synthese endpoint (all the filter in web app)
"""
filters = request.json if request.is_json else {}
# Initalize the select object
query = select(
distinct(VSyntheseForWebApp.cd_nom).label("cd_nom"),
Taxref.cd_ref,
Taxref.nom_complet,
Taxref.nom_vern,
TaxrefBdcStatutTaxon.rq_statut,
TaxrefBdcStatutType.regroupement_type,
TaxrefBdcStatutType.lb_type_statut,
TaxrefBdcStatutText.cd_sig,
TaxrefBdcStatutText.full_citation,
TaxrefBdcStatutText.doc_url,
TaxrefBdcStatutValues.code_statut,
TaxrefBdcStatutValues.label_statut,
)
# Initialize SyntheseQuery class
synthese_query = SyntheseQuery(VSyntheseForWebApp, query, filters)
# Filter query with permissions
synthese_query.filter_query_all_filters(g.current_user, permissions)
# Add join
synthese_query.add_join(Taxref, Taxref.cd_nom, VSyntheseForWebApp.cd_nom)
synthese_query.add_join(
CorAreaSynthese,
CorAreaSynthese.id_synthese,
VSyntheseForWebApp.id_synthese,
)
synthese_query.add_join(
bdc_statut_cor_text_area, bdc_statut_cor_text_area.c.id_area, CorAreaSynthese.id_area
)
synthese_query.add_join(TaxrefBdcStatutTaxon, TaxrefBdcStatutTaxon.cd_ref, Taxref.cd_ref)
synthese_query.add_join(
TaxrefBdcStatutCorTextValues,
TaxrefBdcStatutCorTextValues.id_value_text,
TaxrefBdcStatutTaxon.id_value_text,
)
synthese_query.add_join_multiple_cond(
TaxrefBdcStatutText,
[
TaxrefBdcStatutText.id_text == TaxrefBdcStatutCorTextValues.id_text,
TaxrefBdcStatutText.id_text == bdc_statut_cor_text_area.c.id_text,
],
)
synthese_query.add_join(
TaxrefBdcStatutType,
TaxrefBdcStatutType.cd_type_statut,
TaxrefBdcStatutText.cd_type_statut,
)
synthese_query.add_join(
TaxrefBdcStatutValues,
TaxrefBdcStatutValues.id_value,
TaxrefBdcStatutCorTextValues.id_value,
)
# Build query
query = synthese_query.build_query()
# Set enable status texts filter
query = query.where(TaxrefBdcStatutText.enable == True)
protection_status = []
data = DB.session.execute(query)
for d in data:
d = d._mapping
row = OrderedDict(
[
("cd_nom", d["cd_nom"]),
("cd_ref", d["cd_ref"]),
("nom_complet", d["nom_complet"]),
("nom_vern", d["nom_vern"]),
("type_regroupement", d["regroupement_type"]),
("type", d["lb_type_statut"]),
("territoire_application", d["cd_sig"]),
("intitule_doc", re.sub("<[^<]+?>", "", d["full_citation"])),
("code_statut", d["code_statut"]),
("intitule_statut", d["label_statut"]),
("remarque", d["rq_statut"]),
("url_doc", d["doc_url"]),
]
)
protection_status.append(row)
export_columns = [
"nom_complet",
"nom_vern",
"cd_nom",
"cd_ref",
"type_regroupement",
"type",
"territoire_application",
"intitule_doc",
"code_statut",
"intitule_statut",
"remarque",
"url_doc",
]
return to_csv_resp(
datetime.datetime.now().strftime("%Y_%m_%d_%Hh%Mm%S"),
protection_status,
separator=";",
columns=export_columns,
)
######################################
########### OTHERS ROUTES ############
######################################
@routes.route("/general_stats", methods=["GET"])
@permissions_required("R", module_code="SYNTHESE")
@json_resp
def general_stats(permissions):
"""Return stats about synthese.
.. :quickref: Synthese;
- nb of observations
- nb of distinct species
- nb of distinct observer
- nb of datasets
"""
nb_allowed_datasets = db.session.scalar(
select(func.count("*"))
.select_from(TDatasets)
.where(TDatasets.filter_by_readable().whereclause)
)
query = select(
func.count(Synthese.id_synthese),
func.count(func.distinct(Synthese.cd_nom)),
func.count(func.distinct(Synthese.observers)),
)
synthese_query_obj = SyntheseQuery(Synthese, query, {})
synthese_query_obj.filter_query_with_cruved(g.current_user, permissions)
result = DB.session.execute(synthese_query_obj.query)
synthese_counts = result.fetchone()
data = {
"nb_data": synthese_counts[0],
"nb_species": synthese_counts[1],
"nb_observers": synthese_counts[2],
"nb_dataset": nb_allowed_datasets,
}
return data
@routes.route("/taxon_stats/<int:cd_ref>", methods=["GET"])
@permissions.check_cruved_scope("R", get_scope=True, module_code="SYNTHESE")
@json_resp
def taxon_stats(scope, cd_ref):
"""Return stats for a specific taxon"""
area_type = request.args.get("area_type")
if not area_type:
raise BadRequest("Missing area_type parameter")
# Ensure area_type is valid
valid_area_types = (
db.session.query(BibAreasTypes.type_code)
.distinct()
.filter(BibAreasTypes.type_code == area_type)
.scalar()
)
if not valid_area_types:
raise BadRequest("Invalid area_type")
# Subquery to fetch areas based on area_type
areas_subquery = (
select([LAreas.id_area])
.where(LAreas.id_type == BibAreasTypes.id_type)
.where(BibAreasTypes.type_code == area_type)
.alias("areas")
)
taxref_cd_nom_list = db.session.scalars(select(Taxref.cd_nom).where(Taxref.cd_ref == cd_ref))
# Main query to fetch stats
query = (
select(
[
func.count(distinct(Synthese.id_synthese)).label("observation_count"),
func.count(distinct(Synthese.observers)).label("observer_count"),
func.count(distinct(areas_subquery.c.id_area)).label("area_count"),
func.min(Synthese.altitude_min).label("altitude_min"),
func.max(Synthese.altitude_max).label("altitude_max"),