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

fix river basin names and improve errors in hierarchy #98

13 changes: 9 additions & 4 deletions backend/gn_module_zh/blueprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from flask import Blueprint, Response, jsonify, request, send_file, g
from flask.helpers import send_file
from geojson import FeatureCollection
from werkzeug.exceptions import Forbidden, BadRequest
from werkzeug.exceptions import Forbidden, BadRequest, NotFound

from geonature.core.gn_commons.models import TMedias

Expand Down Expand Up @@ -53,7 +53,7 @@
)

# from .forms import *
from .geometry import set_area, set_geom
from .geometry import set_area, set_geom, get_main_rb
from .hierarchy import Hierarchy, get_all_hierarchy_fields
from .model.cards import Card
from .model.repositories import ZhRepository
Expand Down Expand Up @@ -225,7 +225,8 @@ def get_complete_info(id_zh):

def get_complete_card(id_zh: int) -> Card:
ref_geo_config = [ref for ref in blueprint.config["ref_geo_referentiels"] if ref["active"]]
return Card(id_zh, "full", ref_geo_config).__repr__()
main_id_rb = DB.session.scalar(select(TZH.main_id_rb).where(TZH.id_zh == id_zh))
return Card(id_zh, main_id_rb, "full", ref_geo_config).__repr__()


@blueprint.route("/eval/<int:id_zh>", methods=["GET"])
Expand Down Expand Up @@ -599,6 +600,7 @@ def get_tab_data(id_tab):
raise BadRequest(
"Géométrie manquante",
)

# POST / PATCH
if "id_zh" not in form_data.keys():
# set geometry from coordinates
Expand Down Expand Up @@ -994,7 +996,10 @@ def get_hydro_zones_from_bassin() -> dict:
@permissions.check_cruved_scope("R", module_code="ZONES_HUMIDES")
def get_hierarchy(id_zh):
"""Get zh note"""
hierarchy = Hierarchy(id_zh)
main_id_rb = DB.session.scalar(select(TZH.main_id_rb).where(TZH.id_zh == id_zh))
if not main_id_rb:
raise NotFound("The ZH is not in a river basin")
hierarchy = Hierarchy(id_zh, main_id_rb)
return hierarchy.as_dict()


Expand Down
75 changes: 19 additions & 56 deletions backend/gn_module_zh/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
TOwnership,
TUrbanPlanningDocs,
)
from .geometry import get_main_rb


