def canvasReleaseEvent(self, event):

        # With left click the digitizing is finished
        if event.button() == Qt.LeftButton:

            # Get the click
            x = event.pos().x()
            y = event.pos().y()
            event_point = QPoint(x, y)
            feature = None

            # Snapping
            (retval, result) = self.snapper.snapToBackgroundLayers(
                event_point)  # @UnusedVariable

            # That's the snapped features
            if result:
                for snapped_feat in result:
                    # Check if feature belongs to 'node' group
                    exist = self.snapper_manager.check_node_group(
                        snapped_feat.layer)
                    if exist:
                        # Get the point
                        point = QgsPoint(
                            result[0].snappedVertex)  # @UnusedVariable
                        feature = next(result[0].layer.getFeatures(
                            QgsFeatureRequest().setFilterFid(
                                result[0].snappedAtGeometry)))
                        result[0].layer.select([result[0].snappedAtGeometry])
                        break

            if feature is not None:

                # Get selected features and layer type: 'node'
                node_id = feature.attribute('node_id')

                # Ask question before executing
                message = "Are you sure you want to replace selected node with a new one?"
                answer = self.controller.ask_question(message, "Replace node")
                if answer:
                    # Execute SQL function and show result to the user
                    function_name = "gw_fct_node_replace"
                    sql = ("SELECT " + self.schema_name + "." + function_name +
                           "('" + str(node_id) + "', '" +
                           self.workcat_id_end_aux + "', '" +
                           str(self.enddate_aux) + "', '" +
                           str(utils_giswater.isChecked("keep_elements")) +
                           "');")
                    new_node_id = self.controller.get_row(sql, commit=True)
                    if new_node_id:
                        message = "Node replaced successfully"
                        self.controller.show_info(message)
                        self.open_custom_form(new_node_id)
                    else:
                        message = "Error replacing node"
                        self.controller.show_warning(message)

                    # Refresh map canvas
                    self.refresh_map_canvas()
    def go2epa_accept(self):
        """ Save INP, RPT and result name into GSW file """

        # Get widgets values
        self.file_inp = utils_giswater.getWidgetText(self.dlg_go2epa, self.dlg_go2epa.txt_file_inp)
        self.file_rpt = utils_giswater.getWidgetText(self.dlg_go2epa, self.dlg_go2epa.txt_file_rpt)
        self.project_name = utils_giswater.getWidgetText(self.dlg_go2epa, self.dlg_go2epa.txt_result_name)
        
        # Check that all parameters has been set
        if self.file_inp == "null":
            message = "You have to set this parameter"
            self.controller.show_warning(message, parameter="INP file")
            return
        if self.file_rpt == "null":
            message = "You have to set this parameter"
            self.controller.show_warning(message, parameter="RPT file")
            return            
        if self.project_name == "null":
            message = "You have to set this parameter"
            self.controller.show_warning(message, parameter="Project Name")
            return     
        
        # Check if selected @result_id already exists
        exists = self.check_result_id(self.project_name)
        if exists:
            message = "Selected 'Result name' already exists. Do you want to overwrite it?"
            answer = self.controller.ask_question(message, 'Result name')
            if not answer:
                return
        
        only_check = utils_giswater.isChecked(self.dlg_go2epa, self.dlg_go2epa.chk_only_check)
        if only_check:
            self.check_data()
            return
        
        # Execute function 'gw_fct_pg2epa'
        sql = "SELECT " + self.schema_name + ".gw_fct_pg2epa('" + str(self.project_name) + "', 'False');"  
        row = self.controller.get_row(sql, log_sql=True)
        if not row:
            return False        
    
        # Save INP, RPT and result name into GSW file
        self.save_file_parameters()
        
        # Save database connection parameters into GSW file
        self.save_database_parameters()
        
        # Close form
        self.close_dialog(self.dlg_go2epa)
        
        # Execute 'go2epa_express'
        self.go2epa_express()
    def update_table(self, tablename, dialog):
        """ INSERT or UPDATE tables according :param update"""
        
        sql = "SELECT * FROM " + self.schema_name + "." + tablename
        row = self.controller.get_row(sql)

        columns = []
        for i in range(0, len(row)):
            column_name = self.dao.get_column_name(i)
            columns.append(column_name)

        if columns is not None:
            sql = "UPDATE " + self.schema_name + "." + tablename + " SET "
            for column_name in columns:
                if column_name != 'id':
                    widget = dialog.findChild(QWidget, column_name)
                    widget_type = utils_giswater.getWidgetType(dialog, widget)
                    if widget_type is QCheckBox:
                        value = utils_giswater.isChecked(dialog, widget)
                    elif widget_type is QDateEdit:
                        date = dialog.findChild(QDateEdit, str(column_name))
                        value = date.dateTime().toString('dd/MM/yyyy')
                    elif widget_type is QTimeEdit:
                        aux = 0
                        widget_day = str(column_name) + "_day"
                        day = utils_giswater.getText(dialog, widget_day)
                        if day != "null":
                            aux = int(day) * 24
                        time = dialog.findChild(QTimeEdit, str(column_name))
                        timeparts = time.dateTime().toString('HH:mm:ss').split(':')
                        h = int(timeparts[0]) + int(aux)
                        aux = str(h) + ":" + str(timeparts[1]) + ":" + str(timeparts[2])
                        value = aux
                    elif widget_type is QSpinBox:
                        x = dialog.findChild(QSpinBox, str(column_name))
                        value = x.value()
                    elif widget_type is QComboBox:
                        value = utils_giswater.get_item_data(dialog, widget)
                    else:
                        value = utils_giswater.getWidgetText(dialog, widget)
                    if value == 'null':
                        sql += column_name + " = null, "
                    elif value is None:
                        pass
                    else:
                        if type(value) is not bool and widget_type is not QSpinBox:
                            value = value.replace(",", ".")
                        sql += column_name + " = '" + str(value) + "', "
            sql = sql[:len(sql) - 2]
        self.controller.execute_sql(sql)
        dialog.close()
    def update_config(self, tablename, dialog):
        """ Update table @tablename from values get from @dialog """

        sql = "SELECT * FROM " + self.schema_name + "." + tablename
        row = self.dao.get_row(sql)
        columns = []
        for i in range(0, len(row)):
            column_name = self.dao.get_column_name(i)
            if column_name != 'id': 
                columns.append(column_name)

        if columns is None:
            return
        
        sql = "UPDATE " + self.schema_name + "." + tablename + " SET "
        for column_name in columns:         
            widget_type = utils_giswater.getWidgetType(column_name)
            if widget_type is QCheckBox:
                value = utils_giswater.isChecked(column_name)
            elif widget_type is QDateEdit:
                date = dialog.findChild(QDateEdit, str(column_name))
                value = date.dateTime().toString('yyyy-MM-dd')
            elif widget_type is QTimeEdit:
                aux = 0
                widget_day = str(column_name) + "_day"
                day = utils_giswater.getText(widget_day)
                if day != "null":
                    aux = int(day) * 24
                time = dialog.findChild(QTimeEdit, str(column_name))
                timeparts = time.dateTime().toString('HH:mm:ss').split(':')
                h = int(timeparts[0]) + int(aux)
                aux = str(h) + ":" + str(timeparts[1]) + ":00"
                value = aux
            elif widget_type is QSpinBox:
                x = dialog.findChild(QSpinBox, str(column_name))
                value = x.value()
            else:
                value = utils_giswater.getWidgetText(column_name)
              
            if value is not None:  
                if value == 'null':
                    sql += column_name + " = null, "
                else:
                    if type(value) is not bool and widget_type is not QSpinBox:
                        value = value.replace(",", ".")
                    sql += column_name + " = '" + str(value) + "', "

        sql = sql[:- 2]          
        self.controller.execute_sql(sql)
