Skip to content

Commit

Permalink
Merge pull request #208 from PnX-SI/develop
Browse files Browse the repository at this point in the history
Develop > Master / 0.4.1
  • Loading branch information
camillemonchicourt authored Feb 5, 2023
2 parents 73d6c0b + 57418f0 commit 7f3c928
Show file tree
Hide file tree
Showing 18 changed files with 529 additions and 396 deletions.
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.4.0
0.4.1.dev0
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""Correction t_observation_detail
Revision ID: e78003460441
Revises: 2003e18f248a
Create Date: 2023-01-02 16:44:18.715547
"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'e78003460441'
down_revision = '2003e18f248a'
branch_labels = None
depends_on = None


def upgrade():
op.execute("""
ALTER TABLE gn_monitoring.t_observation_details
DROP CONSTRAINT pk_t_observation_details;
ALTER TABLE gn_monitoring.t_observation_details
ADD CONSTRAINT pk_t_observation_details PRIMARY KEY (id_observation_detail);
ALTER TABLE gn_monitoring.t_observation_details
ADD uuid_observation_detail UUID DEFAULT uuid_generate_v4() NOT NULL;
""")


def downgrade():
op.execute("""
ALTER TABLE gn_monitoring.t_observation_details
DROP CONSTRAINT pk_t_observation_details;
ALTER TABLE gn_monitoring.t_observation_details
ADD CONSTRAINT pk_t_observation_details PRIMARY KEY (id_observation);
ALTER TABLE gn_monitoring.t_observation_details
DROP COLUMN uuid_observation_detail;
""")
2 changes: 1 addition & 1 deletion backend/gn_module_monitoring/monitoring/definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
'site': TMonitoringSites,
'visit': TMonitoringVisits,
'observation': TMonitoringObservations,
'detail': TMonitoringObservationDetails,
'observation_detail': TMonitoringObservationDetails,
'sites_group': TMonitoringSitesGroups
}

Expand Down
12 changes: 11 additions & 1 deletion backend/gn_module_monitoring/monitoring/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ class TMonitoringObservationDetails(DB.Model):

id_observation = DB.Column(DB.ForeignKey('gn_monitoring.t_observations.id_observation'))
data = DB.Column(JSONB)
uuid_observation_detail = DB.Column(UUID(as_uuid=True), default=uuid4)

medias = DB.relationship(
TMedias,
lazy='joined',
primaryjoin=(TMedias.uuid_attached_row == uuid_observation_detail),
foreign_keys=[TMedias.uuid_attached_row])


@serializable
Expand All @@ -58,7 +65,7 @@ class TObservations(DB.Model):
primaryjoin=(TMedias.uuid_attached_row == uuid_observation),
foreign_keys=[TMedias.uuid_attached_row])

t_observation_details = DB.relation(
observation_details = DB.relation(
TMonitoringObservationDetails,
primaryjoin=(id_observation == TMonitoringObservationDetails.id_observation),
foreign_keys=[TMonitoringObservationDetails.id_observation],
Expand All @@ -83,6 +90,9 @@ class TMonitoringObservations(TObservations):
)


TBaseVisits.dataset = DB.relationship(TDatasets)


@serializable
class TMonitoringVisits(TBaseVisits):
__tablename__ = "t_visit_complements"
Expand Down
12 changes: 4 additions & 8 deletions backend/gn_module_monitoring/monitoring/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def get_site_id(self):
return
if hasattr(self._model, 'id_base_site'):
return self._model.id_base_site
return
return
# parent = self.get_parent()
# if not parent:
# return
Expand Down Expand Up @@ -78,18 +78,14 @@ def serialize_children(self, depth):
if not hasattr(self._model, relation_name):
continue


children_of_type = []

for child_model in getattr(self._model, relation_name):
child = (
child = (
monitoring_definitions
.monitoring_object_instance(self._module_code, children_type, model=child_model)
)
children_of_type.append(child.serialize(depth))



children_of_type.append(child.serialize(depth))

children[children_type] = children_of_type

Expand All @@ -101,7 +97,7 @@ def properties_names(self):
return generic + data

def serialize(self, depth=1):
# TODO faire avec un as_dict propre (avec props et relationships)
# TODO faire avec un as_dict propre (avec props et relationships)
if depth is None:
depth = 1
depth = depth-1
Expand Down
58 changes: 33 additions & 25 deletions backend/gn_module_monitoring/routes/monitoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
json_resp, json_resp_accept_empty_list
)

from werkzeug.exceptions import NotFound

from ..blueprint import blueprint

from .decorators import check_cruved_scope_monitoring
Expand Down Expand Up @@ -199,44 +201,50 @@ def update_synthese_api(module_code):
.get()
.process_synthese(process_module=True)
)


