This commit is contained in:
lpoulin 2024-11-26 14:56:34 +01:00
parent c618d76f28
commit 941a639d98
63 changed files with 51341 additions and 0 deletions

View File

@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
"""
/***************************************************************************
pluginsCenSavoie
A QGIS plugin
Load plugins of CEN Savoie
-------------------
begin : 2016-09-08
copyright : (C) 2016 by CEN Savoie
email : sig@cen-savoie.org
git sha : $Format:%H$
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
This script initializes the plugin, making it known to QGIS.
"""
def classFactory(iface):
from .pluginsCenSavoie_v3 import pluginsCenSavoie_v3
return pluginsCenSavoie_v3(iface)

View File

@ -0,0 +1,36 @@
@ECHO OFF
set OSGEO4W_ROOT=C:\OSGeo4W64
set PATH=%OSGEO4W_ROOT%\bin;%PATH%
set PATH=%PATH%;%OSGEO4W_ROOT%\apps\qgis\bin
@echo off
call "%OSGEO4W_ROOT%\bin\o4w_env.bat"
call "%OSGEO4W_ROOT%\bin\qt5_env.bat"
call "%OSGEO4W_ROOT%\bin\py3_env.bat"
@echo off
path %OSGEO4W_ROOT%\apps\qgis-dev\bin;%OSGEO4W_ROOT%\apps\grass\grass-7.2.2\lib;%OSGEO4W_ROOT%\apps\grass\grass-7.2.2\bin;%PATH%
cd /d %~dp0
pause
@ECHO ON
::Ui Compilation
REM call pyuic5 dialog.ui -o gui\generated\ui_dialog.py
::Resources
call pyrcc5 resources.qrc -o resources.py
@ECHO OFF
GOTO END
pause
:ERROR
echo "Failed!"
set ERRORLEVEL=%ERRORLEVEL%
pause
:END
@ECHO ON

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

View File

@ -0,0 +1,40 @@
# This file contains metadata for your plugin. Since
# version 2.0 of QGIS this is the proper way to supply
# information about a plugin. The old method of
# embedding metadata in __init__.py will
# is no longer supported since version 2.0.
# This file should be included when you package your plugin.# Mandatory items:
[general]
name=Plugins Cen Savoie
qgisMinimumVersion=2.99
qgisMaximumVersion=3.98
description=Load plugins of CEN Savoie
version=2.0
author=CEN Savoie
email=sig@cen-savoie.org
about=Ce plugin charge tous les plugins que l'utilisateur a le droit d'utiliser. This plugin load every plugins the user is allowed to use.
tracker=a
repository=a
# End of mandatory metadata
# Recommended items:
# Uncomment the following line and add your changelog:
# changelog=
# Tags are comma separated with spaces allowed
tags=a
homepage=a
category=Plugins
icon=icons/icon_base.png
# experimental flag
experimental=False
# deprecated flag (applies to the whole plugin, not just a single version)
deprecated=False

View File