Example #5
0
    def select_feature(self):

        self.canvas.selectionChanged.disconnect()
        features = self.worker_layer.selectedFeatures()

        if len(features) == 0:
            return

        for f in features:
            feature = f

        self.init_create_point_form()
        if not self.cancel_point:
            if self.virtual_layer_point:
                sql = ("SELECT ST_GeomFromEWKT('SRID=" + str(self.srid) + ";" +
                       str(feature.geometry().exportToWkt(3)) + "')")
                row = self.controller.get_row(sql)
                if not row:
                    return
                inverter = utils_giswater.isChecked(
                    self.dlg_create_point.chk_invert)
                sql = ("SELECT " + self.controller.schema_name +
                       ".gw_fct_cad_add_relative_point"
                       "('" + str(row[0]) + "', " +
                       utils_giswater.getWidgetText(
                           self.dlg_create_point.dist_x) + ", " +
                       utils_giswater.getWidgetText(
                           self.dlg_create_point.dist_y) + ", " +
                       str(inverter) + ")")
                row = self.controller.get_row(sql)
                if not row:
                    return
                point = row[0]
                feature = QgsFeature()
                feature.setGeometry(
                    QgsGeometry.fromPoint(
                        QgsPoint(float(point[0]), float(point[1]))))
                provider = self.virtual_layer_point.dataProvider()
                self.virtual_layer_point.startEditing()
                provider.addFeatures([feature])
                self.virtual_layer_point.commitChanges()
                self.canvas.selectionChanged.connect(
                    partial(self.select_feature))
        else:
            self.iface.setActiveLayer(self.current_layer)
            self.cancel_map_tool()
            self.cancel_point = False
            return
    def master_config_master_accept(self):
        """ Button 99: Slot for 'btn_accept' """
        
        if utils_giswater.isChecked("chk_psector_enabled"):
            self.insert_or_update_config_param_curuser(self.dlg.psector_vdefault, "psector_vdefault", "config_param_user")
        else:
            self.delete_row("psector_vdefault", "config_param_user")
            
        # Update tables 'confog' and 'config_param_system'            
        self.update_config("config", self.dlg)
        self.update_config_param_system("config_param_system")
        
        message = "Values has been updated"
        self.controller.show_info(message)

        self.close_dialog(self.dlg)
    def generate_rapports(self, previous_dialog, dialog):
        
        self.controller.plugin_settings_set_value("psector_rapport_path", utils_giswater.getWidgetText('txt_path'))
        self.controller.plugin_settings_set_value("psector_rapport_chk_composer", utils_giswater.isChecked('chk_composer'))
        self.controller.plugin_settings_set_value("psector_rapport_chk_csv_detail", utils_giswater.isChecked('chk_csv_detail'))
        self.controller.plugin_settings_set_value("psector_rapport_chk_csv", utils_giswater.isChecked('chk_csv'))
        folder_path = utils_giswater.getWidgetText(dialog.txt_path)
        if folder_path is None or folder_path == 'null' or not os.path.exists(folder_path):
            self.get_folder_dialog(dialog.txt_path)
            folder_path = utils_giswater.getWidgetText(dialog.txt_path)
            
        # Generate Composer
        if utils_giswater.isChecked(dialog.chk_composer):
            file_name = utils_giswater.getWidgetText('txt_composer_path')
            if file_name is None or file_name == 'null':
                message = "File name is required"
                self.controller.show_warning(message)
            if file_name.find('.pdf') is False:
                file_name += '.pdf'
            path = folder_path + '/' + file_name
            compass_rotation = float(utils_giswater.getWidgetText(previous_dialog.rotation))
            self.generate_composer(path, compass_rotation)

        # Generate csv detail
        if utils_giswater.isChecked(dialog.chk_csv_detail):
            file_name = utils_giswater.getWidgetText('txt_csv_path')
            viewname = "v_" + self.plan_om + "_current_psector_budget_detail"
            if self.plan_om == 'om' and previous_dialog.psector_type.currentIndex == 0:
                viewname = 'v_om_current_psector_budget_detail_rec'
            elif self.plan_om == 'om' and previous_dialog.psector_type.currentIndex == 1:
                viewname = 'v_om_current_psector_budget_detail_reh'
            if file_name is None or file_name == 'null':
                message = "Price list csv file name is required"
                self.controller.show_warning(message)
            if file_name.find('.csv') is False:
                file_name += '.csv'
            path = folder_path + '/' + file_name
            self.generate_csv(path, viewname, previous_dialog)

        # Generate csv
        if utils_giswater.isChecked(dialog.chk_csv):
            file_name = utils_giswater.getWidgetText('txt_csv_detail_path')
            viewname = "v_" + self.plan_om + "_current_psector_budget"
            if file_name is None or file_name == 'null':
                message = "Price list csv file name is required"
                self.controller.show_warning(message)
            if file_name.find('.csv') is False:
                file_name += '.csv'
            path = folder_path + '/' + file_name
            self.generate_csv(path, viewname, previous_dialog)

        self.set_prev_dialog(dialog, previous_dialog)