def update_tzh(data):
Expand All @@ -65,6 +66,12 @@ def create_zh(form_data, info_role, zh_date, polygon, zh_area, ref_geo_referenti
# temporary code
code = str(uuid.uuid4())[0:12]

# main river basin
rbs = TZH.get_zh_area_intersected(
"river_basin", func.ST_GeomFromGeoJSON(str(form_data["geom"]["geometry"]))
)
main_id_rb = get_main_rb(rbs, form_data["geom"]["geometry"])

# create zh : fill pr_zh.t_zh
new_zh = TZH(
main_name=form_data["main_name"],
Expand All @@ -78,6 +85,7 @@ def create_zh(form_data, info_role, zh_date, polygon, zh_area, ref_geo_referenti
id_sdage=form_data["sdage"],
geom=polygon,
area=zh_area,
main_id_rb=main_id_rb,
)
DB.session.add(new_zh)
DB.session.flush()
Expand Down Expand Up @@ -111,7 +119,7 @@ def create_zh(form_data, info_role, zh_date, polygon, zh_area, ref_geo_referenti
)

# fill cor_zh_rb
post_cor_zh_rb(form_data["geom"]["geometry"], new_zh.id_zh)
post_cor_zh_rb(form_data["geom"]["geometry"], new_zh.id_zh, rbs)
# fill cor_zh_hydro
post_cor_zh_hydro(form_data["geom"]["geometry"], new_zh.id_zh)
# fill cor_zh_fct_area
Expand All @@ -133,22 +141,6 @@ def create_zh(form_data, info_role, zh_date, polygon, zh_area, ref_geo_referenti
return new_zh.id_zh


# except ZHApiError:
# raise
# except Exception as e:
# if e.__class__.__name__ == "DataError":
# raise ZHApiError(
# message="create_zh_post_db_error",
# details=str(e.orig.diag.sqlstate + ": " + e.orig.diag.message_primary),
# status_code=400,
# )
# exc_type, value, tb = sys.exc_info()
# raise ZHApiError(
# message="create_zh_post_error",
# details=str(exc_type) + ": " + str(e.with_traceback(tb)),
# )


def post_cor_lim_list(uuid_lim, criteria):
try:
# fill pr_zh.cor_lim_list
Expand Down Expand Up @@ -204,36 +196,12 @@ def post_cor_zh_area(polygon, id_zh, id_type):
cover = None
DB.session.add(CorZhArea(id_area=element, id_zh=id_zh, cover=cover))
DB.session.flush()
# except Exception as e:
# if e.__class__.__name__ == "DataError":
# raise ZHApiError(
# message="post_cor_zh_area_db_error",
# details=str(e.orig.diag.sqlstate + ": " + e.orig.diag.message_primary),
# )
# exc_type, value, tb = sys.exc_info()
# raise ZHApiError(
# message="post_cor_zh_area_error",
# details=str(exc_type) + ": " + str(e.with_traceback(tb)),
# )


def post_cor_zh_rb(geom, id_zh):
# try:
rbs = TZH.get_zh_area_intersected("river_basin", func.ST_GeomFromGeoJSON(str(geom)))
def post_cor_zh_rb(geom, id_zh, rbs):
for rb in rbs:
DB.session.add(CorZhRb(id_zh=id_zh, id_rb=rb.id_rb))
DB.session.flush()
# except Exception as e:
# if e.__class__.__name__ == "DataError":
# raise ZHApiError(
# message="post_cor_zh_rb_db_error",
# details=str(e.orig.diag.sqlstate + ": " + e.orig.diag.message_primary),
# )
# exc_type, value, tb = sys.exc_info()
# raise ZHApiError(
# message="post_cor_zh_rb_error",
# details=str(exc_type) + ": " + str(e.with_traceback(tb)),
# )


def post_cor_zh_hydro(geom, id_zh):
Expand Down Expand Up @@ -292,10 +260,15 @@ def update_zh_tab0(form_data, polygon, area, info_role, zh_date, geo_refs):

DB.session.execute(delete(CorLimList).where(CorLimList.id_lim_list == id_lim_list))
post_cor_lim_list(id_lim_list, form_data["critere_delim"])
main_id_rb = DB.session.get(TZH, form_data["id_zh"]).main_id_rb

if is_geom_new:
rbs = TZH.get_zh_area_intersected(
"river_basin", func.ST_GeomFromGeoJSON(str(form_data["geom"]["geometry"]))
)
main_id_rb = get_main_rb(rbs, form_data["geom"]["geometry"])
update_cor_zh_area(polygon, form_data["id_zh"], geo_refs)
update_cor_zh_rb(form_data["geom"]["geometry"], form_data["id_zh"])
update_cor_zh_rb(form_data["geom"]["geometry"], form_data["id_zh"], rbs)
update_cor_zh_hydro(form_data["geom"]["geometry"], form_data["id_zh"])
ef_area = update_cor_zh_fct_area(form_data["geom"]["geometry"], form_data["id_zh"])

Expand All @@ -312,22 +285,12 @@ def update_zh_tab0(form_data, polygon, area, info_role, zh_date, geo_refs):
geom=polygon,
area=area,
ef_area=ef_area,
main_id_rb=main_id_rb,
)
)

DB.session.flush()
return form_data["id_zh"]
# except Exception as e:
# if e.__class__.__name__ == "DataError":
# raise ZHApiError(
# message="update_tab0_db_error",
# details=str(e.orig.diag.sqlstate + ": " + e.orig.diag.message_primary),
# status_code=400,
# )
# exc_type, value, tb = sys.exc_info()
# raise ZHApiError(
# message="update_tab0_error", details=str(exc_type) + ": " + str(e.with_traceback(tb))
# )


def check_polygon(polygon, id_zh):
Expand Down Expand Up @@ -389,9 +352,9 @@ def update_cor_zh_area(polygon, id_zh, geo_refs):
)


def update_cor_zh_rb(geom, id_zh):
def update_cor_zh_rb(geom, id_zh, rbs):
DB.session.execute(delete(CorZhRb).where(CorZhRb.id_zh == id_zh))
post_cor_zh_rb(geom, id_zh)
post_cor_zh_rb(geom, id_zh, rbs)


def update_cor_zh_hydro(geom, id_zh):
Expand Down
20 changes: 4 additions & 16 deletions backend/gn_module_zh/geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,27 +86,15 @@ def set_area(geom):
)


def get_main_rb(query: list) -> int:
def get_main_rb(rbs, geom):
rb_id = None
area = 0
for q_ in query:
zh_polygon = DB.session.execute(
select(TZH.geom).where(TZH.id_zh == getattr(q_, "id_zh"))
).scalar_one()