# export add mje
# export all observations
@blueprint.route('/exports/csv/<module_code>/<type>/<method>/<jd>', methods=['GET'])
@blueprint.route('/exports/csv/<module_code>/<method>', methods=['GET'])
@check_cruved_scope_monitoring('R', 1)
def export_all_observations(module_code, type, method,jd):
def export_all_observations(module_code, method):
"""
Export all the observations made on a site group.
Following formats are available:
* csv
* geojson
* shapefile
Export all data in csv of a custom module view
:params module_code: Code of the module
:type module_code: str
:param method: Name of the view without module code prefix
:type method: str
:returns: Array of dict
"""
id_dataset = request.args.get("id_dataset", int, None)

view = GenericTableGeo(
tableName="v_export_" + module_code.lower()+"_"+method,
tableName=f"v_export_{module_code.lower()}_{method}",
schemaName="gn_monitoring",
engine=DB.engine

)
columns = view.tableDef.columns
q = DB.session.query(*columns)
#data = q.all()
#----------------------------
data = DB.session.query(*columns).filter(columns.id_dataset == jd).all()
#-------------------------------------

filename = module_code+"_"+method+"_"+dt.datetime.now().strftime("%Y_%m_%d_%Hh%Mm%S")

if type == 'csv':
return to_csv_resp(
filename,
data=serializeQuery(data, q.column_descriptions),
separator=";",
columns=[db_col.key for db_col in columns if db_col.key != 'geom'], # Exclude the geom column from CSV
)
else:
raise NotFound("type export not found")

# Filter with dataset if is set
if hasattr(columns, "id_dataset") and id_dataset:
data = q.filter(columns.id_dataset == id_dataset)
data = q.all()

timestamp = dt.datetime.now().strftime("%Y_%m_%d_%Hh%Mm%S")
filename = f"{module_code}_{method}_{timestamp}"

return to_csv_resp(
filename,
data=serializeQuery(data, q.column_descriptions),
separator=";",
columns=[
db_col.key for db_col in columns if db_col.key != 'geom'
], # Exclude the geom column from CSV
)

@blueprint.route('/exports/pdf/<module_code>/<object_type>/<int:id>', methods=['POST'])
def post_export_pdf(module_code, object_type, id):
Expand Down
4 changes: 2 additions & 2 deletions config/monitoring/generic/module.json
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@