Example #8
0
    def get_values(self, point_1, point_2):
        self.controller.plugin_settings_set_value(
            self.dlg_create_point.rb_left.objectName(),
            self.dlg_create_point.rb_left.isChecked())
        self.dist_x = self.dlg_create_point.dist_x.text()
        if not self.dist_x:
            self.dist_x = 0
        self.dist_y = self.dlg_create_point.dist_y.text()
        if not self.dist_y:
            self.dist_y = 0
        self.delete_prev = utils_giswater.isChecked(
            self.dlg_create_point, self.dlg_create_point.chk_delete_prev)

        if self.layer_points:
            self.layer_points.startEditing()
            self.close_dialog(self.dlg_create_point)
            if self.dlg_create_point.rb_left.isChecked():
                self.direction = 1
            else:
                self.direction = 2

            sql = ("SELECT ST_GeomFromText('POINT(" + str(point_1[0]) + " " +
                   str(point_1[1]) + ")', " + str(self.srid) + ")")
            row = self.controller.get_row(sql)
            point_1 = row[0]
            sql = ("SELECT ST_GeomFromText('POINT(" + str(point_2[0]) + " " +
                   str(point_2[1]) + ")', " + str(self.srid) + ")")
            row = self.controller.get_row(sql)
            point_2 = row[0]

            sql = ("SELECT " + self.controller.schema_name +
                   ".gw_fct_cad_add_relative_point"
                   "('" + str(point_1) + "', '" + str(point_2) + "', " +
                   str(self.dist_x) + ", " + str(self.dist_y) + ", " +
                   str(self.direction) + ", " + str(self.delete_prev) + " )")
            self.controller.execute_sql(sql)
            self.layer_points.commitChanges()
            self.layer_points.dataProvider().forceReload()
            self.layer_points.triggerRepaint()

        else:
            self.iface.actionPan().trigger()
            self.cancel_point = False
            return
Example #9
0
 def mg_config_accept_table(self, tablename, columns):
     ''' Update values of selected 'tablename' with the content of 'columns' '''
     
     if columns is not None:       
         sql = "UPDATE "+self.schema_name+"."+tablename+" SET "         
         for column_name in columns:
             if column_name != 'id':
                 widget_type = utils_giswater.getWidgetType(column_name)
                 if widget_type is QCheckBox:
                     value = utils_giswater.isChecked(column_name)                      
                 else:
                     value = utils_giswater.getWidgetText(column_name)
                 if value is None or value == 'null':
                     sql+= column_name+" = null, "     
                 else:
                     if type(value) is not bool:
                         value = value.replace(",", ".")
                     sql+= column_name+" = '"+str(value)+"', "           
         
         sql = sql[:-2]
         self.dao.execute_sql(sql)
                     
             
Example #10
0
    def get_radius(self, point):

        self.radius = self.dlg_create_circle.radius.text()
        if not self.radius:
            self.radius = 0.1
        self.delete_prev = utils_giswater.isChecked(
            self.dlg_create_circle, self.dlg_create_circle.chk_delete_prev)

        if self.layer_circle:
            self.layer_circle.startEditing()
            self.close_dialog(self.dlg_create_circle)
            if self.delete_prev:
                selection = self.layer_circle.getFeatures()
                self.layer_circle.setSelectedFeatures(
                    [f.id() for f in selection])
                if self.layer_circle.selectedFeatureCount() > 0:
                    features = self.layer_circle.selectedFeatures()
                    for feature in features:
                        self.layer_circle.deleteFeature(feature.id())

            if not self.cancel_circle:
                feature = QgsFeature()
                feature.setGeometry(
                    QgsGeometry.fromPoint(point).buffer(
                        float(self.radius), 100))
                provider = self.layer_circle.dataProvider()

                provider.addFeatures([feature])
            self.layer_circle.commitChanges()
            self.layer_circle.dataProvider().forceReload()
            self.layer_circle.triggerRepaint()

        else:
            self.iface.actionPan().trigger()
            self.cancel_circle = False
            return