rb_polygon = DB.session.execute(
select(TRiverBasin.geom)
.select_from(CorZhRb)
.join(TRiverBasin, TRiverBasin.id_rb == CorZhRb.id_rb)
.where(TRiverBasin.id_rb == getattr(q_, "id_rb"))
.limit(1)
).scalar_one()

for q_ in rbs:
intersection = DB.session.scalar(
select(
func.ST_Intersection(
func.ST_GeomFromText(func.ST_AsText(zh_polygon)),
func.ST_GeomFromText(func.ST_AsText(rb_polygon)),
func.ST_GeomFromText(func.ST_AsText(func.ST_GeomFromGeoJSON(str(geom)))),
func.ST_GeomFromText(func.ST_AsText(getattr(q_, "geom"))),
)
)
)
Expand Down
18 changes: 2 additions & 16 deletions backend/gn_module_zh/hierarchy.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import sys
from itertools import groupby
from werkzeug.exceptions import NotFound


from geonature.utils.env import DB
from pypnnomenclature.models import BibNomenclaturesTypes, TNomenclatures
Expand Down Expand Up @@ -1134,11 +1132,9 @@ def __str__(self):


class Hierarchy(ZH):
def __init__(self, id_zh):
def __init__(self, id_zh, main_id_rb):
self.id_zh = id_zh
self.rb_id = self.__get_rb()
if not self.rb_id:
raise NotFound("The ZH is not in a river basin")
self.rb_id = main_id_rb
self.is_rules = self.__check_if_rules()
self.volet1 = Volet1(self.id_zh, self.rb_id)
self.volet2 = Volet2(self.id_zh, self.rb_id)
Expand All @@ -1162,16 +1158,6 @@ def __get_final_note(self):
else:
return None

def __get_rb(self):
q_rb = ZH.get_data_by_id(CorZhRb, self.id_zh)
if not q_rb:
return None
if len(q_rb) > 1:
return get_main_rb(q_rb)
return DB.session.execute(
select(CorZhRb.id_rb, TRiverBasin).join(TRiverBasin).where(CorZhRb.id_zh == self.id_zh)
).scalar_one()

def __check_if_rules(self):
try:
if not DB.session.scalars(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""add_main_id_rb_column

Revision ID: 58ab8aba8512
Revises: 76e89c793961
Create Date: 2024-09-11 15:14:12.546662

"""

from alembic import op
import sqlalchemy as sa
from sqlalchemy import Column, Integer


# revision identifiers, used by Alembic.
revision = "58ab8aba8512"
down_revision = "76e89c793961"
branch_labels = None
depends_on = None


def upgrade():
op.add_column(
schema="pr_zh",
table_name="t_zh",
column=Column(
"main_id_rb",
Integer,
nullable=True,
),
)


def downgrade():
op.drop_column(
schema="pr_zh",
table_name="t_zh",
column_name="main_id_rb",
)
51 changes: 51 additions & 0 deletions backend/gn_module_zh/migrations/72a8378567pa_update_main_id_rb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""update_main_id_rb

Revision ID: 72a8378567pa
Revises: 58ab8aba8512
Create Date: 2024-09-11 17:18:21.165324

"""

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = "72a8378567pa"
down_revision = "58ab8aba8512"
branch_labels = None
depends_on = None


def upgrade():
op.execute(
"""
UPDATE pr_zh.t_zh tzh
SET main_id_rb =
(
SELECT id_rb
FROM (
SELECT
czr.id_rb AS id_rb,
ST_Area(ST_Intersection(
ST_GeomFromText(ST_AsText((SELECT geom FROM pr_zh.t_zh WHERE id_zh = tzh.id_zh ))),
ST_GeomFromText(ST_AsText(trb.geom))
)) AS areas
FROM pr_zh.cor_zh_rb czr
LEFT JOIN pr_zh.t_river_basin trb ON trb.id_rb = czr.id_rb
WHERE czr.id_zh = tzh.id_zh
ORDER BY areas DESC
LIMIT 1
) AS a
)
"""
)


def downgrade():
op.execute(
"""
UPDATE pr_zh.t_zh tzh
SET main_id_rb = null
"""
)
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ CREATE TABLE pr_zh.t_zh (
remark_is_other_inventory varchar(2000) ,
main_pict_id integer ,
area real ,
main_id_rb integer ,
CONSTRAINT pk_t_zh_zh_id PRIMARY KEY ( id_zh ),
CONSTRAINT unq_t_zh_code UNIQUE ( code ) ,
CONSTRAINT unq_t_zh UNIQUE ( zh_uuid )
Expand Down
Loading
Loading