"taxonomy_display_field_name": {
"type_widget": "datalist",
"attribut_label": "Affichage des taxon",
"attribut_label": "Affichage des taxons",
"values": [
{
"label":"Nom vernaculaire ou nom latin",
Expand All @@ -127,7 +127,7 @@
"active_frontend": {
"type_widget": "bool_checkbox",
"attribut_label": "Afficher dans le menu ?",
"definition": "Afficher le module dans le menu de GéoNature. (Recharger la page pour voir les modifications)."
"definition": "Afficher le module dans le menu de GeoNature. (Recharger la page pour voir les modifications)."
},
"medias": {
"type_widget": "medias",
Expand Down
30 changes: 30 additions & 0 deletions config/monitoring/generic/observation_detail.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"cruved": {"C":1, "U":1, "D": 1},
"id_field_name": "id_observation_detail",
"description_field_name": "id_observation_detail",
"chained": true,
"label": "Observation détail",
"genre": "F",
"display_properties": ["uuid_observation_detail"],
"uuid_field_name": "uuid_observation_detail",
"generic": {
"id_observation_detail": {
"type_widget": "text",
"attribut_label": "Id observation",
"hidden": true
},
"id_observation": {
"type_widget": "text",
"attribut_label": "Id visite",
"hidden": true
},
"uuid_observation_detail": {
"attribut_label": "uuid"
},
"medias": {
"type_widget": "medias",
"attribut_label": "Médias",
"schema_dot_table": "gn_monitoring.t_observations_details"
}
}
}
25 changes: 24 additions & 1 deletion docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,29 @@
CHANGELOG
=========

0.4.1 (2023-02-05)
------------------

**Evolutions**

* Configuration des exports pour rendre optionnelle la sélection du jeu de données avec le nouveau paramètre ``filter_dataset`` (#158)

**Corrections**

* Amélioration des performances du chargement des observations (#142)
* Correction du modèle "Observation détail" qui permet d'ajouter des informations sous le niveau observation

**⚠️ Notes de version**

Si vous souhaitez que les exports soient filtrables par jeux de données, il faut rajouter le nouveau paramètre ``filter_dataset`` dans la variable ``export_csv``, définie à ``true`` au niveau de la configuration des modules concernés (dans leur fichier ``module.json``). Exemple :

::

"export_csv": [
{ "label": "Format standard CSV", "type":"csv" , "method": "standard" , "filter_dataset": true},
{ "label": "Format analyses CSV", "type":"csv" , "method": "analyses" }
],

0.4.0 (2022-12-21)
------------------

Expand All @@ -23,7 +46,7 @@ Nécessite la version 2.11.0 (ou plus) de GeoNature.
**⚠️ Notes de version**

Si vous mettez à jour le module, il vous faut passer à Alembic.
Pour cela, une fois la version 2.11 de GeoNature installée :
Pour cela, une fois la version 2.11 (ou plus) de GeoNature installée :

* Entrer dans le virtualenv :

Expand Down
16 changes: 8 additions & 8 deletions docs/commandes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ Commandes disponibles

:Important:
Pour pouvoir lancer les commandes il faut s'assurer d'être à la racine de l'application ``GeoNature`` et que le virtualenv soit activé
``source backend/venv/bin/activate``


(``source backend/venv/bin/activate``).

=========================
Installer un module
Expand All @@ -15,12 +13,11 @@ Installer un module
geonature monitorings install <mon_chemin_absolu_vers_mon_module> <mon_module_code>
===============================
Mettre à jour la nommenclature
===============================

Ajoute ou met à jour des nomenclatures en base de données à partir du fichier `nomenclature.json` de la config du module (voir le fichier exemple `contrib/test/nomenclature.json` )
Ajoute ou met à jour des nomenclatures en base de données à partir du fichier ``nomenclature.json`` de la config du module (voir le fichier exemple ``contrib/test/nomenclature.json``)

.. code-block:: bash
Expand All @@ -29,8 +26,10 @@ Ajoute ou met à jour des nomenclatures en base de données à partir du fichier
=============================================
Mettre à jour les objets de permissions
=============================================

La mise à jour correspond pour le moment uniquement à un ajout d'objet de permission.
Les suppressions doivent être réalisées manuellement

Les suppressions doivent être réalisées manuellement.


.. code-block:: bash
Expand All @@ -41,6 +40,7 @@ Les suppressions doivent être réalisées manuellement
=========================
Supprimer un module
=========================

La suppression d'un module n'est possible qu'en cas d'absence de données associées.


Expand All @@ -53,8 +53,8 @@ La suppression d'un module n'est possible qu'en cas d'absence de données associ
Mettre à jour la synthese
=========================

Cette commande lit la vue de synchronisation liée au module et synchronise les données dans la synthèse (insertion et mise à jour uniquement)
Cette commande lit la vue de synchronisation liée au module et synchronise les données dans la synthèse (insertion et mise à jour uniquement).

.. code-block:: bash
geonature monitorings synchronize_synthese <module_code>>
geonature monitorings synchronize_synthese <module_code>>
Loading

0 comments on commit 7f3c928

Please sign in to comment.