Example #11
0
    def ws_options(self):
        """ Open dialog ws_options.ui """

        # Create dialog
        self.dlg_wsoptions = WSoptions()
        utils_giswater.setDialog(self.dlg_wsoptions)

        # Allow QTextView only Double text
        self.dlg_wsoptions.viscosity.setValidator(QDoubleValidator())
        self.dlg_wsoptions.trials.setValidator(QDoubleValidator())
        self.dlg_wsoptions.accuracy.setValidator(QDoubleValidator())
        self.dlg_wsoptions.emitter_exponent.setValidator(QDoubleValidator())
        self.dlg_wsoptions.checkfreq.setValidator(QDoubleValidator())
        self.dlg_wsoptions.maxcheck.setValidator(QDoubleValidator())
        self.dlg_wsoptions.damplimit.setValidator(QDoubleValidator())
        self.dlg_wsoptions.node_id.setValidator(QDoubleValidator())
        self.dlg_wsoptions.unbalanced_n.setValidator(QDoubleValidator())
        self.dlg_wsoptions.specific_gravity.setValidator(QDoubleValidator())
        self.dlg_wsoptions.diffusivity.setValidator(QDoubleValidator())
        self.dlg_wsoptions.tolerance.setValidator(QDoubleValidator())
        self.dlg_wsoptions.demand_multiplier.setValidator(QDoubleValidator())

        self.dlg_wsoptions.chk_enabled.setChecked(True)

        # Set values from widgets of type QComboBox
        sql = "SELECT DISTINCT(id) FROM " + self.schema_name + ".inp_value_opti_units ORDER BY id"
        rows = self.dao.get_rows(sql)
        utils_giswater.fillComboBox("units", rows, False)

        sql = "SELECT DISTINCT(id) FROM " + self.schema_name + ".inp_value_opti_headloss ORDER BY id"
        rows = self.dao.get_rows(sql)
        utils_giswater.fillComboBox("headloss", rows, False)
        sql = "SELECT DISTINCT(pattern_id) FROM " + self.schema_name + ".inp_pattern ORDER BY pattern_id"
        rows = self.dao.get_rows(sql)
        utils_giswater.fillComboBox("pattern", rows, False)

        sql = "SELECT DISTINCT(id) FROM " + self.schema_name + ".inp_value_opti_unbal ORDER BY id"
        rows = self.dao.get_rows(sql)
        utils_giswater.fillComboBox("unbalanced", rows, False)

        sql = "SELECT DISTINCT(id) FROM " + self.schema_name + ".inp_value_opti_hyd ORDER BY id"
        rows = self.dao.get_rows(sql)
        utils_giswater.fillComboBox("hydraulics", rows, False)

        sql = "SELECT DISTINCT(id) FROM " + self.schema_name + ".inp_value_opti_qual ORDER BY id"
        rows = self.dao.get_rows(sql)
        utils_giswater.fillComboBox("quality", rows, False)

        sql = "SELECT id FROM " + self.schema_name + ".inp_value_opti_valvemode ORDER BY id"
        rows = self.controller.get_rows(sql)
        utils_giswater.fillComboBox("valve_mode", rows, False)

        sql = "SELECT id FROM " + self.schema_name + ".anl_mincut_result_cat ORDER BY id"
        rows = self.controller.get_rows(sql)
        utils_giswater.fillComboBox("valve_mode_mincut_result", rows, False)

        sql = "SELECT id FROM " + self.schema_name + ".ext_cat_period ORDER BY id"
        rows = self.controller.get_rows(sql)
        utils_giswater.fillComboBox("rtc_period_id", rows, False)

        sql = "SELECT DISTINCT(id) FROM " + self.schema_name + ".inp_value_opti_rtc_coef ORDER BY id"
        rows = self.dao.get_rows(sql)
        utils_giswater.fillComboBox("rtc_coefficient", rows, False)

        # TODO
        if self.dlg_wsoptions.valve_mode.currentText() == "MINCUT RESULTS":
            self.dlg_wsoptions.valve_mode_mincut_result.setEnabled(False)

        if self.dlg_wsoptions.hydraulics.currentText() == "":
            self.dlg_wsoptions.hydraulics_fname.setEnabled(False)
        else:
            self.dlg_wsoptions.hydraulics_fname.setEnabled(True)

        # TODO
        if self.dlg_wsoptions.quality.currentText() == "TRACE":
            self.dlg_wsoptions.node_id.setEnabled(False)
        else:
            self.dlg_wsoptions.node_id.setEnabled(True)

        if utils_giswater.isChecked(self.dlg_wsoptions.chk_enabled):
            self.dlg_wsoptions.rtc_period_id.setEnabled(True)
            self.dlg_wsoptions.rtc_coefficient.setEnabled(True)
        # TODO
        self.dlg_wsoptions.unbalanced.currentIndexChanged.connect(
            partial(self.enable_linetext, "unbalanced", "unbalanced_n",
                    "STOP"))
        self.dlg_wsoptions.hydraulics.currentIndexChanged.connect(
            partial(self.enable_linetext, "hydraulics", "hydraulics_fname",
                    ""))
        self.dlg_wsoptions.quality.currentIndexChanged.connect(
            partial(self.enable_linetext, "quality", "node_id", "TRACE"))
        self.dlg_wsoptions.valve_mode.currentIndexChanged.connect(
            partial(self.enable_linetext, "valve_mode",
                    "valve_mode_mincut_result", "MINCUT RESULTS"))
        self.dlg_wsoptions.chk_enabled.stateChanged.connect(
            self.enable_per_coef)

        self.dlg_wsoptions.btn_accept.pressed.connect(
            partial(self.insert_or_update, True, 'inp_options',
                    self.dlg_wsoptions))
        self.dlg_wsoptions.btn_cancel.pressed.connect(self.dlg_wsoptions.close)
        self.go2epa_options_get_data('inp_options')
        self.dlg_wsoptions.exec_()
