Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SUIVI-EOLIEN] Séparation des groupes de sites et sites (db + api), style page d'accueil #204

Conversation

mvergez
Copy link

@mvergez mvergez commented Jan 13, 2023

Bonjour,

Dans le cadre d'une prestation pour l'UMS Patrinat, il est souhaité de partager les groupes de sites (parcs éoliens) et les sites (éoliennes/gîtes) entre les protocoles.

Objectifs de la PR

Général

Cette PR est la première d'un travail de refactoring tant en base de données, en backend et en frontend afin d'isoler les groupes de sites et les sites. Ceci, afin de proposer à l'utilisateur 2 entrées depuis l'accueil : l'entrée par sites et par protocole.
Nous avons acté cette isolation afin de préparer un éventuel rappatriement de ces notions de groupes de sites et sites dans GeoNature.

Technique

Le but était d'appliquer le modèle en base de données décidé dans l'issue #117. Pour résumer :

  • Ajout de la notion de types de sites (bib_type_site) étant consitutée d'un id_nomenclature et d'une config (qui accueillera un json au format Monitoring).
  • Lien Many To Many entre t_base_sites et bib_type_site.
  • Lien Many To Many entre t_modules et bib_type_site afin de filtrer les types de site "compatibles" avec le module.
  • Suppression d'id_module dans t_sites_complements pour supprimer le lien entre les modules et les sites directement (le lien s'effectue via les types) et pour supprimer progressivement t_sites_complements (autre PR à venir).
  • Suppression d'id_module dans t_sites_groups pour supprimer le lien entre les modules et les groupes de sites (le lien s'effectue via les sites).