@ -0,0 +1,135 @@
# -*- coding: utf-8 -*-
"""
/***************************************************************************
pluginsCenSavoie_v3
A QGIS plugin
Load plugins of CEN Savoie
-------------------
begin : 2016-09-08
git sha : $Format:%H$
copyright : (C) 2016 by CEN Savoie
email : sig@cen-savoie.org
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
# Import the PyQt and QGIS libraries
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from qgis.core import *
import webbrowser, os
import os.path, sys
import psycopg2
import psycopg2.extras
import base64
# Set up current path.
currentPath = os.path.dirname( __file__ )
#Import own tools
from pluginsCenSavoie_v3.tools.create_sessionAF import CreateSessionAF
from pluginsCenSavoie_v3.tools.backinMFU import BackinMFU
from pluginsCenSavoie_v3.tools.parcelle_to_acte import ParcelleToActe
from pluginsCenSavoie_v3.tools.parcelle_to_site import ParcelleToSite
from pluginsCenSavoie_v3.tools.help import help
# Import du fichier de configuration
from pluginsCenSavoie_v3.tools.confPython import bd_cen_host, bd_cen_port, bd_cen_name, bd_cen_mdp_1st_cnx
class pluginsCenSavoie_v3:
def __init__(self, iface):
self.iface = iface
self.canvas = self.iface.mapCanvas()
self.plugin_dir = os.path.dirname(__file__)
global host
host = bd_cen_host
global port
port = bd_cen_port
global bdd
bdd = bd_cen_name
global mdp_1st_cnx
mdp_1st_cnx = bd_cen_mdp_1st_cnx
def initGui(self):
if sys.platform == 'linux':
os_user = os.environ['USER']
else:
os_user = os.environ['USERNAME']
self.toolBar = self.iface.addToolBar("pluginsCenSavoie_v3")
self.toolBar.setObjectName("Plugins CEN Savoie")
global user, mdp
first_conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=first_cnx password=" + mdp_1st_cnx)
first_cur = first_conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
first_cur.execute("SELECT mdp_cen, usename FROM pg_catalog.pg_user t1, admin_sig.utilisateurs t2 WHERE t2.oid = t1.usesysid AND (utilisateur_id = '" + os_user + "' OR utilisateur_os = '" + os_user + "')")
res_ident = first_cur.fetchone()
mdp = base64.b64decode(str(res_ident[0])).decode('utf-8')
user = res_ident[1]
first_conn.close()
conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=" + user + " password=" + mdp)
cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
cur.execute("""
WITH RECURSIVE t(oid) AS (
VALUES ((SELECT oid FROM admin_sig.utilisateurs WHERE utilisateur_id = '""" + os_user + """' OR utilisateur_os = '""" + os_user + """'))
UNION ALL
SELECT grosysid
FROM pg_catalog.pg_group JOIN t ON (t.oid = ANY (grolist))
)
SELECT DISTINCT groname
FROM pg_catalog.pg_group JOIN t ON (t.oid = pg_group.grosysid)""")
user_group = cur.fetchall()
tbl_grp = []
i = 0
while i < len(user_group): #Boucle sur toutes les options
tbl_grp.append(user_group[i][0])
i=i+1
cur.execute("""
WITH RECURSIVE t(oid) AS (
VALUES ((SELECT oid FROM admin_sig.utilisateurs WHERE utilisateur_id = '""" + os_user + """' OR utilisateur_os = '""" + os_user + """'))
UNION ALL
SELECT grosysid
FROM pg_catalog.pg_group JOIN t ON (t.oid = ANY (grolist))
),
t_group AS (
SELECT DISTINCT groname
FROM pg_catalog.pg_group JOIN t ON (t.oid = pg_group.grosysid))
SELECT
count(*) FILTER (WHERE grant_elt_id = 3 AND grant_group_droit = 't' AND grant_group_id IN (groname)) as parc,
count(*) FILTER (WHERE grant_elt_id = 26 AND grant_group_droit = 't' AND grant_group_id IN (groname)) as site
FROM foncier.grant_group JOIN t_group ON (groname = grant_group_id)""")
can_parc_site = cur.fetchone()
# # Get the tools
if 'cen_user' in tbl_grp:
self.backinMFU = BackinMFU(self.iface, self.toolBar)
self.toolBar.addSeparator()
self.toolBar.addSeparator()
if 'grp_foncier' in tbl_grp or 'grp_sig' in tbl_grp:
if can_parc_site[0] > 0:
self.parcelle_to_acte = ParcelleToActe(self.iface, self.toolBar)
if can_parc_site[1] > 0:
self.parcelle_to_site = ParcelleToSite(self.iface, self.toolBar)
if 'grp_animation_fonciere' in tbl_grp or 'grp_sig' in tbl_grp:
self.create_sessionAF = CreateSessionAF(self.iface, self.toolBar)
if 'grp_animation_fonciere' in tbl_grp or 'grp_foncier' in tbl_grp or 'grp_sig' in tbl_grp:
self.toolBar.addSeparator()
self.toolBar.addSeparator()
if 'cen_user' in tbl_grp:
self.help = help(self.iface, self.toolBar)
conn.close()
def unload(self):
del self.toolBar

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,50 @@
<RCC>
<qresource prefix="/plugins/pluginsCenSavoie_v3" >
<file>tools/images/Frise_portrait.png</file>
</qresource>
<qresource prefix="/plugins/pluginsCenSavoie_v3" >
<file>tools/images/Logo_CEN_Savoie.png</file>
</qresource>
<qresource prefix="/plugins/pluginsCenSavoie_v3" >
<file>tools/images/fond_70.png</file>
</qresource>
<qresource prefix="/plugins/pluginsCenSavoie_v3" >
<file>tools/images/delorean.png</file>
</qresource>
<qresource prefix="/plugins/pluginsCenSavoie_v3" >
<file>icons/createSessionAF.png</file>
</qresource>
<qresource prefix="/plugins/pluginsCenSavoie_v3" >
<file>icons/backinMFU.png</file>
</qresource>
<qresource prefix="/plugins/pluginsCenSavoie_v3" >
<file>icons/parcelleToActe.png</file>
</qresource>
<qresource prefix="/plugins/pluginsCenSavoie_v3" >
<file>icons/parcelleToSite.png</file>
</qresource>
<qresource prefix="/plugins/pluginsCenSavoie_v3" >
<file>icons/objGestion.png</file>
</qresource>
<qresource prefix="/plugins/pluginsCenSavoie_v3" >
<file>icons/sicen.png</file>
</qresource>
<qresource prefix="/plugins/pluginsCenSavoie_v3" >
<file>icons/layerCodex.png</file>
</qresource>
<qresource prefix="/plugins/pluginsCenSavoie_v3" >
<file>icons/parcDDENOM.png</file>
</qresource>
<qresource prefix="/plugins/pluginsCenSavoie_v3" >
<file>icons/copyTrav.png</file>
</qresource>
<qresource prefix="/plugins/pluginsCenSavoie_v3" >
<file>icons/createEPCI.png</file>
</qresource>
<qresource prefix="/plugins/pluginsCenSavoie_v3" >
<file>icons/filterTrav.png</file>
</qresource>
<qresource prefix="/plugins/pluginsCenSavoie_v3" >
<file>icons/help.png</file>
</qresource>
</RCC>

Binary file not shown.

View File

View File

@ -0,0 +1,419 @@
# -*- coding: utf-8 -*-
"""
/***************************************************************************
BackinMFU
A QGIS plugin
Permet de créer une nouvelle session d'animation foncière
-------------------
begin : 2015-10-02
git sha : $Format:%H$
copyright : (C) 2015 by CEN Savoie
email : a.lesconnec@cen-savoie.org
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QAction, QTableWidgetItem
from PyQt5.QtXml import QDomDocument
from qgis.core import *
from qgis.gui import *
# Initialize Qt resources from file resources.py
from pluginsCenSavoie_v3 import resources
# Import the code for the dialog
from pluginsCenSavoie_v3.tools.backinMFU_dialog import BackinMFUDialog
# Import du fichier de configuration
from pluginsCenSavoie_v3.tools.confPython import bd_cen_host, bd_cen_port, bd_cen_name, bd_cen_mdp_1st_cnx
import os.path
import sys
import qgis
import os
import psycopg2
import psycopg2.extras
import base64
import re
from time import localtime, strftime
class BackinMFU:
"""QGIS Plugin Implementation."""
def __init__(self, iface, cenToolbar):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgsInterface
"""
# Variable HOTE de l'accès à la base de données
global host
host = bd_cen_host
global port
port = bd_cen_port
global bdd
bdd = bd_cen_name
global mdp_1st_cnx
mdp_1st_cnx = bd_cen_mdp_1st_cnx
global os_user
if sys.platform == 'linux':
os_user = os.environ['USER']
else:
os_user = os.environ['USERNAME']
# Save reference to the QGIS interface
self.iface = iface
self.canvas = self.iface.mapCanvas()
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# Create the dialog (after translation) and keep reference
self.dlg = BackinMFUDialog()
# Add toolbar button
self.action= QAction(QIcon(":/plugins/pluginsCenSavoie_v3/icons/backinMFU.png"), QCoreApplication.translate('BackinMFU', u'Retour vers la MFU'), self.iface.mainWindow())
self.action.triggered.connect(self.run)
self.action.setEnabled(True)
cenToolbar.addAction(self.action)
def run(self):
"""Run method that performs all the real work"""
# show the dialog
self.dlg.img_logo.setPixmap(QPixmap(":/plugins/pluginsCenSavoie_v3/tools/images/Logo_CEN_Savoie.png"))
self.dlg.lbl_delorean.setPixmap(QPixmap(":/plugins/pluginsCenSavoie_v3/tools/images/delorean.png"))
self.dlg.lbl_fond.setPixmap(QPixmap(":/plugins/pluginsCenSavoie_v3/tools/images/fond_70.png"))
self.dlg.lbl_fond.stackUnder(self.dlg.button_box)
self.dlg.show()
# Run the dialog event loop
result = self.dlg.exec_()
# See if OK was pressed
if result:
first_conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=first_cnx password=" + mdp_1st_cnx)
first_cur = first_conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
first_cur.execute("SELECT mdp_cen, usename FROM pg_catalog.pg_user t1, admin_sig.utilisateurs t2 WHERE t2.oid = t1.usesysid AND (utilisateur_id = '" + os_user + "' OR utilisateur_os = '" + os_user + "')")
res_ident = first_cur.fetchone()
mdp = base64.b64decode(str(res_ident[0])).decode('utf-8')
user = res_ident[1]
first_conn.close()
uri = QgsDataSourceUri()
uri.setConnection(host ,port ,bdd ,user ,mdp)
calDate = self.dlg.calSelect.selectedDate().toString('yyyy-MM-dd')
table_name = 'mfu_'+calDate
sql = """
WITH RECURSIVE table_lot AS (
SELECT
site_id,
old_cad_site_id,
new_lot_id,
new_lot_id AS lot_id_origin,
0 AS level,
ARRAY[old_cad_site_id, new_cad_site_id] as tbl_cad_site_id
FROM
foncier_maj.vm_filiation_parcelles
WHERE diff_surf = 0
UNION
SELECT
v.site_id,
v.old_cad_site_id,
v.new_lot_id,
t.lot_id_origin,
t.level + 1,
CASE WHEN v.old_cad_site_id = ANY (t.tbl_cad_site_id) THEN
CASE WHEN v.new_cad_site_id = ANY (t.tbl_cad_site_id) THEN
t.tbl_cad_site_id
ELSE
array_append(t.tbl_cad_site_id, v.new_cad_site_id)
END
ELSE
CASE WHEN v.new_cad_site_id = ANY (t.tbl_cad_site_id) THEN
array_append(t.tbl_cad_site_id, v.old_cad_site_id)
ELSE
array_append(array_append(t.tbl_cad_site_id, v.old_cad_site_id), v.new_cad_site_id)
END
END
FROM
foncier_maj.vm_filiation_parcelles as v
INNER JOIN table_lot as t ON (t.old_cad_site_id = v.new_cad_site_id)
WHERE diff_surf = 0
),
t_max_level AS (
SELECT lot_id_origin, max(level) as level FROM table_lot GROUP BY lot_id_origin
),
t_filiation_lots AS (
SELECT DISTINCT
table_lot.site_id, table_lot.lot_id_origin, table_lot.tbl_cad_site_id
FROM
table_lot
JOIN t_max_level USING (lot_id_origin, level)
LEFT JOIN table_lot as table_lot2 ON (table_lot2.tbl_cad_site_id @> table_lot.tbl_cad_site_id AND table_lot2.tbl_cad_site_id <> table_lot.tbl_cad_site_id AND table_lot2.site_id = table_lot.site_id)
WHERE table_lot2.tbl_cad_site_id IS NULL
),
tprob AS (
SELECT DISTINCT unnest(string_to_array(array_to_string(array_agg(site_id), ','), ',')) AS site_id
FROM (
SELECT DISTINCT site_id FROM alertes.v_prob_mfu_baddata
UNION
SELECT DISTINCT site_id FROM alertes.v_prob_cadastre_cen WHERE statutmfu_id = 1
UNION
SELECT DISTINCT site_id FROM alertes.v_alertes_mu WHERE alerte LIKE 'termin%'
UNION
SELECT DISTINCT substring(v_prob_mfu_sansparc.mfu_id::text, 4, 4) AS site_id FROM alertes.v_prob_mfu_sansparc
) tsousprob
),
t_actes AS (
SELECT
acte,
mfu_id,
COALESCE(date_effet_conv, date_sign_acte) as date_acte_debut,
COALESCE(NULLIF(date_fin_acte, 'N.D.'), COALESCE(last_end, 'infini')) as date_acte_fin
FROM alertes.v_tdb_mfu
WHERE
statutmfu_id NOT IN (0, 3)
),
t_temp_mu AS (
SELECT DISTINCT
cadastre_site.site_id,
par_id,
COALESCE(lot_id_origin, lot_id) AS lot_id,
COALESCE(r_cad_site_mu.surf_mu, dcntlo) as dcntlo,
COALESCE(r_cad_site_mu.geom, parcelles_cen.geom) as geom,
CASE WHEN surf_mu IS NOT NULL THEN 'Convention pour partie' ELSE 'Convention' END AS mfu,
mu_id AS mfu_id,
r_cad_site_mu.date_entree,
r_cad_site_mu.date_sortie,
r_cad_site_mu.motif_entree_id
FROM
cadastre.parcelles_cen
JOIN cadastre.lots_cen USING (par_id)
JOIN cadastre.cadastre_cen USING (lot_id)
JOIN foncier.cadastre_site USING (cad_cen_id)
JOIN foncier.r_cad_site_mu USING (cad_site_id)
JOIN foncier.mu_conventions USING (mu_id)
JOIN foncier.d_typmu USING (typmu_id)
LEFT JOIN t_filiation_lots ON (t_filiation_lots.site_id = cadastre_site.site_id AND cad_site_id = ANY(tbl_cad_site_id))
WHERE d_typmu.mfu = 't'
),
t_synthese_mu AS (
SELECT
site_id,
par_id,
lot_id,
dcntlo as surf_mfu,
geom,
mfu,
mfu_id,
date_acte_debut,
GREATEST(MIN(date_entree), date_acte_debut) as min_date_entree_mu,
LEAST(MAX(date_sortie), date_acte_fin) as max_date_sortie_mu
FROM
t_temp_mu
JOIN t_actes USING (mfu_id)
GROUP BY t_temp_mu.site_id, t_temp_mu.par_id, t_temp_mu.lot_id, t_temp_mu.dcntlo, t_temp_mu.geom, t_temp_mu.mfu, t_temp_mu.mfu_id, t_actes.date_acte_debut, t_actes.date_acte_fin
),
t_temp_mf AS (
SELECT DISTINCT
cadastre_site.site_id,
par_id,
COALESCE(lot_id_origin, lot_id) AS lot_id,
dcntlo,
parcelles_cen.geom,
'Acquisition' AS mfu,
mf_id AS mfu_id,
r_cad_site_mf.date_entree,
r_cad_site_mf.date_sortie
FROM
cadastre.parcelles_cen
JOIN cadastre.lots_cen USING (par_id)
JOIN cadastre.cadastre_cen USING (lot_id)
JOIN foncier.cadastre_site USING (cad_cen_id)
JOIN foncier.r_cad_site_mf USING (cad_site_id)
LEFT JOIN t_filiation_lots ON (t_filiation_lots.site_id = cadastre_site.site_id AND cad_site_id = ANY(tbl_cad_site_id))
),
t_synthese_mf AS (
SELECT
site_id,
par_id,
lot_id,
dcntlo as surf_mfu,
geom,
mfu,
mfu_id,
date_acte_debut,
GREATEST(MIN(date_entree), date_acte_debut) as min_date_entree_mf,
LEAST(MAX(date_sortie), date_acte_fin) as max_date_sortie_mf
FROM
t_temp_mf
JOIN t_actes USING (mfu_id)
GROUP BY t_temp_mf.site_id, t_temp_mf.lot_id, t_temp_mf.par_id, t_temp_mf.dcntlo, t_temp_mf.geom, t_temp_mf.mfu, t_temp_mf.mfu_id, t_actes.date_acte_debut, t_actes.date_acte_fin
),
tmfu AS (
SELECT DISTINCT
site_id,
par_id,
geom,
lot_id,
surf_mfu as surf_acq,
0 as surf_conv,
mfu,
mfu_id as acte_id,
date_acte_debut,
LEFT(min_date_entree_mf, 10) AS min_date_entree_mf,
LEFT(max_date_sortie_mf, 10) AS max_date_sortie_mf,
'3000-01-01' as min_date_entree_mu,
'3000-12-31' as max_date_sortie_mu,
0 AS motif_entree_id_mu,
CASE WHEN tprob.site_id IS NOT NULL THEN 1 ELSE 0 END as etat_bilan
FROM
t_synthese_mf
LEFT JOIN tprob USING (site_id)
UNION
SELECT DISTINCT
t_synthese_mu.site_id,
t_synthese_mu.par_id,
t_synthese_mu.geom,
t_synthese_mu.lot_id,
0 as surf_acq,
surf_mfu as surf_conv,
t_synthese_mu.mfu,
t_synthese_mu.mfu_id as acte_id,
date_acte_debut,
'3000-01-01' as min_date_entree_mf,
'3000-12-31' as max_date_sortie_mf,
LEFT(min_date_entree_mu, 10) AS min_date_entree_mu,
LEFT(max_date_sortie_mu, 10) AS max_date_sortie_mu,
motif_entree_id AS motif_entree_id_mu,
CASE WHEN tprob.site_id IS NOT NULL THEN 1 ELSE 0 END as etat_bilan
FROM
t_synthese_mu
JOIN t_temp_mu ON (t_synthese_mu.site_id = t_temp_mu.site_id AND t_synthese_mu.min_date_entree_mu = t_temp_mu.date_entree AND t_synthese_mu.mfu_id = t_temp_mu.mfu_id AND t_synthese_mu.lot_id = t_temp_mu.lot_id)
LEFT JOIN tprob ON (t_synthese_mu.site_id = tprob.site_id)
),
t_bilan1 AS (
SELECT DISTINCT
site_id, lot_id, par_id, geom, mfu, acte_id, min_date_entree_mf, max_date_sortie_mf, min_date_entree_mu, max_date_sortie_mu,
CASE WHEN mfu = 'Acquisition' AND min_date_entree_mf <= '"""+calDate+"""' AND (max_date_sortie_mf = 'N.D.' OR max_date_sortie_mf >= '"""+calDate+"""') THEN
surf_acq
ELSE
0
END AS surf_acqu,
CASE WHEN mfu LIKE 'Convention%' AND min_date_entree_mu <= '"""+calDate+"""' AND (max_date_sortie_mu = 'N.D.' OR max_date_sortie_mu >= '"""+calDate+"""') THEN
surf_conv
ELSE
0
END AS surf_conv,
etat_bilan
FROM
tmfu
),
tmfu_one_day1 AS (
SELECT tmfu.*, t_bilan1.surf_acqu, t_bilan1.surf_conv
FROM
t_bilan1
JOIN tmfu USING (lot_id)
WHERE
(t_bilan1.surf_acqu > 0 AND t_bilan1.max_date_sortie_mf = '"""+calDate+"""') OR
(t_bilan1.surf_conv > 0 AND t_bilan1.max_date_sortie_mu = '"""+calDate+"""')
),
tmfu_one_day2 AS (
SELECT old_lot_id, array_agg(new_lot_id) as tbl_lot_one_day
FROM
tmfu_one_day1
JOIN foncier_maj.vm_filiation_parcelles ON (lot_id = old_lot_id AND tmfu_one_day1.site_id = vm_filiation_parcelles.site_id)
JOIN tmfu ON (new_lot_id = tmfu.lot_id)
WHERE
(
surf_acqu > 0 AND
tmfu.min_date_entree_mf != 'N.D.' AND tmfu_one_day1.max_date_sortie_mf != 'N.D.' AND
tmfu.min_date_entree_mf::date = tmfu_one_day1.max_date_sortie_mf::date +'1 day'::interval
)
OR
(
tmfu.surf_conv > 0 AND
tmfu.min_date_entree_mu != 'N.D.' AND tmfu_one_day1.max_date_sortie_mu != 'N.D.' AND
tmfu.min_date_entree_mu::date = tmfu_one_day1.max_date_sortie_mu::date +'1 day'::interval
)
GROUP BY old_lot_id
UNION
SELECT new_lot_id, array_agg(old_lot_id) as tbl_lot_one_day
FROM
tmfu_one_day1
JOIN foncier_maj.vm_filiation_parcelles ON (lot_id = new_lot_id AND tmfu_one_day1.site_id = vm_filiation_parcelles.site_id)
JOIN tmfu ON (old_lot_id = tmfu.lot_id)
WHERE
(
surf_acqu > 0 AND
tmfu.max_date_sortie_mf != 'N.D.' AND tmfu_one_day1.min_date_entree_mf != 'N.D.' AND
tmfu.max_date_sortie_mf::date = tmfu_one_day1.min_date_entree_mf::date -'1 day'::interval
)
OR
(
tmfu.surf_conv > 0 AND
tmfu.max_date_sortie_mu != 'N.D.' AND tmfu_one_day1.min_date_entree_mu != 'N.D.' AND
tmfu.max_date_sortie_mu::date = tmfu_one_day1.min_date_entree_mu::date -'1 day'::interval
)
GROUP BY new_lot_id
),
t_bilan2 AS (
SELECT DISTINCT
tmfu.site_id, old_lot_id as lot_id, par_id, geom, mfu, tmfu.acte_id, tmfu.min_date_entree_mf, tmfu.max_date_sortie_mf, tmfu.min_date_entree_mu, tmfu.max_date_sortie_mu,
CASE WHEN tmfu.mfu = 'Acquisition' THEN tmfu.surf_acq ELSE 0 END AS surf_acqu,
CASE WHEN tmfu.mfu LIKE 'Convention%' THEN tmfu.surf_conv ELSE 0 END AS surf_conv,
tmfu.etat_bilan
FROM
tmfu_one_day2
JOIN tmfu ON (tmfu.lot_id = ANY(tbl_lot_one_day))
),
t_bilan3 AS (
SELECT
site_id, par_id, geom, mfu,
COALESCE(SUM(surf_acqu), 0) AS surf_acqu,
COALESCE(SUM(surf_conv), 0) AS surf_conv,
MAX(etat_bilan) AS etat_bilan
FROM (SELECT * FROM t_bilan1 UNION SELECT * FROM t_bilan2) as t
GROUP BY site_id, par_id, geom, mfu
HAVING SUM(surf_acqu) > 0 OR SUM(surf_conv) > 0
),
t_bilan4 AS (
SELECT DISTINCT
t_bilan3.par_id,
sites.site_id,
array_to_string(array_agg(DISTINCT mfu ORDER BY mfu), ' / ') as mfu,
SUM(CASE WHEN surf_acqu > 0 THEN surf_acqu ELSE surf_conv END) as surf_mfu,
MAX(geom) as geom,
etat_bilan
FROM
sites.sites
JOIN t_bilan3 USING (site_id)
GROUP BY t_bilan3.par_id, sites.site_id, t_bilan3.etat_bilan
)
SELECT
row_number() OVER (ORDER BY par_id) AS gid,
t_bilan4.*
FROM
t_bilan4
ORDER BY site_id, par_id """
uri.setDataSource("", u"(%s\n)" % sql, "geometrie", "", "gid")
layer = self.iface.addVectorLayer(uri.uri(), table_name, "postgres")
styleText = layer.getStyleFromDatabase(str(22))[0]
styleDoc = QDomDocument()
styleDoc.setContent(styleText)
layer.importNamedStyle(styleDoc)
self.dlg.close()
self.canvas.refresh()

View File

@ -0,0 +1,40 @@
# -*- coding: utf-8 -*-
"""
/***************************************************************************
BackinMFUDialog
A QGIS plugin
Permet de créer une nouvelle session d'animation foncière
-------------------
begin : 2015-10-02
git sha : $Format:%H$
copyright : (C) 2015 by CEN Savoie
email : a.lesconnec@cen-savoie.org
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
import os
import psycopg2
import psycopg2.extras
from PyQt5 import QtGui, uic
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QDialog
import datetime
from time import localtime, strftime
FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'backinMFU_dialog_base.ui'))
class BackinMFUDialog(QDialog, FORM_CLASS):
def __init__(self, parent=None):
"""Constructor."""
super(BackinMFUDialog, self).__init__(parent)
self.setupUi(self)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,14 @@
# Paramètres fixes de connexion à la base PostgreSQL
bd_cen_host = '91.134.194.220'
bd_cen_port = '5432'
bd_cen_name = 'bd_cen'
bd_cen_mdp_1st_cnx = 'McVities'
# Paramètres du serveur web
root_path = 'https://intranet.cenra-outils.org/Intranet/'
# Paramètres d'accès à OVH
bd_cen_host_ovh = '91.134.194.220'
bd_cen_port_ovh = '5432'
bd_cen_name_ovh = 'bd_cen'
mdp_1st_cnx_ovh = 'McVities'
bd_sicen_name = 'sicenra'

View File

@ -0,0 +1,7 @@
# Paramètres fixes de connexion à la base PostgreSQL
bd_cen_host = '192.168.100.4'
bd_cen_port = '5432'
bd_cen_name = 'bd_cen_savoie'
bd_cen_mdp_1st_cnx = 'first.com'
# Paramètres du serveur web
root_path = 'http://192.168.100.4/Cen_Savoie/Intranet/'

View File

@ -0,0 +1,623 @@
# -*- coding: utf-8 -*-
"""
/***************************************************************************
CreateSessionAF
A QGIS plugin
Permet de créer une nouvelle session d'animation foncière
-------------------
begin : 2015-10-02
git sha : $Format:%H$
copyright : (C) 2015 by CEN Savoie
email : a.lesconnec@cen-savoie.org
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QAction, QTableWidgetItem, QMessageBox
from qgis.core import *
# Initialize Qt resources from file resources.py
from pluginsCenSavoie_v3 import resources
# Import the code for the dialog
from pluginsCenSavoie_v3.tools.create_sessionAF_dialog import CreateSessionAFDialog
# Import du fichier de configuration
from pluginsCenSavoie_v3.tools.confPython import bd_cen_host, bd_cen_port, bd_cen_name, bd_cen_mdp_1st_cnx
import os.path
import sys
import qgis
import os
import psycopg2
import psycopg2.extras
import base64
import re
from time import localtime, strftime
class CreateSessionAF:
"""QGIS Plugin Implementation."""
def __init__(self, iface, cenToolbar):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgsInterface
"""
# Variable HOTE de l'accès à la base de données
global host
host = bd_cen_host
global port
port = bd_cen_port
global bdd
bdd = bd_cen_name
global mdp_1st_cnx
mdp_1st_cnx = bd_cen_mdp_1st_cnx
global os_user
if sys.platform == 'linux':
os_user = os.environ['USER']
else:
os_user = os.environ['USERNAME']
# Save reference to the QGIS interface
self.iface = iface
self.canvas = self.iface.mapCanvas()
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# Create the dialog (after translation) and keep reference
self.dlg = CreateSessionAFDialog()
# Add toolbar button
self.action= QAction(QIcon(":/plugins/pluginsCenSavoie_v3/icons/createSessionAF.png"), QCoreApplication.translate('CreateSessionAF', u'Créer une Session d''AF'), self.iface.mainWindow())
self.action.triggered.connect(self.run)
self.action.setEnabled(False)
cenToolbar.addAction(self.action)
self.canvas.selectionChanged.connect(self.toggle)
self.iface.layerTreeView().currentLayerChanged.connect(self.toggle)
def toggle(self):
layer = self.iface.activeLayer()
if layer and layer.type() == layer.VectorLayer:
if layer.selectedFeatureCount() > 0:
provider = layer.dataProvider()
source_postgis = provider.dataSourceUri()
source_postgis = source_postgis.replace('"', '')
if (source_postgis.count('table=animation_fonciere.parcelles_dispo_saf') == 1):
self.action.setEnabled(True)
else:
self.action.setEnabled(False)
else:
self.action.setEnabled(False)
else:
self.action.setEnabled(False)
def run(self):
"""Run method that performs all the real work"""
layer = self.iface.activeLayer()
if layer and layer.type() == layer.VectorLayer:
provider = layer.dataProvider()
source_postgis = provider.dataSourceUri()
source_postgis = source_postgis.replace('"', '')
if (source_postgis.count('table=animation_fonciere.parcelles_dispo_saf') != 1):
QMessageBox.critical(None, "Attention", "Vous devez sélectionnez des objets depuis la vue 'parcelles_dispo_saf'")
else:
if layer.selectedFeatureCount() < 1:
QMessageBox.critical(None, "Attention", "Vous devez sélectionnez au moins une parcelle")
else:
global user, mdp
first_conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=first_cnx password=" + mdp_1st_cnx)
first_cur = first_conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
first_cur.execute("SELECT mdp_cen, usename FROM pg_catalog.pg_user t1, admin_sig.utilisateurs t2 WHERE t2.oid = t1.usesysid AND (utilisateur_id = '" + os_user + "' OR utilisateur_os = '" + os_user + "')")
res_ident = first_cur.fetchone()
mdp = base64.b64decode(str(res_ident[0])).decode('utf-8')
user = res_ident[1]
first_conn.close()
self.dlg.tbl_parcelle.setColumnCount(3)
self.dlg.tbl_parcelle.setHorizontalHeaderItem(0, QTableWidgetItem('Par ID'))
self.dlg.tbl_parcelle.setHorizontalHeaderItem(1, QTableWidgetItem('Priorite'))
self.dlg.tbl_parcelle.setHorizontalHeaderItem(2, QTableWidgetItem('cad_site_id'))
self.dlg.tbl_parcelle.cellClicked.connect(self.changeCellValue)
site_id = []
self.canvas = self.iface.mapCanvas()
rowCount = 0
for feature in layer.selectedFeatures():
site_id.append(feature["site_id"])
rowCount += 1
self.dlg.tbl_parcelle.setRowCount(rowCount)
if rowCount > 0:
ligne = 0
col = 0
for feature in layer.selectedFeatures():
self.dlg.tbl_parcelle.setItem(ligne, 0, QTableWidgetItem(feature["par_id"]))
self.dlg.tbl_parcelle.setItem(ligne, 1, QTableWidgetItem('1'))
self.dlg.tbl_parcelle.setItem(ligne, 2, QTableWidgetItem(feature["tbl_cad_site_id"]))
ligne += 1
self.dlg.tbl_parcelle.setEnabled(True)
else:
self.dlg.tbl_parcelle.setEnabled(False)
self.dlg.tbl_parcelle.hideColumn(2)
self.dlg.tbl_parcelle.resizeColumnsToContents()
self.dlg.tbl_parcelle.sortItems(0, 0)
rq_saf_geom = "SELECT st_multi(st_union(geom)) as geom FROM animation_fonciere.parcelles_dispo_saf WHERE par_id IN ("
for feature in layer.selectedFeatures():
rq_saf_geom += "'" + str(feature["par_id"]) + "',"
rq_saf_geom = rq_saf_geom[0:(len(rq_saf_geom)-1)] + ")"
tbl_site_id = list(set(site_id))
self.dlg.InitFormulaire(tbl_site_id, rq_saf_geom, 'load', host, port, bdd, user, mdp)
self.dlg.img_logo.setPixmap(QPixmap(":/plugins/pluginsCenSavoie_v3/tools/images/Logo_CEN_Savoie.png"))
self.dlg.lbl_fond.setPixmap(QPixmap(":/plugins/pluginsCenSavoie_v3/tools/images/fond_70.png"))
self.dlg.lbl_fond.stackUnder(self.dlg.button_box)
# show the dialog
self.dlg.show()
# Run the dialog event loop
result = self.dlg.exec_()
# See if OK was pressed
if result:
curs = QCursor()
curs.setShape(Qt.WaitCursor)
qgis.utils.iface.mainWindow().centralWidget().setCursor(curs)
conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=" + user + " password=" + mdp)
cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
rq_dnuper = """
SELECT DISTINCT
t6.dnuper
FROM
cadastre.r_prop_cptprop_cen t6
JOIN cadastre.cptprop_cen t5 USING (dnupro)
JOIN cadastre.cadastre_cen t3 USING (dnupro)
JOIN cadastre.lots_cen t2 USING (lot_id)
WHERE
t6.dnuper NOT IN (
SELECT DISTINCT dnuper FROM animation_fonciere.rel_proprio_interloc WHERE dnuper IS NOT NULL
UNION
SELECT DISTINCT dnuper FROM animation_fonciere.interlocuteurs WHERE dnuper IS NOT NULL
) AND
t3.date_fin = 'N.D.' AND t2.par_id IN ("""
for r in range(self.dlg.tbl_parcelle.rowCount()):
if self.dlg.tbl_parcelle.isRowHidden(r) == False:
rq_dnuper += "'" + str(self.dlg.tbl_parcelle.item(r, 0).text()) + "',"
rq_dnuper = rq_dnuper[0:(len(rq_dnuper)-1)] + ")"
with conn:
with conn.cursor() as cur:
cur.execute(rq_dnuper)
res_dnuper = cur.fetchall()
i=0
while i < len(res_dnuper): #Boucle sur toutes les options de niveau 1
rq_check_dnuper_missed = """
WITH t1 AS (
SELECT nom_usage||'*$'||prenom_usage||'*$'||ccoqua||'*$'||REPLACE(jdatnss, '-', '')||'*$'||COALESCE(NULLIF(dldnss, ''), 'N.D.')||'*$'||dlign6 as check, dnuper FROM cadastre.proprios_cen
),
t_update AS (
UPDATE animation_fonciere.interlocuteurs
SET dnuper = t1.dnuper FROM t1
WHERE
interlocuteurs.dnuper IS NULL AND
t1.check = nom_usage||'*$'||prenom_usage||'*$'||ccoqua||'*$'||REPLACE(jdatnss, '-', '')||'*$'||COALESCE(NULLIF(dldnss, ''), 'N.D.')||'*$'||dlign6
RETURNING interlocuteurs.interloc_id, interlocuteurs.dnuper
)
INSERT INTO animation_fonciere.rel_proprio_interloc (SELECT dnuper, interloc_id FROM t_update WHERE dnuper || interloc_id::text NOT IN (SELECT dnuper || interloc_id::text
FROM animation_fonciere.rel_proprio_interloc))
RETURNING *"""
cur.execute(rq_check_dnuper_missed)
res_check_dnuper_missed = cur.fetchone()
if cur.rowcount == 0 :
rq_new_interloc_id = "SELECT nextval('animation_fonciere.interloc_id_seq'::regclass)";
cur.execute(rq_new_interloc_id)
res_new_interloc_id = cur.fetchone()
new_interloc_id = res_new_interloc_id[0]
rq_insert_interloc = """
INSERT INTO animation_fonciere.interlocuteurs (
interloc_id,
etat_interloc_id,
dnuper,
ccoqua,
ddenom,
nom_usage,
nom_naissance,
prenom_usage,
dnomlp,
dprnlp,
jdatnss,
dldnss,
dlign3,
dlign4,
dlign5,
dlign6,
email,
fixe_domicile,
fixe_travail,
portable_domicile,
portable_travail,
fax,
gtoper,
ccogrm,
dnatpr,
dsglpm,
commentaires,
annee_matrice,
maj_user,
maj_date,
dqualp,
dnomus,
dprnus,
dforme)
(SELECT
""" + str(new_interloc_id) + """,
1,
t1.dnuper,
t1.ccoqua,
t1.ddenom,
t1.nom_usage,
t1.nom_naissance,
t1.prenom_usage,
t1.dnomlp,
t1.dprnlp,
t1.jdatnss,
t1.dldnss,
t1.dlign3,
t1.dlign4,
t1.dlign5,
t1.dlign6,
t1.email,
t1.fixe_domicile,
t1.fixe_travail,
t1.portable_domicile,
t1.portable_travail,
t1.fax,
t1.gtoper,
t1.ccogrm,
t1.dnatpr,
t1.dsglpm,
t1.commentaires,
t1.annee_matrice,
t1.maj_user,
t1.maj_date,
t1.dqualp,
t1.dnomus,
t1.dprnus,
t1.dforme
FROM cadastre.proprios_cen t1
WHERE t1.dnuper = '""" + res_dnuper[i][0] + """')"""
cur.execute(rq_insert_interloc)
conn.commit()
rq_insert_rel_proprio_interloc = "INSERT INTO animation_fonciere.rel_proprio_interloc (dnuper, interloc_id) VALUES ('" + str(res_dnuper[i][0]) + "', " + str(new_interloc_id) + ")"
cur.execute(rq_insert_rel_proprio_interloc)
conn.commit()
i=i+1
if self.dlg.saf_maj.text() == 'N.P.':
rq_new_session_af_id = "SELECT nextval('animation_fonciere.session_af_id_seq'::regclass)";
cur.execute(rq_new_session_af_id)
res_new_session_af_id = cur.fetchone()
session_af_id = res_new_session_af_id[0]
rq_insert_saf = "INSERT INTO animation_fonciere.session_af (session_af_id, session_af_lib, date_creation, date_maj, utilisateur, origine_id, geom) VALUES (" + str(session_af_id) + ", '" + str(self.dlg.saf_name.text()) + "', '" + str(self.dlg.saf_date.text()) + "', '" + str(self.dlg.saf_date.text()) + "', '" + str(self.dlg.saf_utilisateur.text()) + "', '" + str(self.dlg.saf_origin.text()) + "', (" + str(rq_saf_geom) + "))"
cur.execute(rq_insert_saf)
conn.commit()
else :
session_af_id = self.dlg.saf_maj.text()
for r in range(self.dlg.tbl_parcelle.rowCount()):
for cad_site_id in self.dlg.tbl_parcelle.item(r, 2).text().split(','): #Pour chaque cad_site_id
rq_check_cad_site_id = """
SELECT entite_af_id
FROM
animation_fonciere.rel_eaf_foncier
JOIN animation_fonciere.rel_saf_foncier USING (rel_eaf_foncier_id)
WHERE cad_site_id = """ + str(cad_site_id) + """ AND session_af_id = """ + str(session_af_id)
cur.execute(rq_check_cad_site_id)
if cur.rowcount == 0:
#On recherche si une entite_af_id existe avec les propriétaires de la parcelle
rq_check_entite_af_id = "SELECT COALESCE(animation_fonciere.f_get_eaf("+str(cad_site_id)+"), 0)"
cur.execute(rq_check_entite_af_id)
res_check_entite_af_id = cur.fetchone()
if cur.rowcount == 1 and res_check_entite_af_id[0] != 0: #si une EAF est trouvée
entite_af_id = res_check_entite_af_id[0]
elif cur.rowcount == 1 and res_check_entite_af_id[0] == 0: #sinon il faut tout ajouter
rq_new_eaf_id = "SELECT nextval('animation_fonciere.entite_af_id_seq'::regclass)";
cur.execute(rq_new_eaf_id)
res_new_eaf_id = cur.fetchone()
entite_af_id = res_new_eaf_id[0]
rq_insert_entite_af = "INSERT INTO animation_fonciere.entite_af (entite_af_id) VALUES (" + str(entite_af_id) + ")"
cur.execute(rq_insert_entite_af)
conn.commit()
else:
entite_af_id = 0
#On recherche si un rel_eaf_foncier_id existe pour la parcelle dans cette EAF
rq_check_rel_eaf_foncier_id = "SELECT rel_eaf_foncier_id FROM animation_fonciere.rel_eaf_foncier WHERE cad_site_id = "+str(cad_site_id)+" AND entite_af_id = "+str(entite_af_id)
cur.execute(rq_check_rel_eaf_foncier_id)
res_check_rel_eaf_foncier_id = cur.fetchone()
if cur.rowcount == 1 : #si un rel_eaf_foncier_id est trouvé
rel_eaf_foncier_id = res_check_rel_eaf_foncier_id[0]
elif cur.rowcount == 0 : #sinon il faut l'ajouter
rq_new_rel_eaf_foncier_id = "SELECT nextval('animation_fonciere.rel_eaf_foncier_id_seq'::regclass)";
cur.execute(rq_new_rel_eaf_foncier_id)
res_new_rel_eaf_foncier_id = cur.fetchone()
rel_eaf_foncier_id = res_new_rel_eaf_foncier_id[0]
rq_insert_rel_eaf_foncier = "INSERT INTO animation_fonciere.rel_eaf_foncier (rel_eaf_foncier_id, cad_site_id, entite_af_id) VALUES (" +str(rel_eaf_foncier_id)+","+str(cad_site_id)+","+str(entite_af_id)+")"
cur.execute(rq_insert_rel_eaf_foncier)
conn.commit()
else:
rel_eaf_foncier_id = 0
#On recherche si un rel_saf_foncier_id existe pour la parcelle dans cette EAF dans cette SAF
rq_check_rel_saf_foncier = "SELECT rel_saf_foncier_id FROM animation_fonciere.rel_saf_foncier WHERE rel_eaf_foncier_id = " + str(rel_eaf_foncier_id) + " AND session_af_id = " + str(session_af_id)
cur.execute(rq_check_rel_saf_foncier)
res_check_rel_saf_foncier = cur.fetchone()
if cur.rowcount == 1 : #si un rel_saf_foncier_id est trouvé
rel_saf_foncier_id = res_check_rel_saf_foncier[0]
elif cur.rowcount == 0 : #sinon il faut tout ajouter
rq_new_rel_saf_foncier_id = "SELECT nextval('animation_fonciere.rel_saf_foncier_id_seq'::regclass)";
cur.execute(rq_new_rel_saf_foncier_id)
res_new_rel_saf_foncier_id = cur.fetchone()
rel_saf_foncier_id = res_new_rel_saf_foncier_id[0]
rq_insert_rel_saf_foncier = "INSERT INTO animation_fonciere.rel_saf_foncier (rel_saf_foncier_id, rel_eaf_foncier_id, session_af_id, paf_id) VALUES (" + str(rel_saf_foncier_id) + "," + str(rel_eaf_foncier_id) + "," + str(session_af_id) + ", " + str(self.dlg.tbl_parcelle.item(r, 1).text()) + ")"
cur.execute(rq_insert_rel_saf_foncier)
conn.commit()
else:
rel_saf_foncier_id = 0
rq_lst_interloc_id = """
SELECT DISTINCT
interloc_id,
COALESCE(ccodro, 'N.P.') as ccodro,
COALESCE(ccodem, 'N.P.') as ccodem,
etat_interloc_id
FROM
animation_fonciere.rel_proprio_interloc
JOIN animation_fonciere.interlocuteurs USING (interloc_id)
JOIN cadastre.proprios_cen ON (proprios_cen.dnuper = interlocuteurs.dnuper OR proprios_cen.dnuper = rel_proprio_interloc.dnuper)
JOIN cadastre.r_prop_cptprop_cen ON (r_prop_cptprop_cen.dnuper = proprios_cen.dnuper)
JOIN cadastre.cptprop_cen USING (dnupro)
JOIN cadastre.cadastre_cen USING (dnupro)
JOIN foncier.cadastre_site USING (cad_cen_id)
WHERE cad_site_id = """ + str(cad_site_id)
cur.execute(rq_lst_interloc_id)
res_lst_interloc_id = cur.fetchall()
i=0
while i < len(res_lst_interloc_id):
if (res_lst_interloc_id[i][3] == 4):
type_interloc_id = 21
else:
type_interloc_id = 1
rq_check_rel_saf_foncier_interlocs = """
SELECT
rel_saf_foncier_interlocs_id
FROM
animation_fonciere.rel_saf_foncier_interlocs
WHERE
interloc_id = """ + str(res_lst_interloc_id[i][0]) + """ AND
rel_saf_foncier_id = """ + str(rel_saf_foncier_id) + """ AND type_interloc_id IN (1, 21)"""
cur.execute(rq_check_rel_saf_foncier_interlocs)
res_check_rel_saf_foncier_interlocs = cur.fetchone()
if cur.rowcount == 0 :
rq_insert_rel_saf_foncier_interlocs = "INSERT INTO animation_fonciere.rel_saf_foncier_interlocs (interloc_id, rel_saf_foncier_id, type_interloc_id, ccodro, ccodem) VALUES (" + str(res_lst_interloc_id[i][0]) + "," + str(rel_saf_foncier_id)+", " + str(type_interloc_id) + ", CASE WHEN '" + str(res_lst_interloc_id[i][1]) + "' = 'N.P.' THEN NULL ELSE '" + str(res_lst_interloc_id[i][1]) + "' END, CASE WHEN '" + str(res_lst_interloc_id[i][2]) + "' = 'N.P.' THEN NULL ELSE '" + str(res_lst_interloc_id[i][2]) + "' END)"
cur.execute(rq_insert_rel_saf_foncier_interlocs)
conn.commit()
i=i+1
rq_lst_interloc_id = """
SELECT DISTINCT
interloc_id,
type_interloc_id
FROM
animation_fonciere.interlocuteurs
JOIN animation_fonciere.rel_saf_foncier_interlocs USING (interloc_id)
JOIN animation_fonciere.rel_saf_foncier USING (rel_saf_foncier_id)
JOIN animation_fonciere.rel_eaf_foncier USING (rel_eaf_foncier_id)
JOIN animation_fonciere.d_type_interloc USING (type_interloc_id)
JOIN animation_fonciere.d_groupe_interloc USING (groupe_interloc_id)
WHERE type_interloc_id NOT IN (1, 2) AND all_eaf = 't' AND entite_af_id = """ + str(entite_af_id)
cur.execute(rq_lst_interloc_id)
res_lst_interloc_id = cur.fetchall()
i=0
while i < len(res_lst_interloc_id):
rq_check_rel_saf_foncier_interlocs = """
SELECT
rel_saf_foncier_interlocs_id
FROM
animation_fonciere.rel_saf_foncier_interlocs
WHERE
interloc_id = """ + str(res_lst_interloc_id[i][0]) + """ AND
rel_saf_foncier_id = """ + str(rel_saf_foncier_id) + """ AND type_interloc_id =""" + str(res_lst_interloc_id[i][1])
cur.execute(rq_check_rel_saf_foncier_interlocs)
res_check_rel_saf_foncier_interlocs = cur.fetchone()
if cur.rowcount == 0 :
rq_insert_rel_saf_foncier_interlocs = "INSERT INTO animation_fonciere.rel_saf_foncier_interlocs (interloc_id, rel_saf_foncier_id, type_interloc_id, ccodro, ccodem) VALUES (" + str(res_lst_interloc_id[i][0]) + "," + str(rel_saf_foncier_id)+", " + str(res_lst_interloc_id[i][1]) + ", NULL, NULL)"
cur.execute(rq_insert_rel_saf_foncier_interlocs)
conn.commit()
i=i+1
i=0
while i < len(res_lst_interloc_id):
# Après avoir éventuellement ajouter des parcelles, on vérifie ses relations au sein de l'EAF pour mettre à jour automatiquement les table interloc_referent et interloc_substitution
# L'interlocuteur est représenté par quelqu'un
rq_insert_interloc_substitution = """
WITH t1 AS (
SELECT DISTINCT
rel_saf_foncier_interlocs.rel_saf_foncier_interlocs_id,
rel_saf_foncier_interlocs.rel_saf_foncier_id,
CASE WHEN rel_saf_foncier_interlocs_id IN (SELECT rel_saf_foncier_interlocs_id_vp FROM animation_fonciere.interloc_substitution) THEN 'assoc' ELSE 'N.D.' END as eval
FROM
animation_fonciere.rel_saf_foncier_interlocs
JOIN animation_fonciere.d_type_interloc USING (type_interloc_id)
JOIN animation_fonciere.d_groupe_interloc USING (groupe_interloc_id)
JOIN animation_fonciere.rel_saf_foncier USING (rel_saf_foncier_id)
JOIN animation_fonciere.rel_eaf_foncier USING (rel_eaf_foncier_id)
WHERE
session_af_id = """ + str(session_af_id) + """ AND
entite_af_id = """ + str(entite_af_id) + """ AND
interloc_id = """ + str(res_lst_interloc_id[i][0]) + """ AND
can_be_under_subst = 't'
),
t_subst AS (
SELECT DISTINCT interloc_id
FROM
t1
JOIN animation_fonciere.rel_saf_foncier_interlocs USING (rel_saf_foncier_id)
JOIN animation_fonciere.interloc_substitution ON (rel_saf_foncier_interlocs_id_is = rel_saf_foncier_interlocs.rel_saf_foncier_interlocs_id)
WHERE t1.eval = 'assoc'
),
t2 AS (
SELECT DISTINCT
rel_saf_foncier_interlocs.rel_saf_foncier_interlocs_id,
rel_saf_foncier_interlocs.rel_saf_foncier_id,
rel_saf_foncier_interlocs.interloc_id
FROM
animation_fonciere.rel_saf_foncier_interlocs
JOIN animation_fonciere.rel_saf_foncier USING (rel_saf_foncier_id)
JOIN animation_fonciere.rel_eaf_foncier USING (rel_eaf_foncier_id)
JOIN t_subst USING (interloc_id)
)
INSERT INTO animation_fonciere.interloc_substitution (
SELECT
t1.rel_saf_foncier_interlocs_id as rel_saf_foncier_interlocs_id_vp,
t2.rel_saf_foncier_interlocs_id as rel_saf_foncier_interlocs_id_is
FROM
t1
JOIN t2 USING (rel_saf_foncier_id)
WHERE t1.eval = 'N.D.'
)"""
cur.execute(rq_insert_interloc_substitution)
conn.commit()
# L'interlocuteur est référencé par quelqu'un
rq_insert_interloc_referent = """
WITH t1 AS (
SELECT DISTINCT
rel_saf_foncier_interlocs.rel_saf_foncier_interlocs_id,
rel_saf_foncier_interlocs.rel_saf_foncier_id,
CASE WHEN rel_saf_foncier_interlocs_id IN (SELECT rel_saf_foncier_interlocs_id FROM animation_fonciere.interloc_referent) THEN 'assoc' ELSE 'N.D.' END as eval
FROM
animation_fonciere.rel_saf_foncier_interlocs
JOIN animation_fonciere.d_type_interloc USING (type_interloc_id)
JOIN animation_fonciere.d_groupe_interloc USING (groupe_interloc_id)
JOIN animation_fonciere.rel_saf_foncier USING (rel_saf_foncier_id)
JOIN animation_fonciere.rel_eaf_foncier USING (rel_eaf_foncier_id)
WHERE
session_af_id = """ + str(session_af_id) + """ AND
entite_af_id = """ + str(entite_af_id) + """ AND
interloc_id = """ + str(res_lst_interloc_id[i][0]) + """ AND
can_be_under_ref = 't'
),
t_ref AS (
SELECT DISTINCT interloc_id
FROM
t1
JOIN animation_fonciere.rel_saf_foncier_interlocs USING (rel_saf_foncier_id)
JOIN animation_fonciere.interloc_referent ON (rel_saf_foncier_interlocs_id_ref = rel_saf_foncier_interlocs.rel_saf_foncier_interlocs_id)
WHERE t1.eval = 'assoc'
),
t2 AS (
SELECT DISTINCT
rel_saf_foncier_interlocs.rel_saf_foncier_interlocs_id,
rel_saf_foncier_interlocs.rel_saf_foncier_id,
rel_saf_foncier_interlocs.interloc_id
FROM
animation_fonciere.rel_saf_foncier_interlocs
JOIN animation_fonciere.rel_saf_foncier USING (rel_saf_foncier_id)
JOIN animation_fonciere.rel_eaf_foncier USING (rel_eaf_foncier_id)
JOIN t_ref USING (interloc_id)
)
INSERT INTO animation_fonciere.interloc_referent (
SELECT
t2.rel_saf_foncier_interlocs_id as rel_saf_foncier_interlocs_id_ref,
t1.rel_saf_foncier_interlocs_id
FROM
t1
JOIN t2 USING (rel_saf_foncier_id)
WHERE t1.eval = 'N.D.'
)"""
cur.execute(rq_insert_interloc_referent)
conn.commit()
i=i+1
if self.dlg.saf_maj.text() != 'N.P.':
rq_update_saf_geom = """
UPDATE animation_fonciere.session_af SET geom = (
SELECT
st_multi(st_union(t1.geom)) as geom
FROM
cadastre.lots_cen t2
JOIN cadastre.parcelles_cen t1 USING (par_id)
JOIN cadastre.cadastre_cen t3 USING (lot_id)
JOIN foncier.cadastre_site t4 USING (cad_cen_id)
JOIN animation_fonciere.rel_eaf_foncier USING (cad_site_id)
JOIN animation_fonciere.rel_saf_foncier USING (rel_eaf_foncier_id)
WHERE
rel_saf_foncier.session_af_id = """+str(session_af_id)+""" AND
t3.date_fin = 'N.D.' AND
t4.date_fin = 'N.D.')
WHERE session_af_id = """+str(session_af_id)
cur.execute(rq_update_saf_geom)
conn.commit()
rq_clean_eaf = "SELECT animation_fonciere.f_clean_eaf()";
test = 'NOT OK'
eaf=0
while test != 'OK':
cur.execute(rq_clean_eaf)
if (cur.rowcount == 0 or eaf > 25) :
test = 'OK'
eaf=eaf+1
curs = QCursor()
curs.setShape(Qt.ArrowCursor)
qgis.utils.iface.mainWindow().centralWidget().setCursor(curs)
self.canvas.refresh()
else:
QMessageBox.critical(None, "Attention", "Vous devez sélectionnez des objets depuis la vue 'parcelles_dispo_saf'")
def changeCellValue(self, ligne, col):
conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=" + user + " password=" + mdp)
cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
if self.dlg.tbl_parcelle.item(ligne, 1).text() == '1' and col != 0:
self.dlg.tbl_parcelle.setItem(ligne, 1, QTableWidgetItem('2'))
elif self.dlg.tbl_parcelle.item(ligne, 1).text() == '2' and col != 0:
self.dlg.tbl_parcelle.setItem(ligne, 1, QTableWidgetItem('3'))
elif self.dlg.tbl_parcelle.item(ligne, 1).text() == '3' and col != 0:
self.dlg.tbl_parcelle.setItem(ligne, 1, QTableWidgetItem('1'))
if col == 0:
feature_gid = self.dlg.tbl_parcelle.item(ligne, 0).text()
with conn:
with conn.cursor() as cur:
cur.execute("SELECT st_xmin(st_buffer(t1.geom,10)) as xmin, st_xmax(st_buffer(t1.geom,10)) as xmax, st_ymin(st_buffer(t1.geom,10)) as ymin, st_ymax(st_buffer(t1.geom,10)) as ymax FROM animation_fonciere.parcelles_dispo_saf t1 WHERE t1.par_id = '"+ self.dlg.tbl_parcelle.item(ligne, 0).text() + "'")
coord = cur.fetchone()
xmin = coord[0]
ymin = coord[2]
xmax = coord[1]
ymax = coord[3]
self.canvas.setExtent(QgsRectangle(xmin, ymin, xmax, ymax))
self.canvas.refresh()
self.dlg.tbl_parcelle.item(ligne, col).setSelected(False)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,58 @@
# -*- coding: utf-8 -*-
"""
/***************************************************************************
CreateSessionAF
A QGIS plugin
Permet de créer une nouvelle session d'animation foncière
-------------------
begin : 2015-10-02
git sha : $Format:%H$
copyright : (C) 2015 by CEN Savoie
email : a.lesconnec@cen-savoie.org
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QAction
from qgis.core import *
# Initialize Qt resources from file resources.py
from pluginsCenSavoie_v3 import resources
# Import du fichier de configuration
from pluginsCenSavoie_v3.tools.confPython import root_path
import os.path
import sys
import qgis
import os
import webbrowser
class help:
"""QGIS Plugin Implementation."""
def __init__(self, iface, cenToolbar):
# Save reference to the QGIS interface
self.iface = iface
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# Add toolbar button
self.action= QAction(QIcon(":/plugins/pluginsCenSavoie_v3/icons/help.png"), QCoreApplication.translate('help', u'Aide sur les plugins du CEN Savoie'), self.iface.mainWindow())
self.action.triggered.connect(self.run)
cenToolbar.addAction(self.action)
def run(self):
url= root_path+"sig/guide/outils_qgis.php#plugins"
webbrowser.open_new(url)

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 513 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

View File

@ -0,0 +1,378 @@
# -*- coding: utf-8 -*-
"""
/***************************************************************************
ParcelleToActe
A QGIS plugin
Permet d'associer des parcelles à des actes
-------------------
begin : 2015-06-19
git sha : $Format:%H$
copyright : (C) 2015 by CEN Savoie
email : a.lesconnec@cen-savoie.org
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QAction, QTableWidgetItem, QMessageBox
# Initialize Qt resources from file resources.py
from pluginsCenSavoie_v3 import resources
# Import the code for the dialog
from pluginsCenSavoie_v3.tools.parcelle_to_acte_dialog import ParcelleToActeDialog
# Import du fichier de configuration
from pluginsCenSavoie_v3.tools.confPython import bd_cen_host, bd_cen_port, bd_cen_name, bd_cen_mdp_1st_cnx
import os.path
import sys
import qgis
import os
import psycopg2
import psycopg2.extras
import base64
import re
from time import localtime, strftime
class ParcelleToActe:
"""QGIS Plugin Implementation."""
def __init__(self, iface, cenToolbar):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgsInterface
"""
# Variable HOTE de l'accès à la base de données
global host
host = bd_cen_host
global port
port = bd_cen_port
global bdd
bdd = bd_cen_name
global mdp_1st_cnx
mdp_1st_cnx = bd_cen_mdp_1st_cnx
global os_user
if sys.platform == 'linux':
os_user = os.environ['USER']
else:
os_user = os.environ['USERNAME']
# Save reference to the QGIS interface
self.iface = iface
self.canvas = self.iface.mapCanvas()
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# Create the dialog (after translation) and keep reference
self.dlg = ParcelleToActeDialog()
# Add toolbar button
self.action= QAction(QIcon(":/plugins/pluginsCenSavoie_v3/icons/parcelleToActe.png"), QCoreApplication.translate('ParcelleToActe', u'Associer des parcelles à un acte'), self.iface.mainWindow())
self.action.triggered.connect(self.run)
self.action.setEnabled(False)
cenToolbar.addAction(self.action)
self.canvas.selectionChanged.connect(self.toggle)
self.iface.layerTreeView().currentLayerChanged.connect(self.toggle)
def toggle(self):
layer = self.iface.activeLayer()
if layer and layer.type() == layer.VectorLayer:
if layer.selectedFeatureCount() > 0:
provider = layer.dataProvider()
source_postgis = provider.dataSourceUri()
source_postgis = source_postgis.replace('"', '')
if (source_postgis.count('table=foncier.parcelles_dispo ') == 1):
self.action.setEnabled(True)
else:
self.action.setEnabled(False)
else:
self.action.setEnabled(False)
else:
self.action.setEnabled(False)
def changeCellValue(self, ligne, col):
self.dlg.tbl_detail.blockSignals(True)
if self.dlg.tbl_detail.item(ligne, 2).text() == 'OUI' and col != 0:
self.dlg.tbl_detail.setItem(ligne, 2, QTableWidgetItem('NON'))
self.dlg.tbl_detail.item(ligne, 1).setBackground(QtGui.QColor(255, 145, 145))
self.dlg.tbl_detail.item(ligne, 2).setBackground(QtGui.QColor(255, 145, 145))
elif self.dlg.tbl_detail.item(ligne, 2).text() == 'NON' and col != 0:
self.dlg.tbl_detail.setItem(ligne, 2, QTableWidgetItem('OUI'))
self.dlg.tbl_detail.item(ligne, 1).setBackground(QtGui.QColor(115, 215, 115))
self.dlg.tbl_detail.item(ligne, 2).setBackground(QtGui.QColor(115, 215, 115))
self.dlg.tbl_detail.item(ligne, col).setSelected(False)
self.dlg.tbl_detail.blockSignals(False)
def chg_date_modif(self):
self.dlg.cal_date_modif.setEnabled(True)
self.dlg.cal_date_modif.setVisible(1)
def chg_cal_date_modif(self, date):
current_date_modif = date.toString('yyyy-MM-dd')
self.dlg.date_modif.setText(str(current_date_modif))
self.dlg.cal_date_modif.setEnabled(False)
self.dlg.cal_date_modif.setVisible(0)
if self.dlg.lst_actes.currentIndex() != -1 and self.dlg.date_modif.text() != 'N.P.' and self.dlg.lst_motif_maj.currentIndex() != -1 :
self.dlg.button_box.setEnabled(True)
else:
self.dlg.button_box.setEnabled(False)
def run(self):
"""Run method that performs all the real work"""
# initialise le contenant du formulaire
self.dlg.tbl_detail.setColumnCount(4)
self.dlg.tbl_detail.setHorizontalHeaderItem(0, QTableWidgetItem('Par ID'))
self.dlg.tbl_detail.setHorizontalHeaderItem(1, QTableWidgetItem('Lot ID'))
self.dlg.tbl_detail.setHorizontalHeaderItem(2, QTableWidgetItem('A Associer'))
self.dlg.tbl_detail.setHorizontalHeaderItem(3, QTableWidgetItem('cad_site_id'))
self.dlg.tbl_detail.setColumnHidden(3, True)
self.dlg.btn_date_modif.clicked.connect(self.chg_date_modif)
self.dlg.cal_date_modif.clicked.connect(self.chg_cal_date_modif)
self.dlg.tbl_detail.cellClicked.connect(self.changeCellValue)
first_conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=first_cnx password=" + mdp_1st_cnx)
first_cur = first_conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
first_cur.execute("SELECT mdp_cen, usename FROM pg_catalog.pg_user t1, admin_sig.utilisateurs t2 WHERE t2.oid = t1.usesysid AND (utilisateur_id = '" + os_user + "' OR utilisateur_os = '" + os_user + "')")
res_ident = first_cur.fetchone()
mdp = base64.b64decode(str(res_ident[0])).decode('utf-8')
user = res_ident[1]
conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=" + user + " password=" + mdp)
cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
first_conn.close()
site_id = []
tbl_dnulot = []
tbl_cad_site_id = []
self.canvas = self.iface.mapCanvas()
global layer
layer = self.iface.activeLayer()
rowCount = 0
for feature in layer.selectedFeatures():
site_id.append(feature["site_id"])
tbl_dnulot = re.split(',', feature["tbl_dnulot"])
if len(tbl_dnulot) > 0:
j = 0
while j < len(tbl_dnulot):
rowCount += 1
j+=1
self.dlg.tbl_detail.setRowCount(rowCount)
for id_site in site_id:
rq_lst_sites_around = """
SELECT site_id
FROM sites.sites
WHERE st_distance(geom_ecolo, (SELECT geom_ecolo FROM sites.sites WHERE site_id = '"""+id_site+"""')) < 1000 AND site_id != '"""+id_site+"""'
"""
with conn:
with conn.cursor() as cur:
cur.execute(rq_lst_sites_around)
res_lst_sites_around = cur.fetchall()
site_id_around = []
if len(res_lst_sites_around) > 0:
i = 0
while i < len(res_lst_sites_around):
if res_lst_sites_around[i][0] not in site_id and res_lst_sites_around[i][0] not in site_id_around:
site_id_around.append(res_lst_sites_around[i][0])
i=i+1
site_id = [*site_id, *site_id_around]
if rowCount > 0:
ligne = 0
col = 0
for feature in layer.selectedFeatures():
tbl_dnulot = re.split(',', feature["tbl_dnulot"])
tbl_cad_site_id = re.split(',', feature["tbl_cad_site_id"])
if len(tbl_dnulot) > 0:
self.dlg.tbl_detail.setItem(ligne, 0, QTableWidgetItem(feature["par_id"]))
self.dlg.tbl_detail.setSpan(ligne, 0, len(tbl_dnulot), 1)
j = 0
while j < len(tbl_dnulot):
self.dlg.tbl_detail.setItem(ligne, 1, QTableWidgetItem(tbl_dnulot[j]))
self.dlg.tbl_detail.item(ligne, 1).setBackground(QtGui.QColor(115, 215, 115))
self.dlg.tbl_detail.setItem(ligne, 2, QTableWidgetItem('OUI'))
self.dlg.tbl_detail.item(ligne, 2).setBackground(QtGui.QColor(115, 215, 115))
self.dlg.tbl_detail.setItem(ligne, 3, QTableWidgetItem(tbl_cad_site_id[j]))
ligne += 1
j+=1
self.dlg.tbl_detail.setEnabled(True)
self.dlg.no_lot.setVisible(0)
else:
self.dlg.tbl_detail.setEnabled(False)
self.dlg.no_lot.setVisible(1)
self.dlg.tbl_detail.resizeColumnsToContents()
if (len(set(site_id)) < 1):
QMessageBox.warning(None, "Oups:", 'Selection invalide')
else:
tbl_site_id = list(set(site_id))
self.dlg.InitFormulaire(tbl_site_id, 'load', user, mdp)
self.dlg.img_logo.setPixmap(QPixmap(":/plugins/pluginsCenSavoie_v3/tools/images/Logo_CEN_Savoie.png"))
self.dlg.lbl_fond.setPixmap(QPixmap("%s/images/fond_70.png"%self.plugin_dir))
self.dlg.lbl_fond.stackUnder(self.dlg.button_box)
# show the dialog
self.dlg.show()
# Run the dialog event loop
result = self.dlg.exec_()
# See if OK was pressed
if result:
curs = QCursor()
curs.setShape(Qt.WaitCursor)
qgis.utils.iface.mainWindow().centralWidget().setCursor(curs)
mfu_id = self.dlg.lst_actes.currentText()
motif_maj_id = self.dlg.motif_maj_id.text()
mfu_table = self.dlg.type_acte_sel.text()
aujourdhui = strftime("%Y-%m-%d %H:%M:%S", localtime())
date_modif = self.dlg.date_modif.text()
maj_table = 'NON'
with conn:
with conn.cursor() as cur:
rq_check_droit = """
WITH RECURSIVE t(oid) AS (
VALUES ((SELECT oid FROM admin_sig.utilisateurs WHERE utilisateur_id = '""" + os_user + """' OR utilisateur_os = '""" + os_user + """'))
UNION ALL
SELECT grosysid
FROM pg_catalog.pg_group JOIN t ON (t.oid = ANY (grolist))
),
t_group AS (
SELECT DISTINCT groname
FROM pg_catalog.pg_group JOIN t ON (t.oid = pg_group.grosysid))
SELECT
count(*) FILTER (WHERE grant_elt_id = 3 AND grant_group_droit = 't' AND grant_group_id IN (groname)) as parc
FROM foncier.grant_group JOIN t_group ON (groname = grant_group_id)"""
cur.execute(rq_check_droit)
can_parc_site = cur.fetchone()
if can_parc_site[0] == 0:
QMessageBox.warning(None, "ERROR:", """Le traitement a échoué<br>Vous n'êtes pas autorisé à modifier la liste des parcelles d'un acte""")
else:
rq_statut_mfu = "SELECT statutmfu_id AS statut_id FROM alertes.v_tdb_mfu WHERE mfu_id = '"+mfu_id+"'"
cur.execute(rq_statut_mfu)
statut_mfu = cur.fetchone()
if (int(statut_mfu[0]) == 0):
date_modif = '0000-00-00'
else:
date_modif = date_modif + ' 00:00:00'
if mfu_table == 'r_cad_site_mf':
rq_date_debut_acte = "SELECT date_sign_acte FROM foncier.mf_acquisitions WHERE mf_id = '"+mfu_id+"'"
suffixe = 'mf'
else:
rq_date_debut_acte = "SELECT date_effet_conv FROM foncier.mu_conventions WHERE mu_id = '"+mfu_id+"'"
suffixe = 'mu'
error_date = 'RAS'
tbl_cad_site_id = []
for i in range(self.dlg.tbl_detail.rowCount()):
tbl_cad_site_id.append(self.dlg.tbl_detail.item(i, 3).text())
lst_cad_site_id = ','.join(tbl_cad_site_id)
rq_check_mfu = """
WITH t1 AS (
SELECT cad_site_id
FROM
alertes.v_tdb_mfu
JOIN foncier.r_cad_site_mu ON (mu_id = mfu_id)
WHERE statutmfu_id = 1
UNION
SELECT cad_site_id
FROM
alertes.v_tdb_mfu
JOIN foncier.r_cad_site_mf ON (mf_id = mfu_id)
WHERE statutmfu_id = 1
)
SELECT cad_site_id FROM t1 WHERE cad_site_id IN (""" + str(lst_cad_site_id) + """)"""
cur.execute(rq_check_mfu)
res_check_mfu = cur.fetchall()
if len(res_check_mfu) > 0 and int(statut_mfu[0]) == 1:
error_date = 'PROB'
QMessageBox.warning(None, "ERROR:", """Le traitement a échoué<br>Au moins une parcelle est déjà maitrisée""")
elif int(motif_maj_id) in [3, 10]:
rq_check_date = """
SELECT
cad_site_id
FROM
foncier.cadastre_site
JOIN cadastre.cadastre_cen USING (cad_cen_id)
WHERE
cad_site_id IN (""" + str(lst_cad_site_id) + """) AND
'"""+date_modif+"""'::character varying(10) < ("""+rq_date_debut_acte+""")::character varying(10)"""
cur.execute(rq_check_date)
res_check_date = cur.fetchall()
if len(res_check_date) > 0:
error_date = 'PROB'
QMessageBox.warning(None, "ERROR:", """Le traitement a échoué<br>Au moins une parcelle ajoutée avant la création de l'acte""")
elif int(motif_maj_id) == 9:
rq_check_date = """
SELECT
cad_site_id
FROM
foncier.cadastre_site
JOIN cadastre.cadastre_cen USING (cad_cen_id)
WHERE
cad_site_id IN ("""+str(lst_cad_site_id)+""") AND
cadastre_cen.date_deb::character varying(10) < ("""+rq_date_debut_acte+""")::character varying(10)"""
cur.execute(rq_check_date)
res_check_date = cur.fetchall()
if len(res_check_date) > 0:
error_date = 'PROB'
QMessageBox.warning(None, "ERROR:", """Le traitement a échoué<br>Au moins une parcelle ajoutée avant la création de l'acte""")
if error_date == 'RAS':
rq_ajout = "INSERT INTO foncier.r_cad_site_"+suffixe+" (cad_site_id, "+suffixe+"_id, date_entree, date_sortie, motif_entree_id, motif_sortie_id) VALUES ";
for i in range(self.dlg.tbl_detail.rowCount()):
if self.dlg.tbl_detail.item(i, 2).text() == 'OUI':
if int(motif_maj_id) == 1 and int(statut_mfu[0]) != 0:
rq_ajout += "("+self.dlg.tbl_detail.item(i, 3).text()+", '"+mfu_id+"', ("+rq_date_debut_acte+"), 'N.D.', "+motif_maj_id+", 1), "
elif int(motif_maj_id) == 9:
rq_ajout += "("+self.dlg.tbl_detail.item(i, 3).text()+", '"+mfu_id+"', (SELECT cadastre_cen.date_deb FROM cadastre.cadastre_cen JOIN foncier.cadastre_site USING (cad_cen_id) WHERE cad_site_id = "+self.dlg.tbl_detail.item(i, 3).text()+"), 'N.D.', "+motif_maj_id+", 1), "
else:
rq_ajout += "("+self.dlg.tbl_detail.item(i, 3).text()+", '"+mfu_id+"', '"+date_modif+"', 'N.D.', "+motif_maj_id+", 1), "
if rq_ajout[-2:] == ', ':
rq_ajout = rq_ajout[0:-2]
if self.dlg.tbl_detail.rowCount() > 0 and rq_ajout != "INSERT INTO foncier.r_cad_site_"+suffixe+" (cad_site_id, "+suffixe+"_id, date_entree, date_sortie, motif_entree_id, motif_sortie_id) VALUES ":
cur.execute(rq_ajout)
conn.commit()
maj_table = 'OUI'
if maj_table == 'OUI':
rq_refresh = """
WITH t1 AS (
SELECT array_to_string(array_agg(DISTINCT site_id), ',') as lst_site_id
FROM
foncier."""+mfu_table+"""
JOIN foncier.cadastre_site USING (cad_site_id)
WHERE """+mfu_table[len(mfu_table)-2:len(mfu_table)]+"""_id = '"""+mfu_id+"""'
)
SELECT admin_sig.refresh_mview_foncier(t1.lst_site_id) FROM t1"""
cur.execute(rq_refresh)
conn.commit()
if mfu_table == 'r_cad_site_mu':
rq_update = "UPDATE foncier.mu_conventions SET maj_date = '"+aujourdhui+"', maj_user = '"+os_user+"' WHERE mu_id = '"+mfu_id+"'"
elif mfu_table == 'r_cad_site_mf':
rq_update = "UPDATE foncier.mf_acquisitions SET maj_date = '"+aujourdhui+"', maj_user = '"+os_user+"' WHERE mf_id = '"+mfu_id+"'"
cur.execute(rq_update)
conn.commit()
curs = QCursor()
curs.setShape(Qt.ArrowCursor)
qgis.utils.iface.mainWindow().centralWidget().setCursor(curs)
self.canvas.refresh()

View File

@ -0,0 +1,238 @@
# -*- coding: utf-8 -*-
"""
/***************************************************************************
ParcelleToActeDialog
A QGIS plugin
Permet d'associer des parcelles à des actes
-------------------
begin : 2015-06-19
git sha : $Format:%H$
copyright : (C) 2015 by CEN Savoie
email : a.lesconnec@cen-savoie.org
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
import os
import psycopg2
import psycopg2.extras
import base64
from PyQt5 import QtGui, uic
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QDialog, QMessageBox
from functools import partial
import datetime
from time import gmtime, strftime
# Import du fichier de configuration
from pluginsCenSavoie_v3.tools.confPython import bd_cen_host, bd_cen_port, bd_cen_name
FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'parcelle_to_acte_dialog_base.ui'))
class ParcelleToActeDialog(QDialog, FORM_CLASS):
def __init__(self, parent=None):
"""Constructor."""
global host
host = bd_cen_host
global port
port = bd_cen_port
global bdd
bdd = bd_cen_name
super(ParcelleToActeDialog, self).__init__(parent)
QDialog.__init__(self)
# Set up the user interface from Designer.
# After setupUI you can access any designer object by doing
# self.<objectname>, and you can use autoconnect slots - see
# http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
# #widgets-and-dialogs-with-auto-connect
self.setupUi(self)
def InitFormulaire(self, site_id, acces, user, mdp):
self.chk_convention.clicked.connect(partial(self.InitFormulaire, site_id = site_id, acces='reload', user = user, mdp = mdp))
self.chk_acquisition.clicked.connect(partial(self.InitFormulaire, site_id = site_id, acces='reload', user = user, mdp = mdp))
self.flt_date_today.clicked.connect(partial(self.InitFormulaire, site_id = site_id, acces='reload', user = user, mdp = mdp))
self.flt_date_week.clicked.connect(partial(self.InitFormulaire, site_id = site_id, acces='reload', user = user, mdp = mdp))
self.flt_date_month.clicked.connect(partial(self.InitFormulaire, site_id = site_id, acces='reload', user = user, mdp = mdp))
self.flt_date_unknown.clicked.connect(partial(self.InitFormulaire, site_id = site_id, acces='reload', user = user, mdp = mdp))
self.lst_actes.blockSignals(True)
self.lst_motif_maj.blockSignals(True)
if acces == 'load':
self.chk_convention.setChecked(1)
self.chk_acquisition.setChecked(1)
self.flt_date_unknown.setChecked(1)
self.no_acte.setVisible(0)
self.type_acte_sel.setVisible(0)
self.motif_maj_id.setVisible(0)
self.cal_date_modif.setVisible(0)
self.motif_maj_id.setText('');
self.button_box.setEnabled(False)
self.date_modif.setText('N.P.')
global conn, cur
conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=" + user + " password=" + mdp)
cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
self.lst_actes.clear() #Vidage de la combobox
self.lst_motif_maj.clear() #Vidage de la combobox
k = 0
aujourdhui = strftime("%Y-%m-%d", gmtime())
this_week = strftime("%U", gmtime())
tbl_site_id = site_id
self.no_acte.setVisible(1)
self.lst_actes.setVisible(0)
self.lst_motif_maj.setVisible(0)
global tbl_typemfu
tbl_typemfu = []
global tbl_motif_maj
tbl_motif_maj = []
rq_lst_motif = """
SELECT motif_maj_id as id, motif_maj_lib as lib
FROM
foncier.d_motif_maj
WHERE motif_maj_id != 2 AND motif_maj_manip IN ('entree', 'entree/sortie')
ORDER BY motif_maj_ordre"""
if self.chk_convention.isChecked() == 0:
rq_lst_motif = rq_lst_motif + " AND motif_maj_acte NOT LIKE '%Convention%'"
if self.chk_acquisition.isChecked() == 0:
rq_lst_motif = rq_lst_motif + " AND motif_maj_acte NOT LIKE '%Acquisition%'"
with conn:
with conn.cursor() as cur:
cur.execute(rq_lst_motif)
global res_lst_motif
res_lst_motif = cur.fetchall() #requête de récupération des options possible de niveau 2 à partir du niveau 1 sélectionné
if len(res_lst_motif) > 0:
self.lst_motif_maj.setVisible(1)
i = 0 #Déclaration à 0 d'une variable pour boucler sur toutes les options de la requête identifiée précédement
while i < len(res_lst_motif): #Boucle sur toutes les options de niveau 2
lib = res_lst_motif[i][1] #Déclaration de la variable stockant le libellé complet de la requête
self.lst_motif_maj.addItem(lib) #Ajout à la combobox de l'option en cours de bouclage
tbl_motif_maj.append(res_lst_motif[i][0])
i=i+1 #implémentation de la variable permettant de suivre le bon index de la combobox
self.lst_motif_maj.setCurrentIndex(-1)
while k < len(tbl_site_id):
cur_site_id = tbl_site_id[k]
k = k + 1
rq_lst_mfu = """
WITH tprob AS (
SELECT DISTINCT acte AS acte_id FROM alertes.v_prob_mfu_baddata
UNION
SELECT DISTINCT mfu_id AS acte_id FROM alertes.v_prob_cadastre_cen WHERE statutmfu_id = 1
UNION
SELECT DISTINCT acte AS acte_id FROM alertes.v_alertes_mu WHERE alerte LIKE 'termin%'
UNION
SELECT DISTINCT mfu_id AS acte_id FROM alertes.v_prob_mfu_sansparc
),
t1 AS (
SELECT DISTINCT
acte as type_acte, mfu_id as acte_id, mf_acquisitions.mf_lib as acte_lib, typmfu_lib as acte_typ,
v_tdb_mfu.date_sign_acte as acte_date, mf_acquisitions.maj_date as maj_date
FROM
alertes.v_tdb_mfu
JOIN foncier.mf_acquisitions ON (mf_id = mfu_id)
LEFT JOIN tprob ON (acte_id = mfu_id)
WHERE statutmfu_id IN (0, 1) AND tbl_site_id ILIKE '%"""+cur_site_id+"""%' AND tprob.acte_id IS NULL
UNION
SELECT DISTINCT
acte as type_acte, mfu_id as acte_id, mu_conventions.mu_lib as acte_lib, typmfu_lib as acte_typ,
v_tdb_mfu.date_effet_conv as acte_date, mu_conventions.maj_date as maj_date
FROM
alertes.v_tdb_mfu
JOIN foncier.mu_conventions ON (mu_id = mfu_id)
LEFT JOIN tprob ON (acte_id = mfu_id)
WHERE statutmfu_id IN (0, 1) AND tbl_site_id ILIKE '%"""+cur_site_id+"""%' AND tprob.acte_id IS NULL
)
SELECT * FROM t1 WHERE 1=1"""
if self.chk_convention.isChecked() == 0:
rq_lst_mfu = rq_lst_mfu + " AND type_acte != 'Convention'"
if self.chk_acquisition.isChecked() == 0:
rq_lst_mfu = rq_lst_mfu + " AND type_acte != 'Acquisition'"
if self.flt_date_today.isChecked() == 1:
rq_lst_mfu = rq_lst_mfu + " AND LEFT(maj_date, 10) = '"+aujourdhui+"'"
elif self.flt_date_week.isChecked() == 1:
rq_lst_mfu = rq_lst_mfu + " AND EXTRACT(WEEK FROM to_date(maj_date, 'YYYY-MM-DD')) = " + this_week
elif self.flt_date_month.isChecked() == 1:
rq_lst_mfu = rq_lst_mfu + " AND TO_DATE(maj_date, 'YYYY-MM-DD') BETWEEN TO_DATE('"+strftime("%Y-%m", gmtime())+"-01', '%Y-%m-%d') AND TO_DATE('"+strftime("%Y-%m-%d", gmtime())+"', 'YYYY-MM-DD')"
with conn:
with conn.cursor() as cur:
cur.execute(rq_lst_mfu)
res_lst_mfu = cur.fetchall() #requête de récupération des options possible de niveau 2 à partir du niveau 1 sélectionné
if len(res_lst_mfu) > 0:
self.no_acte.setVisible(0)
self.lst_actes.setVisible(1)
i = 0 #Déclaration à 0 d'une variable pour boucler sur toutes les options de la requête identifiée précédement
while i < len(res_lst_mfu): #Boucle sur toutes les options de niveau 2
lib = res_lst_mfu[i][1] #Déclaration de la variable stockant le libellé complet de la requête
self.lst_actes.addItem(lib) #Ajout à la combobox de l'option en cours de bouclage
tbl_typemfu.append(res_lst_mfu[i][0])
i=i+1 #implémentation de la variable permettant de suivre le bon index de la combobox
self.lst_actes.setCurrentIndex(-1)
self.lst_actes.currentIndexChanged.connect(self.change_lst_acte)
self.lst_actes.blockSignals(False)
self.lst_motif_maj.currentIndexChanged.connect(self.change_lst_motif_maj)
self.lst_motif_maj.blockSignals(False)
def change_lst_acte(self, index):
self.lst_motif_maj.blockSignals(True)
if self.lst_actes.currentIndex() != -1 and self.date_modif.text() != 'N.P.' and self.lst_motif_maj.currentIndex() != -1 :
self.button_box.setEnabled(True)
else:
self.button_box.setEnabled(False)
if index != -1 and tbl_typemfu[index] == 'Acquisition':
self.type_acte_sel.setText('r_cad_site_mf')
elif index != -1 and tbl_typemfu[index] == 'Convention':
self.type_acte_sel.setText('r_cad_site_mu')
with conn:
with conn.cursor() as cur:
if self.motif_maj_id.text() != '':
rq_check_lst_motif = "SELECT motif_maj_id as id, motif_maj_lib as lib FROM foncier.d_motif_maj WHERE motif_maj_manip IN ('entree', 'entree/sortie') AND motif_maj_acte LIKE '%"+str(tbl_typemfu[index])+"%' AND motif_maj_id = "+str(self.motif_maj_id.text())
cur.execute(rq_check_lst_motif)
res_check_lst_motif = cur.fetchall()
if len(res_check_lst_motif) == 0 :
self.lst_motif_maj.setCurrentIndex(-1)
self.motif_maj_id.setText('')
rq_lst_motif = """
SELECT motif_maj_id as id, motif_maj_lib as lib
FROM foncier.d_motif_maj
WHERE motif_maj_id != 2 AND motif_maj_manip IN ('entree', 'entree/sortie') AND motif_maj_acte LIKE '%"+str(tbl_typemfu[index])+"%'
ORDER BY motif_maj_ordre"""
cur.execute(rq_lst_motif)
res_lst_motif = cur.fetchall() #requête de récupération des options possible de niveau 2 à partir du niveau 1 sélectionné
if len(res_lst_motif) > 0:
self.lst_motif_maj.setVisible(1)
self.lst_motif_maj.clear()
tbl_motif_maj.clear()
i = 0 #Déclaration à 0 d'une variable pour boucler sur toutes les options de la requête identifiée précédement
j = -1
while i < len(res_lst_motif): #Boucle sur toutes les options de niveau 2
lib = res_lst_motif[i][1] #Déclaration de la variable stockant le libellé complet de la requête
self.lst_motif_maj.addItem(lib) #Ajout à la combobox de l'option en cours de bouclage
tbl_motif_maj.append(res_lst_motif[i][0])
if str(res_lst_motif[i][0]) == str(self.motif_maj_id.text()):
j = i
i=i+1 #implémentation de la variable permettant de suivre le bon index de la combobox
self.lst_motif_maj.setCurrentIndex(j)
self.lst_motif_maj.blockSignals(False)
def change_lst_motif_maj(self, index):
if self.lst_motif_maj.currentIndex() != -1:
self.motif_maj_id.setText(str(tbl_motif_maj[index]))
if self.lst_actes.currentIndex() != -1 and self.date_modif.text() != 'N.P.' and self.lst_motif_maj.currentIndex() != -1 :
self.button_box.setEnabled(True)
else:
self.button_box.setEnabled(False)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,160 @@
# -*- coding: utf-8 -*-
"""
/***************************************************************************
ParcelleToSite
A QGIS plugin
Permet d'associer des parcelles à des sites
-------------------
begin : 2015-06-19
git sha : $Format:%H$
copyright : (C) 2015 by CEN Savoie
email : a.lesconnec@cen-savoie.org
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QAction, QTableWidgetItem, QApplication, QMessageBox
# Initialize Qt resources from file resources.py
from pluginsCenSavoie_v3 import resources
# Import the code for the dialog
from pluginsCenSavoie_v3.tools.parcelle_to_site_dialog import ParcelleToSiteDialog
# Import du fichier de configuration
from pluginsCenSavoie_v3.tools.confPython import bd_cen_host, bd_cen_port, bd_cen_name, bd_cen_mdp_1st_cnx
import os.path
import sys
import qgis
import os
import psycopg2
import psycopg2.extras
import base64
import re
from time import localtime, strftime
class ParcelleToSite:
"""QGIS Plugin Implementation."""
def __init__(self, iface, cenToolbar):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgsInterface
"""
# Variable HOTE de l'accès à la base de données
global host
host = bd_cen_host
global port
port = bd_cen_port
global bdd
bdd = bd_cen_name
global mdp_1st_cnx
mdp_1st_cnx = bd_cen_mdp_1st_cnx
global os_user
if sys.platform == 'linux':
os_user = os.environ['USER']
else:
os_user = os.environ['USERNAME']
# Save reference to the QGIS interface
self.iface = iface
self.canvas = self.iface.mapCanvas()
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# Create the dialog (after translation) and keep reference
self.dlg = ParcelleToSiteDialog()
# Add toolbar button
self.action= QAction(QIcon(":/plugins/pluginsCenSavoie_v3/icons/parcelleToSite.png"), QCoreApplication.translate('ParcelleToSite', u'Associer des parcelles à un site'), self.iface.mainWindow())
self.action.triggered.connect(self.run)
self.action.setEnabled(False)
cenToolbar.addAction(self.action)
self.canvas.selectionChanged.connect(self.toggle)
self.iface.layerTreeView().currentLayerChanged.connect(self.toggle)
def toggle(self):
layer = self.iface.activeLayer()
if layer and layer.type() == layer.VectorLayer:
if layer.selectedFeatureCount() > 0:
provider = layer.dataProvider()
source_postgis = provider.dataSourceUri()
source_postgis = source_postgis.replace('"', '')
if (source_postgis.count('table=cadastre.parcelles ') == 1 or source_postgis.count('table=cadastre.v_parcelles') == 1):
self.action.setEnabled(True)
else:
self.action.setEnabled(False)
else:
self.action.setEnabled(False)
else:
self.action.setEnabled(False)
def run(self):
"""Run method that performs all the real work"""
tbl_par_id = []
self.canvas = self.iface.mapCanvas()
global layer
layer = self.iface.activeLayer()
provider = layer.dataProvider()
source_postgis = provider.dataSourceUri()
source_postgis = source_postgis.replace('"', '')
if (source_postgis.count('table=cadastre.parcelles ') != 1 and source_postgis.count('table=cadastre.v_parcelles_') != 1):
self.action.setEnabled(False)
QMessageBox.warning(None, "Oups:", str("La couche active n'est pas une couche parcelles valide"))
else:
rowCount = 0
for feature in layer.selectedFeatures():
tbl_par_id.append(feature["par_id"])
if (len(tbl_par_id) < 1):
QMessageBox.warning(None, "Oups:", 'Selection invalide')
else:
first_conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=first_cnx password=" + mdp_1st_cnx)
first_cur = first_conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
first_cur.execute("SELECT mdp_cen, usename FROM pg_catalog.pg_user t1, admin_sig.utilisateurs t2 WHERE t2.oid = t1.usesysid AND (utilisateur_id = '" + os_user + "' OR utilisateur_os = '" + os_user + "')")
res_ident = first_cur.fetchone()
mdp = base64.b64decode(str(res_ident[0])).decode('utf-8')
user = res_ident[1]
first_conn.close()
self.dlg.InitFormulaire(tbl_par_id, 'load', host, port, bdd, user, mdp)
self.dlg.img_logo.setPixmap(QPixmap(":/plugins/pluginsCenSavoie_v3/tools/images/Logo_CEN_Savoie.png"))
self.dlg.img_frise.setPixmap(QPixmap(":/plugins/pluginsCenSavoie_v3/tools/images/Frise_portrait.png"))
self.dlg.img_frise.stackUnder(self.dlg.button_box)
# show the dialog
self.dlg.show()
# Run the dialog event loop
result = self.dlg.exec_()
# See if OK was pressed
if result:
# Do something useful here - delete the line containing pass and
# substitute with your code.
conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=" + user + " password=" + mdp)
cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
QApplication.setOverrideCursor(Qt.WaitCursor)
with conn:
with conn.cursor() as cur:
for feature in layer.selectedFeatures():
rq_insert = """SELECT cadastre.import_parcelles_cen('"""+ str(feature["par_id"]) + """', '"""+ str(self.dlg.site_sel.text()) +"""', '"""+ str(self.dlg.lst_pci.currentText()) +"""')"""
cur.execute(rq_insert)
conn.commit()
rq_refresh = """SELECT admin_sig.refresh_mview_foncier('"""+ str(self.dlg.site_sel.text()) +"""')"""
cur.execute(rq_refresh)
conn.commit()
self.canvas.refresh()
QApplication.restoreOverrideCursor()

View File

@ -0,0 +1,100 @@
# -*- coding: utf-8 -*-
"""
/***************************************************************************
ParcelleToSiteDialog
A QGIS plugin
Permet d'associer des parcelles à des sites
-------------------
begin : 2015-06-19
git sha : $Format:%H$
copyright : (C) 2015 by CEN Savoie
email : a.lesconnec@cen-savoie.org
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
import os
import psycopg2
import psycopg2.extras
import base64
from PyQt5 import QtGui, uic
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QDialog
from functools import partial
import datetime
from time import gmtime, strftime
FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'parcelle_to_site_dialog_base.ui'))
class ParcelleToSiteDialog(QDialog, FORM_CLASS):
def __init__(self, parent=None):
"""Constructor."""
super(ParcelleToSiteDialog, self).__init__(parent)
QDialog.__init__(self)
self.setupUi(self)
def InitFormulaire(self, tbl_par_id, acces, host, port, bdd, user, mdp):
self.lst_sites.currentIndexChanged.connect(self.change_lst_site)
self.site_sel.setVisible(0)
self.button_box.setEnabled(False)
conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=" + user + " password=" + mdp)
cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
self.lst_sites.clear() #Vidage de la combobox
self.lst_pci.clear() #Vidage de la combobox
this_year = strftime("%Y", gmtime())
global tbl_lst_sites
self.tbl_lst_sites = []
rq_lst_sites = """
SELECT DISTINCT site_id, site_nom
FROM sites.sites
WHERE site_id = 'PCEN'
UNION
SELECT DISTINCT site_id, site_nom
FROM
sites.sites
JOIN cadastre.parcelles ON (st_intersects(st_buffer(sites.geom_ecolo, 500), parcelles.geom))
WHERE par_id IN("""
for par_id in tbl_par_id :
rq_lst_sites += """'"""+par_id + """',"""
rq_lst_sites += """'123') ORDER BY site_id"""
with conn:
with conn.cursor() as cur:
cur.execute(rq_lst_sites)
res_lst_sites = cur.fetchall() #requête de récupération des options possible de niveau 2 à partir du niveau 1 sélectionné
if len(res_lst_sites) > 0:
self.lst_sites.setVisible(1)
i = 0 #Déclaration à 0 d'une variable pour boucler sur toutes les options de la requête identifiée précédement
while i < len(res_lst_sites): #Boucle sur toutes les options de niveau 2
self.tbl_lst_sites.append(str(res_lst_sites[i][0]))
self.lst_sites.addItem(str(res_lst_sites[i][0]) + """ """ + str(res_lst_sites[i][1])) #Ajout à la combobox de l'option en cours de bouclage
i=i+1 #implémentation de la variable permettant de suivre le bon index de la combobox
self.lst_sites.setCurrentIndex(0)
self.button_box.setEnabled(True)
else :
self.lst_sites.setVisible(0)
self.lst_pci.addItem(str(int(this_year) - 4))
self.lst_pci.addItem(str(int(this_year) - 3))
self.lst_pci.addItem(str(int(this_year) - 2))
self.lst_pci.addItem(str(int(this_year) - 1))
self.lst_pci.addItem(str(int(this_year)))
self.lst_pci.setCurrentIndex(4)
def change_lst_site(self, index):
if self.lst_sites.currentIndex() != -1:
self.site_sel.setText(str(self.tbl_lst_sites[index]))
else:
self.button_box.setEnabled(False)

File diff suppressed because it is too large Load Diff