Example #12
0
    def ws_options(self):
        """ Open dialog ws_options.ui """
        
        # Create dialog
        self.dlg_wsoptions = WSoptions()
        self.load_settings(self.dlg_wsoptions)

        # Allow QTextView only Double text
        self.dlg_wsoptions.viscosity.setValidator(QDoubleValidator())
        self.dlg_wsoptions.trials.setValidator(QDoubleValidator())
        self.dlg_wsoptions.accuracy.setValidator(QDoubleValidator())
        self.dlg_wsoptions.emitter_exponent.setValidator(QDoubleValidator())
        self.dlg_wsoptions.checkfreq.setValidator(QDoubleValidator())
        self.dlg_wsoptions.maxcheck.setValidator(QDoubleValidator())
        self.dlg_wsoptions.damplimit.setValidator(QDoubleValidator())
        self.dlg_wsoptions.node_id.setValidator(QDoubleValidator())
        self.dlg_wsoptions.unbalanced_n.setValidator(QDoubleValidator())
        self.dlg_wsoptions.specific_gravity.setValidator(QDoubleValidator())
        self.dlg_wsoptions.diffusivity.setValidator(QDoubleValidator())
        self.dlg_wsoptions.tolerance.setValidator(QDoubleValidator())
        self.dlg_wsoptions.demand_multiplier.setValidator(QDoubleValidator())

        self.dlg_wsoptions.rtc_enabled.setChecked(True)

        # Set values from widgets of type QComboBox
        sql = "SELECT id, id FROM "+self.schema_name+".inp_value_opti_units ORDER BY id"
        rows = self.controller.get_rows(sql)
        utils_giswater.set_item_data(self.dlg_wsoptions.units, rows)

        sql = "SELECT id, id FROM "+self.schema_name+".inp_value_opti_headloss ORDER BY id"
        rows = self.controller.get_rows(sql)
        utils_giswater.set_item_data(self.dlg_wsoptions.headloss, rows)

        sql = "SELECT pattern_id, pattern_id FROM "+self.schema_name+".inp_pattern ORDER BY pattern_id"
        rows = self.controller.get_rows(sql)
        utils_giswater.set_item_data(self.dlg_wsoptions.pattern, rows)

        sql = "SELECT id, id FROM "+self.schema_name+".inp_value_opti_unbal ORDER BY id"
        rows = self.controller.get_rows(sql)
        utils_giswater.set_item_data(self.dlg_wsoptions.unbalanced, rows)

        sql = "SELECT id, id FROM "+self.schema_name+".inp_value_opti_hyd ORDER BY id"
        rows = self.controller.get_rows(sql)
        utils_giswater.set_item_data(self.dlg_wsoptions.hydraulics, rows)

        sql = "SELECT id, id FROM "+self.schema_name+".inp_value_opti_qual ORDER BY id"
        rows = self.controller.get_rows(sql)
        utils_giswater.set_item_data(self.dlg_wsoptions.quality, rows)

        sql = "SELECT id, id FROM "+self.schema_name+".inp_value_opti_valvemode ORDER BY id"
        rows = self.controller.get_rows(sql)
        utils_giswater.set_item_data(self.dlg_wsoptions.valve_mode, rows)

        sql = "SELECT id::text, id::text FROM "+self.schema_name+".anl_mincut_result_cat ORDER BY id"
        rows = self.controller.get_rows(sql)
        utils_giswater.set_item_data(self.dlg_wsoptions.valve_mode_mincut_result, rows)

        sql = "SELECT id, code FROM "+self.schema_name+".ext_cat_period ORDER BY id"
        rows = self.controller.get_rows(sql)
        utils_giswater.set_item_data(self.dlg_wsoptions.rtc_period_id, rows, 1)

        sql = "SELECT id, id FROM "+self.schema_name+".inp_value_opti_rtc_coef ORDER BY id"
        rows = self.controller.get_rows(sql)
        utils_giswater.set_item_data(self.dlg_wsoptions.rtc_coefficient, rows)

        # TODO
        if self.dlg_wsoptions.valve_mode.currentText() != "MINCUT RESULTS":
            self.dlg_wsoptions.valve_mode_mincut_result.setEnabled(False)

        if self.dlg_wsoptions.hydraulics.currentText() == "":
            self.dlg_wsoptions.hydraulics_fname.setEnabled(False)
        else:
            self.dlg_wsoptions.hydraulics_fname.setEnabled(True)

        # TODO
        if self.dlg_wsoptions.quality.currentText() == "TRACE":
            self.dlg_wsoptions.node_id.setEnabled(False)
        else:
            self.dlg_wsoptions.node_id.setEnabled(True)

        if utils_giswater.isChecked(self.dlg_wsoptions, self.dlg_wsoptions.rtc_enabled):
            self.dlg_wsoptions.rtc_period_id.setEnabled(True)
            self.dlg_wsoptions.rtc_coefficient.setEnabled(True)
            
        self.dlg_wsoptions.unbalanced.currentIndexChanged.connect(
            partial(self.enable_linetext, self.dlg_wsoptions, self.dlg_wsoptions.unbalanced, self.dlg_wsoptions.unbalanced_n, "STOP"))
        self.dlg_wsoptions.hydraulics.currentIndexChanged.connect(
            partial(self.enable_linetext, self.dlg_wsoptions, self.dlg_wsoptions.hydraulics, self.dlg_wsoptions.hydraulics_fname, ""))
        self.dlg_wsoptions.quality.currentIndexChanged.connect(
            partial(self.enable_linetext, self.dlg_wsoptions, self.dlg_wsoptions.quality, self.dlg_wsoptions.node_id, "TRACE"))
        self.dlg_wsoptions.valve_mode.currentIndexChanged.connect(
            partial(self.enable_linetext, self.dlg_wsoptions, self.dlg_wsoptions.valve_mode, self.dlg_wsoptions.valve_mode_mincut_result, ("EPA TABLES", "INVENTORY VALUES")))
        self.dlg_wsoptions.rtc_enabled.stateChanged.connect(self.enable_per_coef)

        self.dlg_wsoptions.btn_accept.clicked.connect(
            partial(self.update_table, 'inp_options', self.dlg_wsoptions))
        self.dlg_wsoptions.btn_cancel.clicked.connect(self.dlg_wsoptions.close)
        self.go2epa_options_get_data('inp_options', self.dlg_wsoptions)
        self.dlg_wsoptions.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.dlg_wsoptions.exec_()