Cela a mené aux développements suivants :

  • Ajout de migrations alembic.
  • Ajout d'un TRIGGER sur bib_type_site pour s'assurer que l'id_nomenclature insérée est bien de type TYPE_SITE.
  • Modification des modèles sqlalchemy pour correspondre aux migrations alembic.
  • Ajout d'une nouvelle section dans le module admin de GeoNature afin de gérer les types de sites :
    • Chaque type possède un id qui est en réalité l'id_nomenclature directement. Donc chaque type doit être unique, car il n'existe pas de moyen de les distinguer si ce n'est la config.
    • Une vérification d'unicité est effectuée dans le module d'admin pour ne pas déclencher d'erreur en base de données à l'insertion.
    • Si le type de site n'existe pas dans les nomenclatures, il faut alors créer d'abord la nomenclature associée.
  • Ajout d'une option dans "Editer le module" afin de lier le module aux types de site dont il est compatible (permet de filtrer les sites qui seront affichés au niveau du module).
  • Ajout d'une option en backend pour paramétrer le titre et la description du module en frontend au niveau de la page d'accueil. Une réorganisation de cette dernière a dû être nécessaire.
  • Ajout de routes en backend pour récupérer les groupes de sites, les sites ainsi que les types.
  • Optimisation de la requête listant les modules (effectuée depuis la page d'accueil) lorsqu'un grand nombre de jeux de données est présent en base de données.
  • Ajout de schémas marchmallow pour gérer la sérialisation.
  • Ajout d'utilitaires de pagination et d'une query_class pour trier et filtrer.
  • Ajout de tests pour tester les fonctionnalités implémentées.

La suite (ce qui sera fait dans d'autres PR)

  • Ouverture d'une PR sur GeoNature pour supprimer la colonne id_nomenclature_type_site de t_base_sites, qui n'a plus lieu d'être grâce aux types de sites implémentés ici.
  • Ouverture d'une PR sur GeoNature pour ajouter la colonne id_sites_group dans t_base_sites pour lier un site à un groupe de sites.
  • Ouverture d'une PR sur GeoNature pour ajouter la colonne data dans t_base_sites.
  • Créer une migration pour supprimer la table t_site_complements qui n'aura donc plus lieu d'être.

Pour compléter la PR (ce qui ne sera pas fait)

  • Consolider les downgrades et upgrades de certaines migrations pour assurer la migration des données.
  • Ajouter la CI github pour exécuter automatiquement les tests

Avec @andriacap et l'aide précieuse d'@amandine-sahl et de @camillemonchicourt

Maxime Vergez and others added 22 commits January 10, 2023 16:10
commit 70b0139
Author: Maxime Vergez <[email protected]>
Date:   Tue Dec 6 15:22:56 2022 +0100

    style: apply black

commit 2badedf
Author: Maxime Vergez <[email protected]>
Date:   Tue Dec 6 15:11:41 2022 +0100

    chore(db): removed unused import

commit 57d9b52
Author: Maxime Vergez <[email protected]>
Date:   Tue Dec 6 14:47:48 2022 +0100

    feat(db): improved & finished downgrade func

commit 211780f
Author: Maxime Vergez <[email protected]>
Date:   Tue Dec 6 09:32:12 2022 +0100

    feat(db): wip: add upgrade and began downgrade

    Downgrade migration need a little bit more work due to the use of
    sql alchemy and not plain text sql

commit 0b5a3b8
Author: Maxime Vergez <[email protected]>
Date:   Mon Dec 5 11:40:32 2022 +0100

    feat: packaged module
Squashed commit of the following:

commit 2bdc22a
Author: Maxime Vergez <[email protected]>
Date:   Fri Dec 9 14:59:31 2022 +0100

    chore: changed json_schema into config

commit 4279389
Author: Maxime Vergez <[email protected]>
Date:   Tue Dec 6 18:37:41 2022 +0100

    feat(db): add foreign key from site to cat

    From t_base_sites to bib_categorie_site

commit 5cb5dfa
Author: Maxime Vergez <[email protected]>
Date:   Tue Dec 6 16:47:27 2022 +0100

    feat(api): add admin interface

commit 559a0ec
Author: Maxime Vergez <[email protected]>
Date:   Tue Dec 6 16:46:27 2022 +0100

    feat(db): add bib_categorie_site table

    Add migration and model
…t description #2 (#15)

* feat: [6.2] Page d'accueil modul monitoring layout et config title et description #2

* chore(config): applied black & removed imports
* feat(api): wip began add site routes + tests

With site categories
Also add tests

* feat(api): add more routes

* test(api): add tests and fixtures

* style(api): applied black

* feat(db): add migration to remove id_module

Column in t_sites_groups

* refactor(api): move utils for routes from sites

* feat(api): wip: add sites groups route

* test(api): wip: begin adding fixture site_groups

* fix: remove id_module in all models

* chore: rename route for better consistency

* tests: moved site_groups in tests and add tests

* chore(api): applied black

* refactor(api): add filter params function

And refact routes to use it
* feat(api): add association table with alembic

Add model in backend and alembic migration

Reviewed-by: andriac
[Refs ticket]: #3

* test: WIP add test to see new relationship

Adding test to see if categories are showing up when we call module

Reviewed-by: andriacap
[Refs ticket]: #3

* feat: add type site - categorie relation

WIP - add selectfield to get type site in admin module

Reviewed-by: andriac
[Refs ticket]: #3

* feat(api): Flask admin and routes categories

Clean code for change label list and form selectfield for
the BibCategorieView in Flask Admin

Add utils routes to get all subtable relationship in order to
get back the label type site

Review-by: andriac
[Refs ticket]: #3

* refactor: remove paginate_nested

For depth in as_dict()

* test: fix tests due to as_dict depth

* style: applied black and isort

* chore: remove unused import

Co-authored-by: Andria Capai <[email protected]>
* tests: make tests and fixtures work for modules

By changing the way a monitoring module is created in the fixture
Add two tests to check the relationship

* feat(api): add categories in edit module

* style: applied black
Need to set the current working directory of pytest the directory
where the gn_monitoring_module repo is (so with the frontend etc.)
clean: Merge la PR move test_route 
Co-authored-by: Andria Capai <[email protected]>
* feat(api): remove id_module from sites_complements

Co-authored-by: andriacap <[email protected]>

* feat(api): create schema for sites_groups

* test: add sites_group to site fixture

* test: wip add test for sites_groups schemas

* chore(api): remove depth parameter from paginate

* test: updated to work with sites_group schema

* feat: categorie site with marshmallow

Test and marshmallow create/refactor to
adapt for bibcategorie site paginate

WIP : Adapt load_only site_type in test to "assert"
same object when initiate BibCategorieSite

[Refs ticket]: #3

* feat(api): route /sites/categories/id with schema

Changing the route to return a dump Marshmallow schema
BibCategorieSitesSchema

Reviewed-by: andriac
[Refs ticket]: #3

* test(api): routes get categoires label

Change the "as_dict" by schema.dump in order
to use the Marshmallow schema created

Reviewed-by: andriac
[Refs ticket]: #3

* feat(api): Sites: cols to geoserializable + schema

* style(api): applied black

* test(api): add test for Site Schema

* style(api): applied black to test_site

* refactor(api): instantiate schema once

Instead of for each all() iteration

* chore(api): remove useless comments

* chore(api): remove useless comments and imports

Co-authored-by: andriacap <[email protected]>
Co-authored-by: Andria Capai <[email protected]>
To replace it with a bib nomenclature type: TYPE_SITE
* fix(api): add int conversion for limit/offset

* test(api): add test for get_limit_offset

* fix(api): max_per_page => per_page & test

* test(api): update test with changes on schema

Since marshmallow schemas, the json returned by pagination has
changed for items and not sites
* feat(api): add Query Class to sites, grps & cats

* feat(api): add sort and fix _get_model

Via _get_entity

* test(api): test sort query

* feat(api): add api sort/sort_dir params

To be able to sort through REST Api

* fix(api): check if integer to avoid using ilike

In filter_by_params

* test(api): add test to check filter integer
* Merged feat/package-module-alembic

commit 70b0139
Author: Maxime Vergez <[email protected]>
Date:   Tue Dec 6 15:22:56 2022 +0100

    style: apply black

commit 2badedf
Author: Maxime Vergez <[email protected]>
Date:   Tue Dec 6 15:11:41 2022 +0100

    chore(db): removed unused import

commit 57d9b52
Author: Maxime Vergez <[email protected]>
Date:   Tue Dec 6 14:47:48 2022 +0100

    feat(db): improved & finished downgrade func

commit 211780f
Author: Maxime Vergez <[email protected]>
Date:   Tue Dec 6 09:32:12 2022 +0100

    feat(db): wip: add upgrade and began downgrade

    Downgrade migration need a little bit more work due to the use of
    sql alchemy and not plain text sql

commit 0b5a3b8
Author: Maxime Vergez <[email protected]>
Date:   Mon Dec 5 11:40:32 2022 +0100

    feat: packaged module

* Feat/edit categories module (#19)

* tests: make tests and fixtures work for modules

By changing the way a monitoring module is created in the fixture
Add two tests to check the relationship

* feat(api): add categories in edit module

* style: applied black

* fix(config): changed categories into items

Following the change with marshmallow schemas
* feat(db): upgrade down_revision following rebase

Since rebase with develop: changed the down_revision number

* fix(db): fix bind params enabling downgrade

Beforehand the downgrade was not possible...

* refactor(db): removed cor_site_type_category

* refactor(db): changed category into type in cor

* refactor(db): create cor_type_site

* fix(db): renamed column

* refactor(api): update models to fit migrations

* fix(db):change bib_categorie_site to bib_type_site

Adding :
cor_site_module
cor_site_type
revision alembic to create function and trigger in order to add
bib_type_site but only with nomenclature 'TYPE_SITE'
upgrade and downgrade works

[Refs ticket]: #3
Reviewed-by: andriac

* fix(api): updated models from migrations

* fix(api): wip: fix admin following migrations

* fix(api): update routes and tests

To match migration changes

* feat: flask admin bib_type_site

Change bib_categories to bib_type_site into flask admin
Adding filtering in list label_fr of type_site to secure the unique
constraint

Reviewed-by: andriac
[Refs ticket]: #3

* fix(api): updated schema to match models

* fix(api): module edition

* style(api): uniformize type_site

* style(api): change relationship name for type_site

* feat(api): validator admin

* fix(api): make unique BibTypeSite in admin

* test(api): fix test when existing nomenclatures

In database

Co-authored-by: Andria Capai <[email protected]>
* Merged feat/package-module-alembic

commit 70b0139
Author: Maxime Vergez <[email protected]>
Date:   Tue Dec 6 15:22:56 2022 +0100

    style: apply black

commit 2badedf
Author: Maxime Vergez <[email protected]>
Date:   Tue Dec 6 15:11:41 2022 +0100

    chore(db): removed unused import

commit 57d9b52
Author: Maxime Vergez <[email protected]>
Date:   Tue Dec 6 14:47:48 2022 +0100

    feat(db): improved & finished downgrade func

commit 211780f
Author: Maxime Vergez <[email protected]>
Date:   Tue Dec 6 09:32:12 2022 +0100

    feat(db): wip: add upgrade and began downgrade

    Downgrade migration need a little bit more work due to the use of
    sql alchemy and not plain text sql

commit 0b5a3b8
Author: Maxime Vergez <[email protected]>
Date:   Mon Dec 5 11:40:32 2022 +0100

    feat: packaged module

* perf(api): improved loading of modules

When there are loads of datasets, the relationship takes a lot of
time to load, and is useless for the route that uses it.

* fix: due to wrong rebase

Fix: newline on data_utils.py
Fix: relationships are not joined anymore since there is no need of
them
Chore: update comment
* fix(api): page - 1 that returned the wrong page

* test(api): add test for paginate
* fix(db): change trigger to constraint (migrations)

Delete the trigger and create check constraint on id_nomenclature column

Reviewed-by: andriacap
[Refs ticket]: #3

* fix(db) : apply black on migration file

Apply black
[Refs_ticket]: #3
So that it will fallback to == most of the time and ilike when
just Unicode
Cannot use alembic to do this because need sqlalchemy >= 1.4.32
f"gn_commons.t_modules.id_module",
name="fk_t_site_complements_id_module",
ondelete="CASCADE",
onupdate="CASCADE",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dans mon souvenir on avait pas dit qu'on évitait les delete cascades?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Voilà ce qu'on a décidé :

  • Si supprime t_modules => supprime cor_module_type
  • Si supprime bib_type_site => supprime cor_module_type
  • Si supprime t_nomenclature associé à bib_type_site => ERREUR
  • Si supprime t_nomenclature associé à cor_type_site => ERREUR

Donc CASCADE seulement sur cor_module_type sur id_type_site et id_module

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Normalement, après vérification, tout était déjà bon. J'attends ton retour

# FIXME: find a better way because need to assign a module...
statement = sa.text(
f"""
update {monitorings_schema}.t_site_complements
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Si j'ai bien compris id_module de t_site_compléments sera peuplé avec la valeur 'MONITORINGS' ce qui n'est pas un vrai retour en arrière

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oui ce n'est pas idéal mais je ne sais pas si c'est possible de faire le downgrade à l'identique ici car on désolidarise les sites des modules

backend/gn_module_monitoring/monitoring/schemas.py Outdated Show resolved Hide resolved
backend/gn_module_monitoring/utils/routes.py Outdated Show resolved Hide resolved
* refactor(api): change offset to page

* refactor(api): rename id_nomenclature

* fix(admin): add compare field to Unique

Since now, BibTypeSite and TNomenclature do not share the same
column anymore (id_nomenclature_type_site vs id_nomenclature)
@amandine-sahl amandine-sahl merged commit c606f8f into PnX-SI:dev-suivi-eolien Mar 3, 2023
@amandine-sahl amandine-sahl deleted the dev-suivi-eolien-checkpoint1 branch March 3, 2023 14:53
@mvergez mvergez restored the dev-suivi-eolien-checkpoint1 branch April 18, 2023 15:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants