def get_parcel_right_relationship_errors(self, db, error_layer, table_name): query_parcels_with_no_right = db.logic_validation_queries[ 'PARCELS_WITH_NO_RIGHT']['query'] table = db.logic_validation_queries['PARCELS_WITH_NO_RIGHT']['table'] parcels_no_right = db.execute_sql_query_dict_cursor( query_parcels_with_no_right) query_parcels_with_repeated_domain_right = db.logic_validation_queries[ 'PARCELS_WITH_REPEATED_DOMAIN_RIGHT']['query'] parcels_repeated_domain_right = db.execute_sql_query_dict_cursor( query_parcels_with_repeated_domain_right) parcel_no_right_ids = [sublist[0] for sublist in parcels_no_right] parcel_duplicated_domain_right_ids = [ sublist[0] for sublist in parcels_repeated_domain_right ] if error_layer is None: error_layer = QgsVectorLayer( "NoGeometry?crs=EPSG:{}".format(DEFAULT_EPSG), table_name, "memory") pr = error_layer.dataProvider() pr.addAttributes([ QgsField( QCoreApplication.translate( "QGISUtils", "{table}_id").format(table=table), QVariant.Int), QgsField(QCoreApplication.translate("QGISUtils", "error_type"), QVariant.String) ]) error_layer.updateFields() new_features = list() for parcel_id in parcel_no_right_ids: new_feature = QgsVectorLayerUtils().createFeature( error_layer, QgsGeometry(), { 0: parcel_id, 1: translated_strings.ERROR_PARCEL_WITH_NO_RIGHT }) new_features.append(new_feature) for parcel_id in parcel_duplicated_domain_right_ids: new_feature = QgsVectorLayerUtils().createFeature( error_layer, QgsGeometry(), { 0: parcel_id, 1: translated_strings.ERROR_PARCEL_WITH_REPEATED_DOMAIN_RIGHT }) new_features.append(new_feature) error_layer.dataProvider().addFeatures(new_features) return len(new_features), error_layer
def col_party_type_natural_validation(self, db, rule, error_layer): query = db.logic_validation_queries[rule]['query'] table_name = db.logic_validation_queries[rule]['table_name'] table = db.logic_validation_queries[rule]['table'] if error_layer is None: error_layer = QgsVectorLayer("NoGeometry?crs=EPSG:{}".format(DEFAULT_EPSG), table_name, "memory") pr = error_layer.dataProvider() pr.addAttributes([QgsField(QCoreApplication.translate("QGISUtils", "{table}_id").format(table=table), QVariant.Int), QgsField(QCoreApplication.translate("QGISUtils", "error_type"), QVariant.String)]) error_layer.updateFields() records = db.execute_sql_query(query) new_features = list() for record in records: errors_list = list() if record[COL_PARTY_BUSINESS_NAME_FIELD] > 0: errors_list.append(QCoreApplication.translate("LogicChecksConfigStrings", "{business_name} must be NULL").format(business_name=COL_PARTY_BUSINESS_NAME_FIELD)) if record[COL_PARTY_LEGAL_PARTY_FIELD] > 0: errors_list.append(QCoreApplication.translate("LogicChecksConfigStrings", "{legal_party} must be NULL").format(legal_party=COL_PARTY_LEGAL_PARTY_FIELD)) if record[COL_PARTY_SURNAME_FIELD] > 0: errors_list.append(QCoreApplication.translate("LogicChecksConfigStrings", "{surname_party} must not be NULL and It must be filled in").format(surname_party=COL_PARTY_SURNAME_FIELD)) if record[COL_PARTY_FIRST_NAME_FIELD] > 0: errors_list.append(QCoreApplication.translate("LogicChecksConfigStrings", "{first_name_party} must not be NULL and It must be filled in").format(first_name_party=COL_PARTY_FIRST_NAME_FIELD)) if record[COL_PARTY_DOC_TYPE_FIELD] > 0: errors_list.append(QCoreApplication.translate("LogicChecksConfigStrings", "{doc_type} must be different from NIT").format(doc_type=COL_PARTY_DOC_TYPE_FIELD)) mgs_error = ', '. join(errors_list) new_feature = QgsVectorLayerUtils().createFeature(error_layer, QgsGeometry(), {0: record[ID_FIELD], 1:mgs_error}) new_features.append(new_feature) error_layer.dataProvider().addFeatures(new_features) return len(new_features), error_layer
def get_fractions_which_sum_is_not_one(self, db, error_layer): rule = 'GROUP_PARTY_FRACTIONS_SHOULD_SUM_1' query = db.logic_validation_queries[rule]['query'] table_name = db.logic_validation_queries[rule]['table_name'] if error_layer is None: error_layer = QgsVectorLayer("NoGeometry?crs=EPSG:{}".format(DEFAULT_EPSG), table_name, "memory") pr = error_layer.dataProvider() pr.addAttributes([QgsField(QCoreApplication.translate("QGISUtils", "party_group"), QVariant.Int), QgsField(QCoreApplication.translate("QGISUtils", "members"), QVariant.String), QgsField(QCoreApplication.translate("QGISUtils", "fraction_sum"), QVariant.Double)]) error_layer.updateFields() records = db.execute_sql_query(query) new_features = list() for record in records: new_feature = QgsVectorLayerUtils().createFeature( error_layer, QgsGeometry(), {0: record['agrupacion'], 1: ",".join([str(f) for f in record['miembros']]), 2: record['suma_fracciones']}) new_features.append(new_feature) error_layer.dataProvider().addFeatures(new_features) return error_layer
def finish_group_party_saving(self, members, layer_id, features): try: self._la_group_party_table.committedFeaturesAdded.disconnect() except TypeError as e: pass if len(features) != 1: self.log.logMessage("We should have got only one group party... We cannot do anything with {} group parties".format(len(features)), PLUGIN_NAME, Qgis.Warning) else: fid = features[0].id() if not self._la_group_party_table.getFeature(fid).isValid(): self.log.logMessage("Feature not found in table Group Party...", PLUGIN_NAME, Qgis.Warning) else: group_party_id = self._la_group_party_table.getFeature(fid)[ID_FIELD] # Now save members for party_id, fraction in members.items(): # Create connections to react when a group party is stored to the DB self._members_table.committedFeaturesAdded.connect(partial(self.finish_member_saving, fraction)) new_feature = QgsVectorLayerUtils().createFeature(self._members_table) new_feature.setAttribute(MEMBERS_GROUP_PARTY_FIELD, group_party_id) new_feature.setAttribute(MEMBERS_PARTY_FIELD, party_id) self.log.logMessage("Saving group party's member ({}: {}).".format(group_party_id, party_id), PLUGIN_NAME, Qgis.Info) with edit(self._members_table): self._members_table.addFeature(new_feature)
def create_plots_from_boundaries(self): selected_boundaries = self.__layers[ self.names.LC_BOUNDARY_T].selectedFeatures() boundary_geometries = [f.geometry() for f in selected_boundaries] collection = QgsGeometry().polygonize(boundary_geometries) features = list() for polygon in collection.asGeometryCollection(): feature = QgsVectorLayerUtils().createFeature( self.__editing_layer, polygon) features.append(feature) if not features: return EnumPlotCreationResult.NO_PLOTS_CREATED if not self.__editing_layer.isEditable(): self.__editing_layer.startEditing() self.__editing_layer.addFeatures(features) self.__iface.mapCanvas().refresh() message = QCoreApplication.translate( "WizardTranslations", "{} new plot(s) has(have) been created! To finish the creation of the plots, open its attribute table and fill in the mandatory fields." ).format(len(features)) button_text = QCoreApplication.translate("WizardTranslations", "Open table of attributes") level = Qgis.Info layer = self.__editing_layer filter = '"{}" is Null'.format(self.names.LC_PLOT_T_PLOT_AREA_F) self.__logger.message_with_button_open_table_attributes_emitted.emit( message, button_text, level, layer, filter) # self.close_wizard(show_message=False) return EnumPlotCreationResult.CREATED
def finish_member_saving(self, fraction, layer_id, features): try: self._layers[self.names.MEMBERS_T].committedFeaturesAdded.disconnect() except TypeError as e: pass if len(features) != 1: self.logger.warning(__name__, "We should have got only one member... We cannot do anything with {} members".format(len(features))) else: fid = features[0].id() if not self._layers[self.names.MEMBERS_T].getFeature(fid).isValid(): self.logger.warning(__name__, "Feature not found in table Members...") else: member_id = self._layers[self.names.MEMBERS_T].getFeature(fid)[self.names.T_ID_F] if fraction == [0, 0]: return # And finally save fractions new_feature = QgsVectorLayerUtils().createFeature(self._layers[self.names.FRACTION_S]) new_feature.setAttribute(self.names.FRACTION_S_MEMBER_F, member_id) new_feature.setAttribute(self.names.FRACTION_S_NUMERATOR_F, fraction[0]) new_feature.setAttribute(self.names.FRACTION_S_DENOMINATOR_F, fraction[1]) with edit(self._layers[self.names.FRACTION_S]): self.logger.info(__name__, "Saving member's fraction ({}: {}).".format(member_id, fraction)) self._layers[self.names.FRACTION_S].addFeature(new_feature)
def finish_right(self, administrative_source_ids, layerId, features): if len(features) != 1: self.log.logMessage("We should have got only one right... We cannot do anything with {} rights".format(len(features)), PLUGIN_NAME, Qgis.Warning) else: fid = features[0].id() if not self._right_layer.getFeature(fid).isValid(): self.log.logMessage("Feature not found in layer Right...", PLUGIN_NAME, Qgis.Warning) else: right_id = self._right_layer.getFeature(fid)[ID_FIELD] # Fill rrrfuente table new_features = [] for administrative_source_id in administrative_source_ids: new_feature = QgsVectorLayerUtils().createFeature(self._rrr_source_relation_layer) new_feature.setAttribute(RRR_SOURCE_SOURCE_FIELD, administrative_source_id) new_feature.setAttribute(RRR_SOURCE_RIGHT_FIELD, right_id) self.log.logMessage("Saving Administrative_source-Right: {}-{}".format(administrative_source_id, right_id), PLUGIN_NAME, Qgis.Info) new_features.append(new_feature) self._rrr_source_relation_layer.dataProvider().addFeatures(new_features) self.iface.messageBar().pushMessage("Asistente LADM_COL", QCoreApplication.translate("CreateRightCadastreWizard", "The new right (t_id={}) was successfully created and associated with its corresponding administrative source (t_id={})!".format(right_id, administrative_source_ids[0])), Qgis.Info) self._right_layer.committedFeaturesAdded.disconnect() self.log.logMessage("Right's committedFeaturesAdded SIGNAL disconnected", PLUGIN_NAME, Qgis.Info)
def add_oid_feature(self): # Add OID record self._oid_layer.startEditing() feature = QgsVectorLayerUtils().createFeature(self._oid_layer) feature.setAttribute(OID_EXTADDRESS_ID_FIELD, self._extaddress_tid) self._oid_layer.addFeature(feature) self._oid_layer.commitChanges()
def basic_logic_validations(self, db, records, rule, error_code): """ Create an error table with the errors found :param db: db connection :param records: Result of execute the query :param rule: Quality rule config (Contains info like table_name: Error table name and rule_name: Rule error description (Name of rule to show in log quality rules)). Note: rule_name is used by _log_quality_rules decorator """ error_layer = QgsVectorLayer("NoGeometry", rule.error_table_name, "memory") pr = error_layer.dataProvider() pr.addAttributes(rule.error_table_fields) error_layer.updateFields() new_features = [] for record in records: new_feature = QgsVectorLayerUtils().createFeature( error_layer, QgsGeometry(), { 0: record[db.names.T_ILI_TID_F], 1: self.quality_rules_manager.get_error_message(error_code), 2: error_code }) new_features.append(new_feature) error_layer.dataProvider().addFeatures(new_features) return self.return_message(db, rule.rule_name, error_layer)
def check_duplicate_records_in_a_table(self, db, table, fields, rule_code): rule = self.quality_rules_manager.get_quality_rule(rule_code) error_layer = QgsVectorLayer("NoGeometry", rule.error_table_name, "memory") pr = error_layer.dataProvider() pr.addAttributes(rule.error_table_fields) error_layer.updateFields() res, records = self.get_ladm_queries( db.engine).get_duplicate_records_in_table(db, table, fields) error_code = rule.error_codes[ 0] # Each non-duplicate-records rule has a single and different error code if res: new_features = list() for record in records: new_feature = QgsVectorLayerUtils().createFeature( error_layer, QgsGeometry(), { 0: record['duplicate_uuids'], 1: record['duplicate_total'], 2: self.quality_rules_manager.get_error_message( error_code), 3: error_code }) new_features.append(new_feature) error_layer.dataProvider().addFeatures(new_features) else: self.logger.error_msg( __name__, "Error executing query for rule check duplicate records in a table: {}" .format(records)) return self.return_message(db, rule.error_table_name, error_layer)
def finish_feature_creation(self, layerId, features): message = QCoreApplication.translate( self.WIZARD_NAME, "'{}' tool has been closed because an error occurred while trying to save the data." ).format(self.WIZARD_TOOL_NAME) if len(features) != 1: message = QCoreApplication.translate( self.WIZARD_NAME, "'{}' tool has been closed. We should have got only one responsibility... We cannot do anything with {} responsibility" ).format(self.WIZARD_TOOL_NAME, len(features)) self.log.logMessage( "We should have got only one Responsibility... We cannot do anything with {} responsibility" .format(len(features)), PLUGIN_NAME, Qgis.Warning) else: fid = features[0].id() administrative_source_ids = [ f['t_id'] for f in self._layers[ADMINISTRATIVE_SOURCE_TABLE] [LAYER].selectedFeatures() ] if not self._layers[self.EDITING_LAYER_NAME][LAYER].getFeature( fid).isValid(): self.log.logMessage( "Feature not found in layer Responsibility...", PLUGIN_NAME, Qgis.Warning) else: responsibility_id = self._layers[ self.EDITING_LAYER_NAME][LAYER].getFeature(fid)[ID_FIELD] # Fill rrrfuente table new_features = [] for administrative_source_id in administrative_source_ids: new_feature = QgsVectorLayerUtils().createFeature( self._layers[RRR_SOURCE_RELATION_TABLE][LAYER]) new_feature.setAttribute(RRR_SOURCE_SOURCE_FIELD, administrative_source_id) new_feature.setAttribute(RRR_SOURCE_RESPONSIBILITY_FIELD, responsibility_id) self.log.logMessage( "Saving Administrative_source-Responsibility: {}-{}". format(administrative_source_id, responsibility_id), PLUGIN_NAME, Qgis.Info) new_features.append(new_feature) self._layers[RRR_SOURCE_RELATION_TABLE][LAYER].dataProvider( ).addFeatures(new_features) message = QCoreApplication.translate( self.WIZARD_NAME, "The new responsibility (t_id={}) was successfully created and associated with its corresponding administrative source (t_id={})!" ).format( responsibility_id, ", ".join([str(b) for b in administrative_source_ids])) self._layers[self.EDITING_LAYER_NAME][ LAYER].committedFeaturesAdded.disconnect() self.log.logMessage( "Responsibility's committedFeaturesAdded SIGNAL disconnected", PLUGIN_NAME, Qgis.Info) self.close_wizard(message)
def finish_member_saving(self, fraction, layer_id, features): try: self._members_table.committedFeaturesAdded.disconnect() except TypeError as e: pass if len(features) != 1: self.log.logMessage( "We should have got only one member... We cannot do anything with {} members" .format(len(features)), PLUGIN_NAME, Qgis.Warning) else: fid = features[0].id() if not self._members_table.getFeature(fid).isValid(): self.log.logMessage("Feature not found in table Members...", PLUGIN_NAME, Qgis.Warning) else: member_id = self._members_table.getFeature(fid)[ID_FIELD] if fraction == [0, 0]: return # And finally save fractions new_feature = QgsVectorLayerUtils().createFeature( self._fraction_table) new_feature.setAttribute(FRACTION_MEMBER_FIELD, member_id) new_feature.setAttribute(FRACTION_NUMERATOR_FIELD, fraction[0]) new_feature.setAttribute(FRACTION_DENOMINATOR_FIELD, fraction[1]) with edit(self._fraction_table): self.log.logMessage( "Saving member's fraction ({}: {}).".format( member_id, fraction), PLUGIN_NAME, Qgis.Info) self._fraction_table.addFeature(new_feature)
def finish_right_of_way_line(self, width_value, iface): self._right_of_way_line_layer.committedFeaturesAdded.disconnect() self.log.logMessage( "RigthOfWayLine's committedFeaturesAdded SIGNAL disconnected", PLUGIN_NAME, Qgis.Info) params = { 'INPUT': self._right_of_way_line_layer, 'DISTANCE': width_value, 'SEGMENTS': 5, 'END_CAP_STYLE': 1, # Flat 'JOIN_STYLE': 2, 'MITER_LIMIT': 2, 'DISSOLVE': False, 'OUTPUT': 'memory:' } buffered_right_of_way_layer = processing.run("native:buffer", params)['OUTPUT'] buffer_geometry = buffered_right_of_way_layer.getFeature(1).geometry() feature = QgsVectorLayerUtils().createFeature(self._right_of_way_layer, buffer_geometry) if feature: self._right_of_way_layer.startEditing() self._right_of_way_layer.addFeature(feature) form = iface.getFeatureForm(self._right_of_way_layer, feature) form.show()
def post_save(self, features): message = QCoreApplication.translate("WizardTranslations", "'{}' tool has been closed because an error occurred while trying to save the data.").format(self.WIZARD_TOOL_NAME) if len(features) != 1: message = QCoreApplication.translate("WizardTranslations", "'{}' tool has been closed. We should have got only one {} by we have {}").format(self.WIZARD_TOOL_NAME, self.WIZARD_FEATURE_NAME, len(features)) self.logger.warning(__name__, "We should have got only one {}, but we have {}".format(self.WIZARD_FEATURE_NAME, len(features))) else: fid = features[0].id() building_unit_ids = [f[self.names.T_ID_F] for f in self._layers[self.names.LC_BUILDING_UNIT_T].selectedFeatures()] if not self._layers[self.EDITING_LAYER_NAME].getFeature(fid).isValid(): self.logger.warning(__name__, "Feature not found in layer {}...".format(self.EDITING_LAYER_NAME)) else: building_unit_valuation_id = self._layers[self.EDITING_LAYER_NAME].getFeature(fid)[self.names.T_ID_F] # Fill avaluounidadconstruccion table new_features = [] for building_unit_id in building_unit_ids: new_feature = QgsVectorLayerUtils().createFeature(self._layers[LADMNames.AVALUOUNIDADCONSTRUCCION_TABLE]) new_feature.setAttribute(LADMNames.AVALUOUNIDADCONSTRUCCION_TABLE_BUILDING_UNIT_FIELD, building_unit_id) new_feature.setAttribute(LADMNames.AVALUOUNIDADCONSTRUCCION_TABLE_BUILDING_UNIT_VALUATION_FIELD, building_unit_valuation_id) self.logger.info(__name__, "Saving Building unit-Building unit valuation: {}-{}".format(building_unit_id, building_unit_valuation_id)) new_features.append(new_feature) self._layers[LADMNames.AVALUOUNIDADCONSTRUCCION_TABLE].dataProvider().addFeatures(new_features) if building_unit_ids: message = QCoreApplication.translate("WizardTranslations", "The new {} (t_id={}) was successfully created and associated with its corresponding building unit (t_id={})!").format(self.WIZARD_FEATURE_NAME, building_unit_valuation_id, building_unit_ids[0]) return message
def get_duplicate_records_in_a_table(self, db, table, fields, error_layer, id_field=ID_FIELD): rule = 'DUPLICATE_RECORDS_IN_TABLE' query = db.logic_validation_queries[rule]['query'] table_name = QCoreApplication.translate("LogicChecksConfigStrings", "Duplicate records in '{table}'").format(table=table) # config query query = query.format(schema=db.schema, table=table, fields=", ".join(fields), id=id_field) if error_layer is None: error_layer = QgsVectorLayer("NoGeometry?crs=EPSG:{}".format(DEFAULT_EPSG), table_name, "memory") pr = error_layer.dataProvider() pr.addAttributes([QgsField(QCoreApplication.translate("QGISUtils", "duplicate_ids"), QVariant.String), QgsField(QCoreApplication.translate("QGISUtils", "count"), QVariant.Int)]) error_layer.updateFields() records = db.execute_sql_query(query) new_features = list() for record in records: new_feature = QgsVectorLayerUtils().createFeature(error_layer, QgsGeometry(), {0: record['duplicate_ids'], 1: record['duplicate_total']}) new_features.append(new_feature) error_layer.dataProvider().addFeatures(new_features) return error_layer
def check_group_party_fractions_that_do_not_add_one(self, db): rule = self.quality_rules_manager.get_quality_rule( EnumQualityRule.Logic.FRACTION_SUM_FOR_PARTY_GROUPS) layers = {db.names.MEMBERS_T: None, db.names.LC_GROUP_PARTY_T: None} self.app.core.get_layers(db, layers, load=False) if not layers: return QCoreApplication.translate( "LogicQualityRules", "At least one required layer (members, group party) was not found!" ), Qgis.Critical dict_uuid_members = get_uuid_dict(layers[db.names.MEMBERS_T], db.names, db.names.T_ID_F) dict_uuid_group_party = get_uuid_dict( layers[db.names.LC_GROUP_PARTY_T], db.names, db.names.T_ID_F) error_layer = QgsVectorLayer("NoGeometry", rule.error_table_name, "memory") pr = error_layer.dataProvider() pr.addAttributes(rule.error_table_fields) error_layer.updateFields() res, records = self.get_ladm_queries( db.engine).get_group_party_fractions_that_do_not_make_one(db) if res: new_features = list() for record in records: new_feature = QgsVectorLayerUtils().createFeature( error_layer, QgsGeometry(), { 0: dict_uuid_group_party.get( record['agrupacion'] ), # Field alias as defined in the sql query 1: ",".join([ str(dict_uuid_members.get(int(t_id))) for t_id in record['miembros'].split(',') ]), 2: record['suma_fracciones'], 3: self.quality_rules_manager.get_error_message( QUALITY_RULE_ERROR_CODE_E400201), 4: QUALITY_RULE_ERROR_CODE_E400201 }) new_features.append(new_feature) error_layer.dataProvider().addFeatures(new_features) else: self.logger.error_msg( __name__, "Error executing query for rule {}: {}".format( rule.rule_name, records)) return self.return_message(db, rule.error_table_name, error_layer)
def finish_feature_creation(self, layerId, features): message = QCoreApplication.translate( self.WIZARD_NAME, "'{}' tool has been closed because an error occurred while trying to save the data." ).format(self.WIZARD_TOOL_NAME) if len(features) != 1: message = QCoreApplication.translate( self.WIZARD_NAME, "'{}' tool has been closed. We should have got only one spatial unit... We cannot do anything with {} spatials units" ).format(self.WIZARD_TOOL_NAME, len(features)) self.log.logMessage( "We should have got only one spatial unit... We cannot do anything with {} spatials units" .format(len(features)), PLUGIN_NAME, Qgis.Warning) else: fid = features[0].id() if not self._layers[self.EDITING_LAYER_NAME][LAYER].getFeature( fid).isValid(): message = QCoreApplication.translate( self.WIZARD_NAME, "'{}' tool has been closed. Feature not found in layer {}... It's not posible create a ExtAddress. " ).format(self.WIZARD_TOOL_NAME, self.EDITING_LAYER_NAME) self.log.logMessage( "Feature not found in layer {} ...".format( self.EDITING_LAYER_NAME), PLUGIN_NAME, Qgis.Warning) else: extaddress_tid = self._layers[ self.EDITING_LAYER_NAME][LAYER].getFeature(fid)[ID_FIELD] # Suppress (i.e., hide) feature form self.qgis_utils.suppress_form(self._layers[OID_TABLE][LAYER], True) # Add OID record self._layers[OID_TABLE][LAYER].startEditing() feature = QgsVectorLayerUtils().createFeature( self._layers[OID_TABLE][LAYER]) feature.setAttribute(OID_EXTADDRESS_ID_FIELD, extaddress_tid) self._layers[OID_TABLE][LAYER].addFeature(feature) self._layers[OID_TABLE][LAYER].commitChanges() # Don't suppress (i.e., show) feature form self.qgis_utils.suppress_form(self._layers[OID_TABLE][LAYER], False) message = QCoreApplication.translate( self.WIZARD_NAME, "The new extaddress (t_id={}) was successfully created " ).format(extaddress_tid) self._layers[ self.EDITING_LAYER_NAME][LAYER].committedFeaturesAdded.disconnect( self.finish_feature_creation) self.log.logMessage( "ExtAddress's committedFeaturesAdded SIGNAL disconnected", PLUGIN_NAME, Qgis.Info) self.close_wizard(message)
def uebaunit_parcel_validation(self, db, rule, error_layer): query = db.logic_validation_queries[rule]['query'] table_name = db.logic_validation_queries[rule]['table_name'] table = db.logic_validation_queries[rule]['table'] if error_layer is None: error_layer = QgsVectorLayer("NoGeometry?crs=EPSG:{}".format(DEFAULT_EPSG), table_name, "memory") pr = error_layer.dataProvider() pr.addAttributes([QgsField(QCoreApplication.translate("QGISUtils", "{table}_id").format(table=table), QVariant.Int), QgsField(QCoreApplication.translate("QGISUtils", "associated_parcels"), QVariant.Int), QgsField(QCoreApplication.translate("QGISUtils", "associated_buildings"), QVariant.Int), QgsField(QCoreApplication.translate("QGISUtils", "associated_building_units"), QVariant.Int), QgsField(QCoreApplication.translate("QGISUtils", "error_type"), QVariant.String)]) error_layer.updateFields() records = db.execute_sql_query(query) new_features = list() for record in records: mgs_error = None plot_count = record['sum_t'] # count of plots associated to the parcel building_count = record['sum_c'] # count of buildings associated to the parcel building_unit_count = record['sum_uc'] # count of building units associated to the parcel if record[PARCEL_TYPE_FIELD] == PARCEL_TYPE_NO_HORIZONTAL_PROPERTY: mgs_error = QCoreApplication.translate("LogicChecksConfigStrings", "When the {parcel_type_field} of {table} is '{parcel_type}' you should have 1 plot and 0 building unit but you have {plot_count} plot(s) and {building_unit_count} building unit(s)").format(plot_count=plot_count, building_unit_count=building_unit_count, table=PARCEL_TABLE, parcel_type_field=PARCEL_TYPE_FIELD, parcel_type=PARCEL_TYPE_NO_HORIZONTAL_PROPERTY) elif record[PARCEL_TYPE_FIELD] == PARCEL_TYPE_HORIZONTAL_PROPERTY_PARENT: mgs_error = QCoreApplication.translate("LogicChecksConfigStrings", "When the {parcel_type_field} of {table} is '{parcel_type}' you should have 1 plot and 0 building unit but you have {plot_count} plot(s) and {building_unit_count} building unit(s)").format(plot_count=plot_count, building_unit_count=building_unit_count, table=PARCEL_TABLE, parcel_type_field=PARCEL_TYPE_FIELD, parcel_type=PARCEL_TYPE_HORIZONTAL_PROPERTY_PARENT) elif record[PARCEL_TYPE_FIELD] == PARCEL_TYPE_CONDOMINIUM_PARENT: mgs_error = QCoreApplication.translate("LogicChecksConfigStrings", "When the {parcel_type_field} of {table} is '{parcel_type}' you should have 1 plot and 0 building unit but you have {plot_count} plot(s) and {building_unit_count} building unit(s)").format(plot_count=plot_count, building_unit_count=building_unit_count, table=PARCEL_TABLE, parcel_type_field=PARCEL_TYPE_FIELD, parcel_type=PARCEL_TYPE_CONDOMINIUM_PARENT) elif record[PARCEL_TYPE_FIELD] == PARCEL_TYPE_CEMETERY_PARENT: mgs_error = QCoreApplication.translate("LogicChecksConfigStrings", "When the {parcel_type_field} of {table} is '{parcel_type}' you should have 1 plot and 0 building unit but you have {plot_count} plot(s) and {building_unit_count} building unit(s)").format(plot_count=plot_count, building_unit_count=building_unit_count, table=PARCEL_TABLE, parcel_type_field=PARCEL_TYPE_FIELD, parcel_type=PARCEL_TYPE_CEMETERY_PARENT) elif record[PARCEL_TYPE_FIELD] == PARCEL_TYPE_PUBLIC_USE: mgs_error = QCoreApplication.translate("LogicChecksConfigStrings", "When the {parcel_type_field} of {table} is '{parcel_type}' you should have 1 plot and 0 building unit but you have {plot_count} plot(s) and {building_unit_count} building unit(s)").format(plot_count=plot_count, building_unit_count=building_unit_count, table=PARCEL_TABLE, parcel_type_field=PARCEL_TYPE_FIELD, parcel_type=PARCEL_TYPE_PUBLIC_USE) elif record[PARCEL_TYPE_FIELD] == PARCEL_TYPE_CONDOMINIUM_PARCEL_UNIT: mgs_error = QCoreApplication.translate("LogicChecksConfigStrings", "When the {parcel_type_field} of {table} is '{parcel_type}' you should have 1 plot and 0 building unit but you have {plot_count} plot(s) and {building_unit_count} building unit(s)").format(plot_count=plot_count, building_unit_count=building_unit_count, table=PARCEL_TABLE, parcel_type_field=PARCEL_TYPE_FIELD, parcel_type=PARCEL_TYPE_CONDOMINIUM_PARCEL_UNIT) elif record[PARCEL_TYPE_FIELD] == PARCEL_TYPE_ROAD: mgs_error = QCoreApplication.translate("LogicChecksConfigStrings", "When the {parcel_type_field} of {table} is '{parcel_type}' you should have 1 plot and 0 building and 0 building unit but you have {plot_count} plot(s) and {building_count} building(s) and {building_unit_count} building unit(s)").format(plot_count=plot_count, building_count=building_count, building_unit_count=building_unit_count, table=PARCEL_TABLE, parcel_type_field=PARCEL_TYPE_FIELD, parcel_type=PARCEL_TYPE_ROAD) elif record[PARCEL_TYPE_FIELD] == PARCEL_TYPE_CEMETERY_PRIVATE_UNIT: mgs_error = QCoreApplication.translate("LogicChecksConfigStrings", "When the {parcel_type_field} of {table} is '{parcel_type}' you should have 1 plot and 0 building and 0 building unit but you have {plot_count} plot(s) and {building_count} building(s) and {building_unit_count} building unit(s)").format(plot_count=plot_count, building_count=building_count, building_unit_count=building_unit_count, table=PARCEL_TABLE, parcel_type_field=PARCEL_TYPE_FIELD, parcel_type=PARCEL_TYPE_CEMETERY_PRIVATE_UNIT) elif record[PARCEL_TYPE_FIELD] == PARCEL_TYPE_HORIZONTAL_PROPERTY_PARCEL_UNIT: mgs_error = QCoreApplication.translate("LogicChecksConfigStrings", "When the {parcel_type_field} of {table} is '{parcel_type}' you should have 0 plot and 0 building but you have {plot_count} plot(s) and {building_count} building(s)").format(plot_count=plot_count, building_count=building_count, table=PARCEL_TABLE, parcel_type_field=PARCEL_TYPE_FIELD, parcel_type=PARCEL_TYPE_HORIZONTAL_PROPERTY_PARCEL_UNIT) elif record[PARCEL_TYPE_FIELD] == PARCEL_TYPE_MEJORA: mgs_error = QCoreApplication.translate("LogicChecksConfigStrings", "When the {parcel_type_field} of {table} is '{parcel_type}' you should have 0 plot and 1 building and 0 building unit but you have {plot_count} plot(s) and {building_count} building(s) and {building_unit_count} building unit(s)").format(plot_count=plot_count, building_count=building_count, building_unit_count=building_unit_count, table=PARCEL_TABLE, parcel_type_field=PARCEL_TYPE_FIELD, parcel_type=PARCEL_TYPE_MEJORA) new_feature = QgsVectorLayerUtils().createFeature(error_layer, QgsGeometry(), {0: record[ID_FIELD], 1: plot_count, 2: building_count, 3: building_unit_count, 4: mgs_error}) new_features.append(new_feature) error_layer.dataProvider().addFeatures(new_features) return len(new_features), error_layer
def check_parcel_right_relationship(self, db): rule = self.quality_rules_manager.get_quality_rule( EnumQualityRule.Logic.PARCEL_RIGHT_RELATIONSHIP) error_layer = QgsVectorLayer("NoGeometry", rule.error_table_name, "memory") pr = error_layer.dataProvider() pr.addAttributes(rule.error_table_fields) error_layer.updateFields() new_features = list() res, records = self.get_ladm_queries( db.engine).get_parcels_with_no_right(db) if res: for record in records: new_feature = QgsVectorLayerUtils().createFeature( error_layer, QgsGeometry(), { 0: record[db.names.T_ILI_TID_F], 1: self.quality_rules_manager.get_error_message( QUALITY_RULE_ERROR_CODE_E400102), 2: QUALITY_RULE_ERROR_CODE_E400102 }) new_features.append(new_feature) res, records = self.get_ladm_queries( db.engine).get_parcels_with_repeated_domain_right(db) if res: for record in records: new_feature = QgsVectorLayerUtils().createFeature( error_layer, QgsGeometry(), { 0: record[db.names.T_ILI_TID_F], 1: self.quality_rules_manager.get_error_message( QUALITY_RULE_ERROR_CODE_E400101), 2: QUALITY_RULE_ERROR_CODE_E400101 }) new_features.append(new_feature) error_layer.dataProvider().addFeatures(new_features) return self.return_message(db, rule.error_table_name, error_layer)
def check_dangles_in_boundaries(self, db, layer_dict): rule = self.quality_rules_manager.get_quality_rule( EnumQualityRule.Line.DANGLES_IN_BOUNDARIES) boundary_layer = list(layer_dict[QUALITY_RULE_LAYERS].values() )[0] if layer_dict[QUALITY_RULE_LAYERS] else None if not boundary_layer: return QCoreApplication.translate( "LineQualityRules", "'Boundary' layer was not found!"), Qgis.Critical if boundary_layer.featureCount() == 0: return (QCoreApplication.translate( "LineQualityRules", "There are no boundaries to check for dangles."), Qgis.Warning) else: error_layer = QgsVectorLayer( "Point?crs={}".format(boundary_layer.sourceCrs().authid()), rule.error_table_name, "memory") pr = error_layer.dataProvider() pr.addAttributes(rule.error_table_fields) error_layer.updateFields() end_points, dangle_ids = self.geometry.get_dangle_ids( boundary_layer) new_features = [] for dangle in end_points.getFeatures(dangle_ids): new_feature = QgsVectorLayerUtils().createFeature( end_points, dangle.geometry(), { 0: dangle[db.names.T_ILI_TID_F], 1: self.quality_rules_manager.get_error_message( QUALITY_RULE_ERROR_CODE_E200501), 2: QUALITY_RULE_ERROR_CODE_E200501 }) new_features.append(new_feature) error_layer.dataProvider().addFeatures(new_features) if error_layer.featureCount() > 0: added_layer = self.app.gui.add_error_layer(db, error_layer) return (QCoreApplication.translate( "LineQualityRules", "A memory layer with {} boundary dangles has been added to the map!" ).format(added_layer.featureCount()), Qgis.Critical) else: return (QCoreApplication.translate( "LineQualityRules", "Boundaries have no dangles!"), Qgis.Success)
def check_boundaries_are_not_split(self, db, layer_dict): """ An split boundary is an incomplete boundary because it is connected to a single boundary and therefore, they don't represent a change in boundary (colindancia). """ rule = self.quality_rules_manager.get_quality_rule(EnumQualityRule.Line.BOUNDARIES_ARE_NOT_SPLIT) features = [] boundary_layer = list(layer_dict[QUALITY_RULE_LAYERS].values())[0] if layer_dict[QUALITY_RULE_LAYERS] else None if not boundary_layer: return QCoreApplication.translate("LineQualityRules", "'Boundary' layer not found!"), Qgis.Critical if boundary_layer.featureCount() == 0: return (QCoreApplication.translate("LineQualityRules", "There are no boundaries to check 'boundaries should not be split'!"), Qgis.Warning) else: wrong_boundaries = self.geometry.get_boundaries_connected_to_single_boundary(db.names, boundary_layer) if wrong_boundaries is None: return (QCoreApplication.translate("LineQualityRules", "There are no wrong boundaries!"), Qgis.Success) else: error_layer = QgsVectorLayer("LineString?crs={}".format(boundary_layer.sourceCrs().authid()), rule.error_table_name, "memory") pr = error_layer.dataProvider() pr.addAttributes(rule.error_table_fields) error_layer.updateFields() # Get geometries from LADM-COL original layer. If not HAS_ADJUSTED_LAYERS, it's OK to get # them from wrong_boundaries list, as it would have been created from original geoms if layer_dict[HAS_ADJUSTED_LAYERS]: ladm_col_boundary_layer = list(layer_dict[QUALITY_RULE_LADM_COL_LAYERS].values())[0] if layer_dict[QUALITY_RULE_LADM_COL_LAYERS] else boundary_layer wrong_tids = ",".join([str(f[db.names.T_ID_F]) for f in wrong_boundaries]) # Use t_id, which is indexed geoms = {f[db.names.T_ILI_TID_F]:f.geometry() for f in ladm_col_boundary_layer.getFeatures("{} IN ({})".format(db.names.T_ID_F, wrong_tids))} else: geoms = {f[db.names.T_ILI_TID_F]: f.geometry() for f in wrong_boundaries} for feature in wrong_boundaries: new_feature = QgsVectorLayerUtils().createFeature(error_layer, geoms[feature[db.names.T_ILI_TID_F]], {0: feature[db.names.T_ILI_TID_F], 1: self.quality_rules_manager.get_error_message(QUALITY_RULE_ERROR_CODE_E200201), 2: QUALITY_RULE_ERROR_CODE_E200201}) features.append(new_feature) error_layer.dataProvider().addFeatures(features) if error_layer.featureCount() > 0: added_layer = self.app.gui.add_error_layer(db, error_layer) return (QCoreApplication.translate("LineQualityRules", "A memory layer with {} wrong boundaries has been added to the map!").format(added_layer.featureCount()), Qgis.Critical) else: return (QCoreApplication.translate("LineQualityRules", "There are no wrong boundaries."), Qgis.Success)
def get_feature_with_buffer_right_of_way(self, layer): params = {'INPUT': layer, 'DISTANCE': self.width_line_edit.value(), 'SEGMENTS': 5, 'END_CAP_STYLE': 1, # Flat 'JOIN_STYLE': 2, 'MITER_LIMIT': 2, 'DISSOLVE': False, 'OUTPUT': 'memory:'} buffered_right_of_way_layer = processing.run("native:buffer", params)['OUTPUT'] buffer_geometry = buffered_right_of_way_layer.getFeature(1).geometry() feature = QgsVectorLayerUtils().createFeature(self._layers[self.EDITING_LAYER_NAME], buffer_geometry) return feature
def save_group_party(self, db, params): """ Save group party data into associated tables: LA_GROUP_PARTY_TABLE, MEMBERS_TABLE and FRACTION_TABLE. params: List of dicts, where each dict is an independent group party: { LA_GROUP_PARTY_NAME_FIELD: '', LA_GROUP_PARTY_GPTYPE_FIELD: '', 'porcentajes': { 't_id_miembro': [20, 100], # numerador/denominador 't_id_miembro2': [40, 100] } } """ # Disconnect from previous runs try: self._la_group_party_table.committedFeaturesAdded.disconnect() except TypeError as e: pass try: self._members_table.committedFeaturesAdded.disconnect() except TypeError as e: pass for group in params: # Create connections to react when a group party is stored to the DB self._la_group_party_table.committedFeaturesAdded.connect( partial(self.finish_group_party_saving, group['porcentajes'])) # First save the group party new_feature = QgsVectorLayerUtils().createFeature( self._la_group_party_table) new_feature.setAttribute(LA_GROUP_PARTY_GPTYPE_FIELD, group[LA_GROUP_PARTY_GPTYPE_FIELD]) new_feature.setAttribute(LA_GROUP_PARTY_NAME_FIELD, group[LA_GROUP_PARTY_NAME_FIELD]) new_feature.setAttribute(LA_GROUP_PARTY_TYPE_FIELD, LA_GROUP_PARTY_TYPE_VALUE) # TODO: Gui should allow users to ented namespace, local_id and date values #new_feature.setAttribute("p_espacio_de_nombres", LA_GROUP_PARTY_TABLE) #new_feature.setAttribute("p_local_id", '0') #new_feature.setAttribute("comienzo_vida_util_version", 'now()') self.log.logMessage("Saving Group Party: {}".format(group), PLUGIN_NAME, Qgis.Info) with edit(self._la_group_party_table): self._la_group_party_table.addFeature(new_feature)
def finish_building_unit_valuation(self, building_unit_ids, layerId, features): if len(features) != 1: self.log.logMessage( "We should have got only one building unit... We cannot do anything with {} building units" .format(len(features)), PLUGIN_NAME, Qgis.Warning) else: fid = features[0].id() if not self._building_unit_valuation.getFeature(fid).isValid(): self.log.logMessage( "Feature not found in layer building unit...", PLUGIN_NAME, Qgis.Warning) else: building_unit_valuation_id = self._building_unit_valuation.getFeature( fid)[ID_FIELD] # Fill avaluounidadconstruccion table new_features = [] for building_unit_id in building_unit_ids: new_feature = QgsVectorLayerUtils().createFeature( self._avaluounidadconstruccion_table) new_feature.setAttribute( AVALUOUNIDADCONSTRUCCION_TABLE_BUILDING_UNIT_FIELD, building_unit_id) new_feature.setAttribute( AVALUOUNIDADCONSTRUCCION_TABLE_BUILDING_UNIT_VALUATION_FIELD, building_unit_valuation_id) self.log.logMessage( "Saving Building unit-Building unit valuation: {}-{}". format(building_unit_id, building_unit_valuation_id), PLUGIN_NAME, Qgis.Info) new_features.append(new_feature) self._avaluounidadconstruccion_table.dataProvider( ).addFeatures(new_features) if building_unit_ids: self.iface.messageBar().pushMessage( "Asistente LADM_COL", QCoreApplication.translate( "CreateBuildingUnitValuationWizard", "The new building unit valuation (t_id={}) was successfully created and associated with its corresponding building unit (t_id={})!" ).format(building_unit_valuation_id, building_unit_ids[0]), Qgis.Info) self._building_unit_valuation.committedFeaturesAdded.disconnect() self.log.logMessage( "Building unit valuation's committedFeaturesAdded SIGNAL disconnected", PLUGIN_NAME, Qgis.Info)
def get_feature_with_buffer_right_of_way(self, tmp_layer, layer): params = {'INPUT': tmp_layer, 'DISTANCE': self.width_line, 'SEGMENTS': 5, 'END_CAP_STYLE': 1, # Flat 'JOIN_STYLE': 2, 'MITER_LIMIT': 2, 'DISSOLVE': False, 'OUTPUT': 'memory:'} buffered_right_of_way_layer = processing.run("native:buffer", params)['OUTPUT'] buffer_geometry = buffered_right_of_way_layer.getFeature(1).geometry() feature = QgsVectorLayerUtils().createFeature(layer, buffer_geometry) tmp_layer.commitChanges() return feature
def save_group_party(self, db, params): """ Save group party data into associated tables: self.names.OP_GROUP_PARTY_T, self.names.MEMBERS_T and self.names.FRACTION_S. params: List of dicts, where each dict is an independent group party: { self.names.COL_PARTY_T_NAME_F: '', self.names.COL_GROUP_PARTY_T_TYPE_F: '', 'porcentajes': { 't_id_miembro': [20, 100], # numerador/denominador 't_id_miembro2': [40, 100] } } """ # Disconnect from previous runs self.disconnect_signals() for group in params: # Create connections to react when a group party is stored to the DB self._layers[self.names.OP_GROUP_PARTY_T][ LAYER].committedFeaturesAdded.connect( partial(self.finish_group_party_saving, group['porcentajes'])) # First save the group party new_feature = QgsVectorLayerUtils().createFeature( self._layers[self.names.OP_GROUP_PARTY_T][LAYER]) new_feature.setAttribute( self.names.COL_GROUP_PARTY_T_TYPE_F, group[self.names.COL_GROUP_PARTY_T_TYPE_F]) new_feature.setAttribute(self.names.COL_PARTY_T_NAME_F, group[self.names.COL_PARTY_T_NAME_F]) # TODO: Remove when local id and working space are defined new_feature.setAttribute(self.names.OID_T_LOCAL_ID_F, 1) new_feature.setAttribute(self.names.OID_T_NAMESPACE_F, self.names.OP_GROUP_PARTY_T) # TODO: Gui should allow users to ented namespace, local_id and date values #new_feature.setAttribute("p_espacio_de_nombres", self.names.OP_GROUP_PARTY_T) #new_feature.setAttribute("p_local_id", '0') #new_feature.setAttribute("comienzo_vida_util_version", 'now()') self.logger.info(__name__, "Saving Group Party: {}".format(group)) with edit(self._layers[self.names.OP_GROUP_PARTY_T][LAYER]): self._layers[self.names.OP_GROUP_PARTY_T][LAYER].addFeature( new_feature)
def processAlgorithm(self, parameters, context, feedback): source = self.parameterAsSource(parameters, self.INPUT, context) target = self.parameterAsVectorLayer(parameters, self.OUTPUT, context) target_provider = target.dataProvider() target_provider.clearErrors() if target.isEditable(): feedback.reportError("\nWARNING: You need to close the edit session on layer '{}' before running this algorithm.".format( target.name() )) return {self.OUTPUT: None} features = QgsVectorLayerUtils().makeFeaturesCompatible(source.getFeatures(), target) eval_context = QgsExpressionContext(QgsExpressionContextUtils.globalProjectLayerScopes(target)) # Make sure automatic values are calculated if automatic_values_in_batch_mode # is enabled and that they are not calculated otherwise automatic_values_in_batch_mode = QSettings().value('Asistente-LADM-COL/automatic_values/automatic_values_in_batch_mode', DEFAULT_AUTOMATIC_VALUES_IN_BATCH_MODE, bool) list_automatic_fields = list() if automatic_values_in_batch_mode: # Get indexes that have an automatic value configured, except primary keys, # since we deal with PK's values differently (namely, directly with the provider) list_automatic_fields = [idx for idx in target.attributeList() if target.defaultValueDefinition(idx).isValid() and idx not in target_provider.pkAttributeIndexes()] # Update attribute values before saving for feature in features: for idx in target_provider.pkAttributeIndexes(): # Get the PK from the provider itself feature.setAttribute(idx, target_provider.defaultValue(idx)) for idx in list_automatic_fields: feature.setAttribute(idx, target.defaultValue(idx, feature, eval_context)) if self.save_features(target, features, 'provider', feedback): feedback.pushInfo("\nSUCCESS: {} out of {} features from input layer were successfully copied into '{}'!".format( len(features), source.featureCount(), target.name() )) else: # Messages are handled by save_features method return {self.OUTPUT: None} return {self.OUTPUT: target}
def finish_group_party_saving(self, members, layer_id, features): try: self._layers[self.names.LC_GROUP_PARTY_T].committedFeaturesAdded.disconnect() except TypeError as e: pass message = QCoreApplication.translate("WizardTranslations", "'{}' tool has been closed because an error occurred while trying to save the data.").format(self.WIZARD_TOOL_NAME) if len(features) != 1: message = QCoreApplication.translate("WizardTranslations", "'{}' tool has been closed. We should have got only one group party... We cannot do anything with {} group parties").format(self.WIZARD_TOOL_NAME, len(features)) self.logger.warning(__name__, "We should have got only one group party... We cannot do anything with {} group parties".format(len(features))) else: fid = features[0].id() if not self._layers[self.names.LC_GROUP_PARTY_T].getFeature(fid).isValid(): self.logger.warning(__name__, "Feature not found in table Group Party...") else: group_party_id = self._layers[self.names.LC_GROUP_PARTY_T].getFeature(fid)[self.names.T_ID_F] # Now save members party_ids = list() for party_id, fraction in members.items(): # Create connections to react when a group party is stored to the DB self._layers[self.names.MEMBERS_T].committedFeaturesAdded.connect(partial(self.finish_member_saving, fraction)) new_feature = QgsVectorLayerUtils().createFeature(self._layers[self.names.MEMBERS_T]) new_feature.setAttribute(self.names.MEMBERS_T_GROUP_PARTY_F, group_party_id) new_feature.setAttribute(self.names.MEMBERS_T_PARTY_F, party_id) self.logger.info(__name__, "Saving group party's member ({}: {}).".format(group_party_id, party_id)) with edit(self._layers[self.names.MEMBERS_T]): self._layers[self.names.MEMBERS_T].addFeature(new_feature) party_ids.append(party_id) if len(party_ids): message = QCoreApplication.translate("WizardTranslations", "The new group party (t_id={}) was successfully created and associated with its corresponding party(ies) (t_id={})!").format(group_party_id, ", ".join([str(b) for b in party_ids])) else: message = QCoreApplication.translate("WizardTranslations", "The new group party (t_id={}) was successfully created but this one wasn't associated with a party(ies)").format(group_party_id) self.close_wizard(message)
def parcel_type_and_22_position_of_parcel_number_validation(self, db, rule, error_layer): query = db.logic_validation_queries[rule]['query'] table_name = db.logic_validation_queries[rule]['table_name'] table = db.logic_validation_queries[rule]['table'] if error_layer is None: error_layer = QgsVectorLayer("NoGeometry?crs=EPSG:{}".format(DEFAULT_EPSG), table_name, "memory") pr = error_layer.dataProvider() pr.addAttributes([QgsField(QCoreApplication.translate("QGISUtils", "{table}_id").format(table=table), QVariant.Int), QgsField(QCoreApplication.translate("QGISUtils", "error_type"), QVariant.String)]) error_layer.updateFields() records = db.execute_sql_query(query) new_features = list() for record in records: mgs_error = None if record[PARCEL_TYPE_FIELD] == PARCEL_TYPE_NO_HORIZONTAL_PROPERTY: mgs_error = QCoreApplication.translate("LogicChecksConfigStrings", "When the {parcel_type_field} of {table} is {parcel_type} the 22nd position of the property code must be 0").format(table=PARCEL_TABLE, parcel_type_field=PARCEL_TYPE_FIELD, parcel_type=PARCEL_TYPE_NO_HORIZONTAL_PROPERTY) elif record[PARCEL_TYPE_FIELD] in (PARCEL_TYPE_HORIZONTAL_PROPERTY_PARENT, PARCEL_TYPE_HORIZONTAL_PROPERTY_PARCEL_UNIT): mgs_error = QCoreApplication.translate("LogicChecksConfigStrings", "When the {parcel_type_field} of {table} is {parcel_type} the 22nd position of the property code must be 9").format(table=PARCEL_TABLE, parcel_type_field=PARCEL_TYPE_FIELD, parcel_type=PARCEL_TYPE_HORIZONTAL_PROPERTY_PARENT + " or " + PARCEL_TYPE_HORIZONTAL_PROPERTY_PARCEL_UNIT) elif record[PARCEL_TYPE_FIELD] in (PARCEL_TYPE_CONDOMINIUM_PARENT, PARCEL_TYPE_CONDOMINIUM_PARCEL_UNIT): mgs_error = QCoreApplication.translate("LogicChecksConfigStrings", "When the {parcel_type_field} of {table} is {parcel_type} the 22nd position of the property code must be 8").format(table=PARCEL_TABLE, parcel_type_field=PARCEL_TYPE_FIELD, parcel_type=PARCEL_TYPE_CONDOMINIUM_PARENT + " or " + PARCEL_TYPE_CONDOMINIUM_PARCEL_UNIT) elif record[PARCEL_TYPE_FIELD] in (PARCEL_TYPE_CEMETERY_PARENT, PARCEL_TYPE_CEMETERY_PRIVATE_UNIT): mgs_error = QCoreApplication.translate("LogicChecksConfigStrings", "When the {parcel_type_field} of {table} is {parcel_type} the 22nd position of the property code must be 7").format(table=PARCEL_TABLE, parcel_type_field=PARCEL_TYPE_FIELD, parcel_type=PARCEL_TYPE_CEMETERY_PARENT + " or " + PARCEL_TYPE_CEMETERY_PRIVATE_UNIT) elif record[PARCEL_TYPE_FIELD] == PARCEL_TYPE_MEJORA: mgs_error = QCoreApplication.translate("LogicChecksConfigStrings", "When the {parcel_type_field} of {table} is {parcel_type} the 22nd position of the property code must be 5").format(table=PARCEL_TABLE, parcel_type_field=PARCEL_TYPE_FIELD, parcel_type=PARCEL_TYPE_MEJORA) elif record[PARCEL_TYPE_FIELD] == PARCEL_TYPE_ROAD: mgs_error = QCoreApplication.translate("LogicChecksConfigStrings", "When the {parcel_type_field} of {table} is {parcel_type} the 22nd position of the property code must be 4").format(table=PARCEL_TABLE, parcel_type_field=PARCEL_TYPE_FIELD, parcel_type=PARCEL_TYPE_ROAD) elif record[PARCEL_TYPE_FIELD] == PARCEL_TYPE_PUBLIC_USE: mgs_error = QCoreApplication.translate("LogicChecksConfigStrings", "When the {parcel_type_field} of {table} is {parcel_type} the 22nd position of the property code must be 3").format(table=PARCEL_TABLE, parcel_type_field=PARCEL_TYPE_FIELD, parcel_type=PARCEL_TYPE_PUBLIC_USE) new_feature = QgsVectorLayerUtils().createFeature(error_layer, QgsGeometry(), {0: record[ID_FIELD], 1: mgs_error}) new_features.append(new_feature) error_layer.dataProvider().addFeatures(new_features) return len(new_features), error_layer
def create_plots_from_boundaries(self): selected_boundaries = self._layers[BOUNDARY_TABLE][ LAYER].selectedFeatures() boundary_geometries = [f.geometry() for f in selected_boundaries] collection = QgsGeometry().polygonize(boundary_geometries) features = list() for polygon in collection.asGeometryCollection(): feature = QgsVectorLayerUtils().createFeature( self._layers[self.EDITING_LAYER_NAME][LAYER], polygon) features.append(feature) if features: if not self._layers[self.EDITING_LAYER_NAME][LAYER].isEditable(): self._layers[self.EDITING_LAYER_NAME][LAYER].startEditing() self._layers[self.EDITING_LAYER_NAME][LAYER].addFeatures(features) self.iface.mapCanvas().refresh() message = QCoreApplication.translate( "QGISUtils", "{} new plot(s) has(have) been created! To finish the creation of the plots, open its attribute table and fill in the mandatory fields." ).format(len(features)) button_text = QCoreApplication.translate( "QGISUtils", "Open table of attributes") level = Qgis.Info layer = self._layers[self.EDITING_LAYER_NAME][LAYER] filter = '"{}" is Null and "{}" is Null'.format( PLOT_REGISTRY_AREA_FIELD, PLOT_CALCULATED_AREA_FIELD) self.qgis_utils.message_with_open_table_attributes_button_emitted.emit( message, button_text, level, layer, filter) self.close_wizard(show_message=False) else: message = QCoreApplication.translate( "QGISUtils", "No plot could be created. Make sure selected boundaries are closed!" ) self.close_wizard(message)