Example #13
0
    def edit_config_edit_accept(self):

        if utils_giswater.isChecked("chk_state_vdefault"):
            self.insert_or_update_config_param_curuser(self.dlg.state_vdefault, "state_vdefault", "config_param_user")
        else:
            self.delete_row("state_vdefault", "config_param_user")
        if utils_giswater.isChecked("chk_workcat_vdefault"):
            self.insert_or_update_config_param_curuser(self.dlg.workcat_vdefault, "workcat_vdefault", "config_param_user")
        else:
            self.delete_row("workcat_vdefault", "config_param_user")
        if utils_giswater.isChecked("chk_verified_vdefault"):
            self.insert_or_update_config_param_curuser(self.dlg.verified_vdefault, "verified_vdefault", "config_param_user")
        else:
            self.delete_row("verified_vdefault", "config_param_user")
        if utils_giswater.isChecked("chk_builtdate_vdefault"):
            self.insert_or_update_config_param_curuser(self.dlg.builtdate_vdefault, "builtdate_vdefault", "config_param_user")
        else:
            self.delete_row("builtdate_vdefault", "config_param_user")
        if utils_giswater.isChecked("chk_enddate_vdefault"):
            self.insert_or_update_config_param_curuser(self.dlg.enddate_vdefault, "enddate_vdefault", "config_param_user")
        else:
            self.delete_row("enddate_vdefault", "config_param_user")
        if utils_giswater.isChecked("chk_arccat_vdefault"):
            self.insert_or_update_config_param_curuser(self.dlg.arccat_vdefault, "arccat_vdefault", "config_param_user")
        else:
            self.delete_row("arccat_vdefault", "config_param_user")
        if utils_giswater.isChecked("chk_nodecat_vdefault"):
            self.insert_or_update_config_param_curuser(self.dlg.nodecat_vdefault, "nodecat_vdefault", "config_param_user")
        else:
            self.delete_row("nodecat_vdefault", "config_param_user")
        if utils_giswater.isChecked("chk_connecat_vdefault"):
            self.insert_or_update_config_param_curuser(self.dlg.connecat_vdefault, "connecat_vdefault", "config_param_user")
        else:
            self.delete_row("connecat_vdefault", "config_param_user")
        if utils_giswater.isChecked("chk_elementcat_vdefault"):
            self.insert_or_update_config_param_curuser(self.dlg.elementcat_vdefault, "elementcat_vdefault", "config_param_user")
        else:
            self.delete_row("elementcat_vdefault", "config_param_user")
        if utils_giswater.isChecked("chk_exploitation_vdefault"):
            self.insert_or_update_config_param_curuser(self.dlg.exploitation_vdefault, "exploitation_vdefault", "config_param_user")
        else:
            self.delete_row("exploitation_vdefault", "config_param_user")
        if utils_giswater.isChecked("chk_municipality_vdefault"):
            self.insert_or_update_config_param_curuser(self.dlg.municipality_vdefault, "municipality_vdefault", "config_param_user")
        else:
            self.delete_row("municipality_vdefault", "config_param_user")
        if utils_giswater.isChecked("chk_visitcat_vdefault"):
            self.insert_or_update_config_param_curuser(self.dlg.visitcat_vdefault, "visitcat_vdefault", "config_param_user")
        else:
            self.delete_row("visitcat_vdefault", "config_param_user")

        # UD
        if utils_giswater.isChecked("chk_nodetype_vdefault"):
            sql = "SELECT name FROM " + self.schema_name + ".value_state WHERE id::text = "
            sql += "(SELECT value FROM " + self.schema_name + ".config_param_user WHERE parameter = 'exploitation_vdefault')::text"
            row = self.controller.get_row(sql)
            if row:
                utils_giswater.setWidgetText("exploitation_vdefault", str(row[0]))
            self.insert_or_update_config_param_curuser(self.dlg.nodetype_vdefault, "nodetype_vdefault", "config_param_user")
        else:
            self.delete_row("nodetype_vdefault", "config_param_user")
        if utils_giswater.isChecked("chk_arctype_vdefault"):
            self.insert_or_update_config_param_curuser(self.dlg.arctype_vdefault, "arctype_vdefault", "config_param_user")
        else:
            self.delete_row("arctype_vdefault", "config_param_user")
        if utils_giswater.isChecked("chk_connectype_vdefault"):
            self.insert_or_update_config_param_curuser(self.dlg.connectype_vdefault, "connectype_vdefault", "config_param_user")
        else:
            self.delete_row("connectype_vdefault", "config_param_user")

        message = "Values has been updated"
        self.controller.show_info(message)
        self.close_dialog(self.dlg)
Example #14
0
    def insert_or_update_new_psector(self, update, tablename):

        sql = "SELECT *"
        sql += " FROM " + self.schema_name + "." + tablename
        row = self.dao.get_row(sql)
        columns = []
        for i in range(0, len(row)):
            column_name = self.dao.get_column_name(i)
            columns.append(column_name)

        if update:
            if columns is not None:
                sql = "UPDATE " + self.schema_name + "." + tablename + " SET "
                for column_name in columns:
                    if column_name != 'psector_id':
                        widget_type = utils_giswater.getWidgetType(column_name)
                        if widget_type is QCheckBox:
                            value = utils_giswater.isChecked(column_name)
                        elif widget_type is QDateEdit:
                            date = self.dlg.findChild(QDateEdit, str(column_name))
                            value = date.dateTime().toString('yyyy-MM-dd HH:mm:ss')
                        else:
                            value = utils_giswater.getWidgetText(column_name)
                        if value is None or value == 'null':
                            sql += column_name + " = null, "
                        else:
                            if type(value) is not bool:
                                value = value.replace(",", ".")
                            sql += column_name + " = '" + str(value) + "', "

                sql = sql[:len(sql) - 2]
                sql += " WHERE psector_id = '" + self.psector_id.text() + "'"

        else:
            values = "VALUES("
            if columns is not None:
                sql = "INSERT INTO " + self.schema_name + "." + tablename+" ("
                for column_name in columns:
                    if column_name != 'psector_id':
                        widget_type = utils_giswater.getWidgetType(column_name)
                        if widget_type is not None:
                            if widget_type is QCheckBox:
                                values += utils_giswater.isChecked(column_name)+", "
                            elif widget_type is QDateEdit:
                                date = self.dlg.findChild(QDateEdit, str(column_name))
                                values += date.dateTime().toString('yyyy-MM-dd HH:mm:ss')+", "
                            else:
                                value = utils_giswater.getWidgetText(column_name)
                            if value is None or value == 'null':
                                sql += column_name + ", "
                                values += "null, "
                            else:
                                values += "'" + value + "',"
                                sql += column_name + ", "
                sql = sql[:len(sql) - 2]+") "
                values = values[:len(values)-2] + ")"
                sql += values
                
        self.controller.execute_sql(sql)
        
        self.close_dialog()
Example #15
0
 def enable_per_coef(self):
     """ Enable or dissable cbx """
     self.dlg_wsoptions.rtc_period_id.setEnabled(
         utils_giswater.isChecked("chk_enabled"))
     self.dlg_wsoptions.rtc_coefficient.setEnabled(
         utils_giswater.isChecked("chk_enabled"))
    def insert_or_update_new_psector(self, update, tablename, close_dlg=False):

        psector_name = utils_giswater.getWidgetText(self.dlg.name, return_string_null=False)
        if psector_name == "":
            message = "Mandatory field is missing. Please, set a value"
            self.controller.show_warning(message, parameter='Name')
            return

        rotation = utils_giswater.getWidgetText(self.dlg.rotation, return_string_null=False)
        if rotation == "":
            utils_giswater.setWidgetText(self.dlg.rotation, 0)

        name_exist = self.check_name(psector_name)
        if name_exist and not update:
            message = "The name is current in use"
            self.controller.show_warning(message)
            return
        else:
            self.enable_tabs(True)
            self.enable_buttons(True)

        sql = ("SELECT column_name FROM information_schema.columns"
               " WHERE table_name = '" + "v_edit_" + self.plan_om + "_psector'"
               " AND table_schema = '" + self.schema_name.replace('"', '') + "'"
               " ORDER BY ordinal_position")
        rows = self.controller.get_rows(sql)

        columns = []
        for i in range(0, len(rows)):
            column_name = rows[i]
            columns.append(str(column_name[0]))

        if update:
            if columns:
                sql = "UPDATE " + self.schema_name + "." + tablename + " SET "
                for column_name in columns:
                    if column_name != 'psector_id':
                        widget_type = utils_giswater.getWidgetType(column_name)
                        if widget_type is QCheckBox:
                            value = utils_giswater.isChecked(column_name)
                        elif widget_type is QDateEdit:
                            date = self.dlg.findChild(QDateEdit, str(column_name))
                            value = date.dateTime().toString('yyyy-MM-dd HH:mm:ss')
                        elif (widget_type is QComboBox) and (column_name == 'expl_id' or column_name == 'sector_id'
                              or column_name == 'result_id' or column_name == 'psector_type'):
                            combo = utils_giswater.getWidget(column_name)
                            elem = combo.itemData(combo.currentIndex())
                            value = str(elem[0])
                        else:
                            value = utils_giswater.getWidgetText(column_name)
                        if value is None or value == 'null':
                            sql += column_name + " = null, "
                        else:
                            if type(value) is not bool:
                                value = value.replace(",", ".")
                            sql += column_name + " = '" + str(value) + "', "

                sql = sql[:len(sql) - 2]
                sql += " WHERE psector_id = '" + utils_giswater.getWidgetText(self.psector_id) + "'"

        else:
            values = "VALUES("
            if columns:
                sql = "INSERT INTO " + self.schema_name + "." + tablename + " ("
                for column_name in columns:
                    if column_name != 'psector_id':
                        widget_type = utils_giswater.getWidgetType(column_name)
                        if widget_type is not None:
                            if widget_type is QCheckBox:
                                value = str(utils_giswater.isChecked(column_name)).upper()
                            elif widget_type is QDateEdit:
                                date = self.dlg.findChild(QDateEdit, str(column_name))
                                values += date.dateTime().toString('yyyy-MM-dd HH:mm:ss') + ", "
                            elif (widget_type is QComboBox) and (column_name == 'expl_id' or column_name == 'sector_id'
                                or column_name == 'result_id' or column_name == 'psector_type'):
                                combo = utils_giswater.getWidget(column_name)
                                elem = combo.itemData(combo.currentIndex())
                                value = str(elem[0])
                            else:
                                value = utils_giswater.getWidgetText(column_name)
                            if value is None or value == 'null':
                                sql += column_name + ", "
                                values += "null, "
                            else:
                                values += "'" + value + "', "
                                sql += column_name + ", "

                sql = sql[:len(sql) - 2] + ") "
                values = values[:len(values) - 2] + ")"
                sql += values

        if not update:
            sql += " RETURNING psector_id"
            new_psector_id = self.controller.execute_returning(sql, search_audit=False, log_sql=True)
            utils_giswater.setText(self.dlg.psector_id, str(new_psector_id[0]))

            if new_psector_id and self.plan_om == 'plan':
                sql = ("SELECT parameter FROM " + self.schema_name + ".config_param_user "
                       " WHERE parameter = 'psector_vdefault' AND cur_user = current_user")
                row = self.controller.get_row(sql)
                if row:
                    sql = ("UPDATE " + self.schema_name + ".config_param_user "
                           " SET value = '" + str(new_psector_id[0]) + "' "
                           " WHERE parameter = 'psector_vdefault'")
                else:
                    sql = ("INSERT INTO " + self.schema_name + ".config_param_user (parameter, value, cur_user) "
                           " VALUES ('psector_vdefault', '" + str(new_psector_id[0]) + "', current_user)")
                self.controller.execute_sql(sql, log_sql=True)
        else:
            self.controller.execute_sql(sql, log_sql=True)
            
        self.dlg.tabWidget.setTabEnabled(1, True)
        self.insert_psector_selector(self.plan_om+'_psector_selector', 'psector_id', utils_giswater.getWidgetText(self.dlg.psector_id))

        if close_dlg:
            self.reload_states_selector()
            self.close_dialog()
Example #17
0
    def insert_or_update(self, update, tablename, dialog):
        """ INSERT or UPDATE tables according :param update"""

        sql = "SELECT *"
        sql += " FROM " + self.schema_name + "." + tablename
        row = self.dao.get_row(sql)

        columns = []
        for i in range(0, len(row)):
            column_name = self.dao.get_column_name(i)
            columns.append(column_name)

        if update:
            if columns is not None:
                sql = "UPDATE " + self.schema_name + "." + tablename + " SET "
                for column_name in columns:
                    if column_name != 'id':
                        widget_type = utils_giswater.getWidgetType(column_name)
                        if widget_type is QCheckBox:
                            value = utils_giswater.isChecked(column_name)
                        elif widget_type is QDateEdit:
                            date = dialog.findChild(QDateEdit,
                                                    str(column_name))
                            value = date.dateTime().toString('yyyy-MM-dd')
                        elif widget_type is QTimeEdit:
                            aux = 0
                            widget_day = str(column_name) + "_day"
                            day = utils_giswater.getText(widget_day)
                            if day != "null":
                                aux = int(day) * 24
                            time = dialog.findChild(QTimeEdit,
                                                    str(column_name))
                            timeparts = time.dateTime().toString(
                                'HH:mm:ss').split(':')
                            h = int(timeparts[0]) + int(aux)
                            aux = str(h) + ":" + str(timeparts[1]) + ":00"
                            value = aux
                        elif widget_type is QSpinBox:
                            x = dialog.findChild(QSpinBox, str(column_name))
                            value = x.value()
                        else:
                            value = utils_giswater.getWidgetText(column_name)
                        if value == 'null':
                            sql += column_name + " = null, "
                        elif value is None:
                            pass
                        else:
                            if type(
                                    value
                            ) is not bool and widget_type is not QSpinBox:
                                value = value.replace(",", ".")
                            sql += column_name + " = '" + str(value) + "', "
                sql = sql[:len(sql) - 2]
        else:
            values = "VALUES("
            if columns is not None:
                sql = "INSERT INTO " + self.schema_name + "." + tablename + " ("
                for column_name in columns:
                    if column_name != 'id':
                        widget_type = utils_giswater.getWidgetType(column_name)
                        if widget_type is not None:
                            if widget_type is QCheckBox:
                                values += utils_giswater.isChecked(
                                    column_name) + ", "
                            elif widget_type is QDateEdit:
                                date = dialog.findChild(
                                    QDateEdit, str(column_name))
                                values += date.dateTime().toString(
                                    'yyyy-MM-dd') + ", "
                            else:
                                value = utils_giswater.getWidgetText(
                                    column_name)
                            if value is None or value == 'null':
                                sql += column_name + ", "
                                values += "null, "
                            else:
                                values += "'" + value + "',"
                                sql += column_name + ", "
                sql = sql[:len(sql) - 2] + ") "
                values = values[:len(values) - 2] + ")"
                sql += values
        self.controller.execute_sql(sql)
        dialog.close()
    def canvasReleaseEvent(self, event):

        if event.button() == Qt.RightButton:
            self.cancel_map_tool()
            return

        # Get the click
        x = event.pos().x()
        y = event.pos().y()
        event_point = QPoint(x, y)
        snapped_feat = None

        # Snapping
        (retval,
         result) = self.snapper.snapToCurrentLayer(event_point,
                                                   2)  # @UnusedVariable

        if result:
            # Get the first feature
            snapped_feat = result[0]
            point = QgsPoint(snapped_feat.snappedVertex)  #@UnusedVariable
            snapped_feat = next(
                snapped_feat.layer.getFeatures(
                    QgsFeatureRequest().setFilterFid(
                        result[0].snappedAtGeometry)))

        if snapped_feat:

            # Get 'node_id' and 'nodetype'
            node_id = snapped_feat.attribute('node_id')
            if self.project_type == 'ws':
                nodetype_id = snapped_feat.attribute('nodetype_id')
            elif self.project_type == 'ud':
                nodetype_id = snapped_feat.attribute('node_type')
            layer = self.controller.get_layer_by_nodetype(nodetype_id,
                                                          log_info=True)
            if not layer:
                return

            # Ask question before executing
            message = "Are you sure you want to replace selected node with a new one?"
            answer = self.controller.ask_question(message, "Replace node")
            if answer:
                # Execute SQL function and show result to the user
                function_name = "gw_fct_node_replace"
                sql = ("SELECT " + self.schema_name + "." + function_name +
                       "('" + str(node_id) + "', '" + self.workcat_id_end_aux +
                       "', '" + str(self.enddate_aux) + "', '" +
                       str(utils_giswater.isChecked("keep_elements")) + "');")
                new_node_id = self.controller.get_row(sql, commit=True)
                if new_node_id:
                    message = "Node replaced successfully"
                    self.controller.show_info(message)
                    self.iface.setActiveLayer(layer)
                    self.force_active_layer = False
                    self.open_custom_form(layer, new_node_id)
                else:
                    message = "Error replacing node"
                    self.controller.show_warning(message)

                # Refresh map canvas
                self.refresh_map_canvas()

            # Deactivate map tool
            self.deactivate()
            self.set_action_pan()