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
Beispiel #2
0
    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)
Beispiel #3
0
 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 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)
Beispiel #5
0
    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 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 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)
Beispiel #8
0
    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 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)
Beispiel #10
0
    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)
Beispiel #11
0
    def save_group_party(self, db, params):
        """
        Save group party data into associated tables: self.names.LC_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.LC_GROUP_PARTY_T].committedFeaturesAdded.connect(partial(self.finish_group_party_saving, group['porcentajes']))

            # First save the group party
            new_feature = QgsVectorLayerUtils().createFeature(self._layers[self.names.LC_GROUP_PARTY_T])
            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 namespace are defined
            #new_feature.setAttribute(self.names.OID_T_LOCAL_ID_F, 1)
            #new_feature.setAttribute(self.names.OID_T_NAMESPACE_F, self.names.LC_GROUP_PARTY_T)

            # TODO: Gui should allow users to enter namespace, local_id and date values
            #new_feature.setAttribute("p_espacio_de_nombres", self.names.LC_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.LC_GROUP_PARTY_T]):
                self._layers[self.names.LC_GROUP_PARTY_T].addFeature(new_feature)
Beispiel #12
0
    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, "We should have got only one building unit... We cannot do anything with {} building units".format(len(features)))
            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:

            building_unit_ids = [f[ID_FIELD] for f in self._layers[BUILDING_UNIT_TABLE][LAYER].selectedFeatures()]
            fid = features[0].id()

            if not self._layers[self.EDITING_LAYER_NAME][LAYER].getFeature(fid).isValid():
                self.log.logMessage("Feature not found in layer building unit...", PLUGIN_NAME, Qgis.Warning)
            else:
                building_unit_valuation_id = self._layers[self.EDITING_LAYER_NAME][LAYER].getFeature(fid)[ID_FIELD]

                # Fill avaluounidadconstruccion table
                new_features = []
                for building_unit_id in building_unit_ids:
                    new_feature = QgsVectorLayerUtils().createFeature(self._layers[AVALUOUNIDADCONSTRUCCION_TABLE][LAYER])
                    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._layers[AVALUOUNIDADCONSTRUCCION_TABLE][LAYER].dataProvider().addFeatures(new_features)

                if building_unit_ids:
                    message = QCoreApplication.translate(self.WIZARD_NAME,
                                                   "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])

        self._layers[self.EDITING_LAYER_NAME][LAYER].committedFeaturesAdded.disconnect(self.finish_feature_creation)
        self.log.logMessage("Building unit valuation's committedFeaturesAdded SIGNAL disconnected", PLUGIN_NAME, Qgis.Info)
        self.close_wizard(message)
    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)
Beispiel #14
0
    def build_boundary(self, db):
        QgsProject.instance().setAutoTransaction(False)
        layer = self.qgis_utils.get_layer_from_layer_tree(
            db, db.names.OP_BOUNDARY_T)
        use_selection = True

        if layer is None:
            self.logger.message_with_button_load_layer_emitted.emit(
                QCoreApplication.translate(
                    "ToolBar", "First load the layer {} into QGIS!").format(
                        db.names.OP_BOUNDARY_T),
                QCoreApplication.translate("ToolBar",
                                           "Load layer {} now").format(
                                               db.names.OP_BOUNDARY_T),
                db.names.OP_BOUNDARY_T, Qgis.Warning)
            return
        else:
            if layer.selectedFeatureCount() == 0:

                reply = QMessageBox.question(
                    None, QCoreApplication.translate("ToolBar", "Continue?"),
                    QCoreApplication.translate(
                        "ToolBar",
                        "There are no selected boundaries. Do you want to use all the {} boundaries in the database?"
                    ).format(layer.featureCount()),
                    QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Cancel)
                if reply == QMessageBox.Yes:
                    use_selection = False
                elif reply == QMessageBox.Cancel:
                    self.logger.warning_msg(
                        __name__,
                        QCoreApplication.translate(
                            "ToolBar", "First select at least one boundary!"))
                    return

        if use_selection:
            new_boundary_geoms, boundaries_to_del_ids = self.geometry.fix_selected_boundaries(
                db.names, layer, db.names.T_ID_F)
            num_boundaries = layer.selectedFeatureCount()
        else:
            new_boundary_geoms, boundaries_to_del_ids = self.geometry.fix_boundaries(
                layer, db.names.T_ID_F)
            num_boundaries = layer.featureCount()

        if len(new_boundary_geoms) > 0:
            layer.startEditing(
            )  # Safe, even if layer is already on editing state

            # the boundaries that are to be replaced are removed
            layer.deleteFeatures(boundaries_to_del_ids)

            # Create features based on segment geometries
            new_fix_boundary_features = list()
            for boundary_geom in new_boundary_geoms:
                feature = QgsVectorLayerUtils().createFeature(
                    layer, boundary_geom)

                # TODO: Remove when local id and working space are defined
                feature.setAttribute(db.names.OID_T_LOCAL_ID_F, 1)
                feature.setAttribute(db.names.OID_T_NAMESPACE_F,
                                     db.names.OP_BOUNDARY_T)

                new_fix_boundary_features.append(feature)

            layer.addFeatures(new_fix_boundary_features)
            self.logger.info_msg(
                __name__,
                QCoreApplication.translate(
                    "ToolBar",
                    "{} feature(s) was(were) analyzed generating {} boundary(ies)!"
                ).format(num_boundaries, len(new_fix_boundary_features)))
            self.iface.mapCanvas().refresh()
        else:
            self.logger.info_msg(
                __name__,
                QCoreApplication.translate(
                    "ToolBar", "There are no boundaries to build."))
Beispiel #15
0
    def fill_topology_tables_morebfs_less(self, db, use_selection=True):
        layers = {
            db.names.OP_PLOT_T: {
                'name': db.names.OP_PLOT_T,
                'geometry': QgsWkbTypes.PolygonGeometry,
                LAYER: None
            },
            db.names.MORE_BFS_T: {
                'name': db.names.MORE_BFS_T,
                'geometry': None,
                LAYER: None
            },
            db.names.LESS_BFS_T: {
                'name': db.names.LESS_BFS_T,
                'geometry': None,
                LAYER: None
            },
            db.names.OP_BOUNDARY_T: {
                'name': db.names.OP_BOUNDARY_T,
                'geometry': None,
                LAYER: None
            }
        }

        self.qgis_utils.get_layers(db, layers, load=True)
        if not layers:
            return None

        if use_selection:
            if layers[db.names.OP_PLOT_T][LAYER].selectedFeatureCount() == 0:
                if self.qgis_utils.get_layer_from_layer_tree(
                        db,
                        db.names.OP_PLOT_T,
                        geometry_type=QgsWkbTypes.PolygonGeometry) is None:
                    self.logger.message_with_button_load_layer_emitted.emit(
                        QCoreApplication.translate(
                            "ToolBar",
                            "First load the layer {} into QGIS and select at least one plot!"
                        ).format(db.names.OP_PLOT_T),
                        QCoreApplication.translate("ToolBar",
                                                   "Load layer {} now").format(
                                                       db.names.OP_PLOT_T),
                        db.names.OP_PLOT_T, Qgis.Warning)
                else:
                    reply = QMessageBox.question(
                        None,
                        QCoreApplication.translate("ToolBar", "Continue?"),
                        QCoreApplication.translate(
                            "ToolBar",
                            "There are no selected plots. Do you want to fill the '{more}' and '{less}' tables for all the {all} plots in the database?"
                        ).format(more=db.names.MORE_BFS_T,
                                 less=db.names.LESS_BFS_T,
                                 all=layers[db.names.OP_PLOT_T]
                                 [LAYER].featureCount()),
                        QMessageBox.Yes | QMessageBox.Cancel,
                        QMessageBox.Cancel)
                    if reply == QMessageBox.Yes:
                        use_selection = False
                    elif reply == QMessageBox.Cancel:
                        self.logger.warning_msg(
                            __name__,
                            QCoreApplication.translate(
                                "ToolBar", "First select at least one plot!"))
                        return
            else:
                reply = QMessageBox.question(
                    None, QCoreApplication.translate("ToolBar", "Continue?"),
                    QCoreApplication.translate(
                        "ToolBar",
                        "There are {selected} plots selected. Do you want to fill the '{more}' and '{less}' tables just for the selected plots?\n\nIf you say 'No', the '{more}' and '{less}' tables will be filled for all plots in the database."
                    ).format(selected=layers[db.names.OP_PLOT_T]
                             [LAYER].selectedFeatureCount(),
                             more=db.names.MORE_BFS_T,
                             less=db.names.LESS_BFS_T),
                    QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
                    QMessageBox.Cancel)
                if reply == QMessageBox.Yes:
                    use_selection = True
                elif reply == QMessageBox.No:
                    use_selection = False
                elif reply == QMessageBox.Cancel:
                    return

        more_bfs_features = layers[db.names.MORE_BFS_T][LAYER].getFeatures()
        less_features = layers[db.names.LESS_BFS_T][LAYER].getFeatures()

        # Get unique pairs id_boundary-id_plot in both tables
        existing_more_pairs = [
            (more_bfs_feature[db.names.MORE_BFS_T_OP_PLOT_F],
             more_bfs_feature[db.names.MORE_BFS_T_OP_BOUNDARY_F])
            for more_bfs_feature in more_bfs_features
        ]
        existing_more_pairs = set(existing_more_pairs)
        # Todo: Update when ili2db issue is solved.
        # Todo: When an abstract class only implements a concrete class, the name of the attribute is different if two or more classes are implemented.
        existing_less_pairs = [
            (less_feature[db.names.LESS_BFS_T_OP_PLOT_F],
             less_feature[db.names.LESS_BFS_T_OP_BOUNDARY_F])
            for less_feature in less_features
        ]
        existing_less_pairs = set(existing_less_pairs)

        id_more_pairs, id_less_pairs = self.geometry.get_pair_boundary_plot(
            layers[db.names.OP_BOUNDARY_T][LAYER],
            layers[db.names.OP_PLOT_T][LAYER],
            db.names.T_ID_F,
            use_selection=use_selection)
        if id_less_pairs:
            layers[db.names.LESS_BFS_T][LAYER].startEditing()
            features = list()
            for id_pair in id_less_pairs:
                if not id_pair in existing_less_pairs:  # Avoid duplicated pairs in the DB
                    # Create feature
                    feature = QgsVectorLayerUtils().createFeature(
                        layers[db.names.LESS_BFS_T][LAYER])
                    feature.setAttribute(db.names.LESS_BFS_T_OP_PLOT_F,
                                         id_pair[0])
                    # Todo: Update LESS_BFS_T_OP_BOUNDARY_F by LESS_BFS_T_OP_BOUNDARY_F.
                    # Todo: When an abstract class only implements a concrete class, the name of the attribute is different if two or more classes are implemented.
                    feature.setAttribute(db.names.LESS_BFS_T_OP_BOUNDARY_F,
                                         id_pair[1])
                    features.append(feature)
            layers[db.names.LESS_BFS_T][LAYER].addFeatures(features)
            layers[db.names.LESS_BFS_T][LAYER].commitChanges()
            self.logger.info_msg(
                __name__,
                QCoreApplication.translate(
                    "ToolBar",
                    "{} out of {} records were saved into '{}'! {} out of {} records already existed in the database."
                ).format(len(features), len(id_less_pairs),
                         db.names.LESS_BFS_T,
                         len(id_less_pairs) - len(features),
                         len(id_less_pairs)))
        else:
            self.logger.info_msg(
                __name__,
                QCoreApplication.translate(
                    "ToolBar",
                    "No pairs id_boundary-id_plot found for '{}' table.").
                format(db.names.LESS_BFS_T))

        if id_more_pairs:
            layers[db.names.MORE_BFS_T][LAYER].startEditing()
            features = list()
            for id_pair in id_more_pairs:
                if not id_pair in existing_more_pairs:  # Avoid duplicated pairs in the DB
                    # Create feature
                    feature = QgsVectorLayerUtils().createFeature(
                        layers[db.names.MORE_BFS_T][LAYER])
                    feature.setAttribute(db.names.MORE_BFS_T_OP_PLOT_F,
                                         id_pair[0])
                    feature.setAttribute(db.names.MORE_BFS_T_OP_BOUNDARY_F,
                                         id_pair[1])
                    features.append(feature)
            layers[db.names.MORE_BFS_T][LAYER].addFeatures(features)
            layers[db.names.MORE_BFS_T][LAYER].commitChanges()
            self.logger.info_msg(
                __name__,
                QCoreApplication.translate(
                    "ToolBar",
                    "{} out of {} records were saved into '{}'! {} out of {} records already existed in the database."
                ).format(len(features), len(id_more_pairs),
                         db.names.MORE_BFS_T,
                         len(id_more_pairs) - len(features),
                         len(id_more_pairs)))
        else:
            self.logger.info_msg(
                __name__,
                QCoreApplication.translate(
                    "ToolBar",
                    "No pairs id_boundary-id_plot found for '{}' table.").
                format(db.names.MORE_BFS_T))
Beispiel #16
0
    def fill_topology_table_pointbfs(self, db, use_selection=True):
        layers = {
            db.names.OP_BOUNDARY_T: {
                'name': db.names.OP_BOUNDARY_T,
                'geometry': None,
                LAYER: None
            },
            db.names.POINT_BFS_T: {
                'name': db.names.POINT_BFS_T,
                'geometry': None,
                LAYER: None
            },
            db.names.OP_BOUNDARY_POINT_T: {
                'name': db.names.OP_BOUNDARY_POINT_T,
                'geometry': None,
                LAYER: None
            }
        }

        self.qgis_utils.get_layers(db, layers, load=True)
        if not layers:
            return None

        if use_selection:
            if layers[
                    db.names.OP_BOUNDARY_T][LAYER].selectedFeatureCount() == 0:
                if self.qgis_utils.get_layer_from_layer_tree(
                        db, db.names.OP_BOUNDARY_T) is None:
                    self.logger.message_with_button_load_layer_emitted.emit(
                        QCoreApplication.translate(
                            "ToolBar",
                            "First load the layer {} into QGIS and select at least one boundary!"
                        ).format(db.names.OP_BOUNDARY_T),
                        QCoreApplication.translate("ToolBar",
                                                   "Load layer {} now").format(
                                                       db.names.OP_BOUNDARY_T),
                        db.names.OP_BOUNDARY_T, Qgis.Warning)
                else:
                    reply = QMessageBox.question(
                        None,
                        QCoreApplication.translate("ToolBar", "Continue?"),
                        QCoreApplication.translate(
                            "ToolBar",
                            "There are no selected boundaries. Do you want to fill the '{}' table for all the {} boundaries in the database?"
                        ).format(
                            db.names.POINT_BFS_T, layers[
                                db.names.OP_BOUNDARY_T][LAYER].featureCount()),
                        QMessageBox.Yes | QMessageBox.Cancel,
                        QMessageBox.Cancel)
                    if reply == QMessageBox.Yes:
                        use_selection = False
                    elif reply == QMessageBox.Cancel:
                        self.logger.warning_msg(
                            __name__,
                            QCoreApplication.translate(
                                "ToolBar",
                                "First select at least one boundary!"))
                        return
            else:
                reply = QMessageBox.question(
                    None, QCoreApplication.translate("ToolBar", "Continue?"),
                    QCoreApplication.translate(
                        "ToolBar",
                        "There are {selected} boundaries selected. Do you want to fill the '{table}' table just for the selected boundaries?\n\nIf you say 'No', the '{table}' table will be filled for all boundaries in the database."
                    ).format(selected=layers[db.names.OP_BOUNDARY_T]
                             [LAYER].selectedFeatureCount(),
                             table=db.names.POINT_BFS_T),
                    QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
                    QMessageBox.Cancel)
                if reply == QMessageBox.Yes:
                    use_selection = True
                elif reply == QMessageBox.No:
                    use_selection = False
                elif reply == QMessageBox.Cancel:
                    return

        bfs_features = layers[db.names.POINT_BFS_T][LAYER].getFeatures()

        # Get unique pairs id_boundary-id_boundary_point
        existing_pairs = [
            (bfs_feature[db.names.POINT_BFS_T_OP_BOUNDARY_F],
             bfs_feature[db.names.POINT_BFS_T_OP_BOUNDARY_POINT_F])
            for bfs_feature in bfs_features
        ]
        existing_pairs = set(existing_pairs)

        id_pairs = self.geometry.get_pair_boundary_boundary_point(
            layers[db.names.OP_BOUNDARY_T][LAYER],
            layers[db.names.OP_BOUNDARY_POINT_T][LAYER],
            db.names.T_ID_F,
            use_selection=use_selection)

        if id_pairs:
            layers[db.names.POINT_BFS_T][LAYER].startEditing()
            features = list()
            for id_pair in id_pairs:
                if not id_pair in existing_pairs:  # Avoid duplicated pairs in the DB
                    # Create feature
                    feature = QgsVectorLayerUtils().createFeature(
                        layers[db.names.POINT_BFS_T][LAYER])
                    feature.setAttribute(db.names.POINT_BFS_T_OP_BOUNDARY_F,
                                         id_pair[0])
                    feature.setAttribute(
                        db.names.POINT_BFS_T_OP_BOUNDARY_POINT_F, id_pair[1])
                    features.append(feature)
            layers[db.names.POINT_BFS_T][LAYER].addFeatures(features)
            layers[db.names.POINT_BFS_T][LAYER].commitChanges()
            self.logger.info_msg(
                __name__,
                QCoreApplication.translate(
                    "ToolBar",
                    "{} out of {} records were saved into {}! {} out of {} records already existed in the database."
                ).format(len(features), len(id_pairs), db.names.POINT_BFS_T,
                         len(id_pairs) - len(features), len(id_pairs)))
        else:
            self.logger.info_msg(
                __name__,
                QCoreApplication.translate(
                    "ToolBar",
                    "No pairs id_boundary-id_boundary_point found."))
Beispiel #17
0
    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 parcel... We cannot do anything with {} parcels"
            ).format(self.WIZARD_TOOL_NAME, len(features))
            self.log.logMessage(
                "We should have got only one parcel... We cannot do anything with {} parcels"
                .format(len(features)), PLUGIN_NAME, Qgis.Warning)
        else:
            fid = features[0].id()

            if not self._layers[self.EDITING_LAYER_NAME][LAYER].getFeature(
                    fid).isValid():
                self.log.logMessage("Feature not found in layer Predio...",
                                    PLUGIN_NAME, Qgis.Warning)
            else:
                parcel_id = self._layers[
                    self.EDITING_LAYER_NAME][LAYER].getFeature(fid)[ID_FIELD]

                plot_ids = list()
                building_ids = list()
                building_unit_ids = list()

                # Apply restriction to the selection
                if PLOT_TABLE in CONSTRAINT_TYPES_OF_PARCEL[
                        self.cb_parcel_type.currentText()]:
                    if CONSTRAINT_TYPES_OF_PARCEL[
                            self.cb_parcel_type.currentText(
                            )][PLOT_TABLE] is not None:
                        plot_ids = [
                            f[ID_FIELD] for f in self._layers[PLOT_TABLE]
                            [LAYER].selectedFeatures()
                        ]
                else:
                    plot_ids = [
                        f[ID_FIELD] for f in self._layers[PLOT_TABLE]
                        [LAYER].selectedFeatures()
                    ]

                if BUILDING_TABLE in CONSTRAINT_TYPES_OF_PARCEL[
                        self.cb_parcel_type.currentText()]:
                    if CONSTRAINT_TYPES_OF_PARCEL[
                            self.cb_parcel_type.currentText(
                            )][BUILDING_TABLE] is not None:
                        building_ids = [
                            f[ID_FIELD] for f in self._layers[BUILDING_TABLE]
                            [LAYER].selectedFeatures()
                        ]
                else:
                    building_ids = [
                        f[ID_FIELD] for f in self._layers[BUILDING_TABLE]
                        [LAYER].selectedFeatures()
                    ]

                if BUILDING_UNIT_TABLE in CONSTRAINT_TYPES_OF_PARCEL[
                        self.cb_parcel_type.currentText()]:
                    if CONSTRAINT_TYPES_OF_PARCEL[
                            self.cb_parcel_type.currentText(
                            )][BUILDING_UNIT_TABLE] is not None:
                        building_unit_ids = [
                            f[ID_FIELD]
                            for f in self._layers[BUILDING_UNIT_TABLE]
                            [LAYER].selectedFeatures()
                        ]
                else:
                    building_unit_ids = [
                        f[ID_FIELD] for f in self._layers[BUILDING_UNIT_TABLE]
                        [LAYER].selectedFeatures()
                    ]

                # Fill uebaunit table
                new_features = []
                for plot_id in plot_ids:
                    new_feature = QgsVectorLayerUtils().createFeature(
                        self._layers[UEBAUNIT_TABLE][LAYER])
                    new_feature.setAttribute(UEBAUNIT_TABLE_PLOT_FIELD,
                                             plot_id)
                    new_feature.setAttribute(UEBAUNIT_TABLE_PARCEL_FIELD,
                                             parcel_id)
                    self.log.logMessage(
                        "Saving Plot-Parcel: {}-{}".format(plot_id, parcel_id),
                        PLUGIN_NAME, Qgis.Info)
                    new_features.append(new_feature)

                for building_id in building_ids:
                    new_feature = QgsVectorLayerUtils().createFeature(
                        self._layers[UEBAUNIT_TABLE][LAYER])
                    new_feature.setAttribute(UEBAUNIT_TABLE_BUILDING_FIELD,
                                             building_id)
                    new_feature.setAttribute(UEBAUNIT_TABLE_PARCEL_FIELD,
                                             parcel_id)
                    self.log.logMessage(
                        "Saving Building-Parcel: {}-{}".format(
                            building_id, parcel_id), PLUGIN_NAME, Qgis.Info)
                    new_features.append(new_feature)

                for building_unit_id in building_unit_ids:
                    new_feature = QgsVectorLayerUtils().createFeature(
                        self._layers[UEBAUNIT_TABLE][LAYER])
                    new_feature.setAttribute(
                        UEBAUNIT_TABLE_BUILDING_UNIT_FIELD, building_unit_id)
                    new_feature.setAttribute(UEBAUNIT_TABLE_PARCEL_FIELD,
                                             parcel_id)
                    self.log.logMessage(
                        "Saving Building Unit-Parcel: {}-{}".format(
                            building_unit_id, parcel_id), PLUGIN_NAME,
                        Qgis.Info)
                    new_features.append(new_feature)

                self._layers[UEBAUNIT_TABLE][LAYER].dataProvider().addFeatures(
                    new_features)

                if plot_ids and building_ids and building_unit_ids:
                    message = QCoreApplication.translate(
                        self.WIZARD_NAME,
                        "The new parcel (t_id={}) was successfully created and associated with its corresponding Plot (t_id={}) and Building(s) (t_id={}) and Building Unit(s) (t_id={})!"
                    ).format(parcel_id, ", ".join([str(b) for b in plot_ids]),
                             ", ".join([str(b) for b in building_ids]),
                             ", ".join([str(b) for b in building_unit_ids]))
                elif plot_ids and building_ids and not building_unit_ids:
                    message = QCoreApplication.translate(
                        self.WIZARD_NAME,
                        "The new parcel (t_id={}) was successfully created and associated with its corresponding Plot (t_id={}) and Building(s) (t_id={})!"
                    ).format(parcel_id, ", ".join([str(b) for b in plot_ids]),
                             ", ".join([str(b) for b in building_ids]))
                elif plot_ids and not building_ids and building_unit_ids:
                    message = QCoreApplication.translate(
                        self.WIZARD_NAME,
                        "The new parcel (t_id={}) was successfully created and associated with its corresponding Plot (t_id={}) and Building Unit(s) (t_id={})!"
                    ).format(parcel_id, ", ".join([str(b) for b in plot_ids]),
                             ", ".join([str(b) for b in building_unit_ids]))
                elif plot_ids and not building_ids and not building_unit_ids:
                    message = QCoreApplication.translate(
                        self.WIZARD_NAME,
                        "The new parcel (t_id={}) was successfully created and associated with its corresponding Plot (t_id={})!"
                    ).format(parcel_id, ", ".join([str(b) for b in plot_ids]))
                elif not plot_ids and building_ids and not building_unit_ids:
                    message = QCoreApplication.translate(
                        self.WIZARD_NAME,
                        "The new parcel (t_id={}) was successfully created and associated with its corresponding Building(s) (t_id={})!"
                    ).format(parcel_id,
                             ", ".join([str(b) for b in building_ids]))
                elif not plot_ids and building_ids and building_unit_ids:
                    message = QCoreApplication.translate(
                        self.WIZARD_NAME,
                        "The new parcel (t_id={}) was successfully created and associated with its corresponding Building(s) (t_id={}) and Building Unit(s) (t_id={})!"
                    ).format(parcel_id,
                             ", ".join([str(b) for b in building_ids]),
                             ", ".join([str(b) for b in building_unit_ids]))
                elif not plot_ids and not building_ids and building_unit_ids:
                    message = QCoreApplication.translate(
                        self.WIZARD_NAME,
                        "The new parcel (t_id={}) was successfully created and associated with its corresponding Building Unit(s) (t_id={})!"
                    ).format(parcel_id,
                             ", ".join([str(b) for b in building_unit_ids]))
                elif not plot_ids and not building_ids and not building_unit_ids:
                    message = QCoreApplication.translate(
                        self.WIZARD_NAME,
                        "The new parcel (t_id={}) was successfully created but this one wasn't associated with a spatial unit"
                    ).format(parcel_id)

        self._layers[
            self.EDITING_LAYER_NAME][LAYER].committedFeaturesAdded.disconnect(
                self.finish_feature_creation)
        self.log.logMessage(
            "Parcel's committedFeaturesAdded SIGNAL disconnected", PLUGIN_NAME,
            Qgis.Info)
        self.close_wizard(message)
    def fill_right_of_way_relations(self, db):
        # Load layers
        res_layers = self.qgis_utils.get_layers(db, {
            ADMINISTRATIVE_SOURCE_TABLE: {
                'name': ADMINISTRATIVE_SOURCE_TABLE,
                'geometry': None
            },
            PARCEL_TABLE: {
                'name': PARCEL_TABLE,
                'geometry': None
            },
            PLOT_TABLE: {
                'name': PLOT_TABLE,
                'geometry': QgsWkbTypes.PolygonGeometry
            },
            RESTRICTION_TABLE: {
                'name': RESTRICTION_TABLE,
                'geometry': None
            },
            RIGHT_OF_WAY_TABLE: {
                'name': RIGHT_OF_WAY_TABLE,
                'geometry': QgsWkbTypes.PolygonGeometry
            },
            RRR_SOURCE_RELATION_TABLE: {
                'name': RRR_SOURCE_RELATION_TABLE,
                'geometry': None
            },
            SURVEY_POINT_TABLE: {
                'name': SURVEY_POINT_TABLE,
                'geometry': None
            },
            UEBAUNIT_TABLE: {
                'name': UEBAUNIT_TABLE,
                'geometry': None
            }
        },
                                                load=True)

        self._administrative_source_layer = res_layers[
            ADMINISTRATIVE_SOURCE_TABLE]
        self._parcel_layer = res_layers[PARCEL_TABLE]
        self._plot_layer = res_layers[PLOT_TABLE]
        self._restriction_layer = res_layers[RESTRICTION_TABLE]
        self._right_of_way_layer = res_layers[RIGHT_OF_WAY_TABLE]
        self._survey_point_layer = res_layers[SURVEY_POINT_TABLE]
        self._rrr_source_relation_layer = res_layers[RRR_SOURCE_RELATION_TABLE]
        self._uebaunit_table = res_layers[UEBAUNIT_TABLE]

        if self._parcel_layer is None:
            self.qgis_utils.message_emitted.emit(
                QCoreApplication.translate(
                    "RightOfWay", "Table {} not found in the DB! {}").format(
                        PARCEL_TABLE, db.get_description()), Qgis.Warning)
            return

        if self._right_of_way_layer is None:
            self.qgis_utils.message_emitted.emit(
                QCoreApplication.translate(
                    "RightOfWay", "Table {} not found in the DB! {}").format(
                        RIGHT_OF_WAY_TABLE, db.get_description()),
                Qgis.Warning)
            return

        if self._uebaunit_table is None:
            self.iface.messageBar().pushMessage(
                "Asistente LADM_COL",
                QCoreApplication.translate(
                    "RightOfWay",
                    "UEBAUNIT table couldn't be found... {}").format(
                        self._db.get_description()), Qgis.Warning)
            return

        if self._plot_layer.selectedFeatureCount(
        ) == 0 or self._right_of_way_layer.selectedFeatureCount(
        ) == 0 or self._administrative_source_layer.selectedFeatureCount(
        ) == 0:
            if self.qgis_utils.get_layer_from_layer_tree(
                    PLOT_TABLE,
                    schema=db.schema,
                    geometry_type=QgsWkbTypes.PolygonGeometry) is None:
                self.qgis_utils.message_with_button_load_layer_emitted.emit(
                    QCoreApplication.translate(
                        "RightOfWay",
                        "First load the layer {} into QGIS and select at least one plot!"
                    ).format(PLOT_TABLE),
                    QCoreApplication.translate(
                        "RightOfWay", "Load layer {} now").format(PLOT_TABLE),
                    [PLOT_TABLE, None], Qgis.Warning)
            else:
                self.qgis_utils.message_emitted.emit(
                    QCoreApplication.translate(
                        "RightOfWay",
                        "Select at least one benefited plot, one right of way and at least one administrative source to create relations!"
                    ), Qgis.Warning)
                return
        else:
            ue_baunit_features = self._uebaunit_table.getFeatures()
            # Get unique pairs id_right_of_way-id_parcel
            existing_pairs = [
                (ue_baunit_feature[UEBAUNIT_TABLE_PARCEL_FIELD],
                 ue_baunit_feature[UEBAUNIT_TABLE_RIGHT_OF_WAY_FIELD])
                for ue_baunit_feature in ue_baunit_features
            ]
            existing_pairs = set(existing_pairs)

            plot_ids = [
                f[ID_FIELD] for f in self._plot_layer.selectedFeatures()
            ]

            right_of_way_id = self._right_of_way_layer.selectedFeatures(
            )[0].attribute(ID_FIELD)
            id_pairs = list()
            for plot in plot_ids:
                exp = "\"{uebaunit}\" = {plot}".format(
                    uebaunit=UEBAUNIT_TABLE_PLOT_FIELD, plot=plot)
                parcels = self._uebaunit_table.getFeatures(exp)
                for parcel in parcels:
                    id_pair = (parcel.attribute(UEBAUNIT_TABLE_PARCEL_FIELD),
                               right_of_way_id)
                    id_pairs.append(id_pair)

            if len(id_pairs) < len(plot_ids):
                # If any relationship plot-parcel is not found, we don't need to continue
                self.qgis_utils.message_emitted.emit(
                    QCoreApplication.translate(
                        "RightOfWay",
                        "One or more pairs id_plot-id_parcel weren't found, this is needed to create benefited and restriction relations."
                    ), Qgis.Warning)
                return

            if id_pairs:
                new_features = list()
                for id_pair in id_pairs:
                    if not id_pair in existing_pairs:
                        #Create feature
                        new_feature = QgsVectorLayerUtils().createFeature(
                            self._uebaunit_table)
                        new_feature.setAttribute(UEBAUNIT_TABLE_PARCEL_FIELD,
                                                 id_pair[0])
                        new_feature.setAttribute(
                            UEBAUNIT_TABLE_RIGHT_OF_WAY_FIELD, id_pair[1])
                        self.log.logMessage(
                            "Saving RightOfWay-Parcel: {}-{}".format(
                                id_pair[1], id_pair[0]), PLUGIN_NAME,
                            Qgis.Info)
                        new_features.append(new_feature)

                self._uebaunit_table.dataProvider().addFeatures(new_features)
                self.qgis_utils.message_emitted.emit(
                    QCoreApplication.translate(
                        "RightOfWay",
                        "{} out of {} records were saved into {}! {} out of {} records already existed in the database."
                    ).format(len(new_features), len(id_pairs), UEBAUNIT_TABLE,
                             len(id_pairs) - len(new_features), len(id_pairs)),
                    Qgis.Info)

            spatial_join_layer = processing.run(
                "qgis:joinattributesbylocation", {
                    'INPUT':
                    self._plot_layer,
                    'JOIN':
                    QgsProcessingFeatureSourceDefinition(
                        self._right_of_way_layer.id(), True),
                    'PREDICATE': [0],
                    'JOIN_FIELDS':
                    [ID_FIELD, RIGHT_OF_WAY_TABLE_IDENTIFICATOR_FIELD],
                    'METHOD':
                    0,
                    'DISCARD_NONMATCHING':
                    True,
                    'PREFIX':
                    '',
                    'OUTPUT':
                    'memory:'
                })['OUTPUT']

            restriction_features = self._restriction_layer.getFeatures()

            existing_restriction_pairs = [
                (restriction_feature[RESTRICTION_TABLE_PARCEL_FIELD],
                 restriction_feature[RESTRICTION_TABLE_DESCRIPTION_FIELD])
                for restriction_feature in restriction_features
            ]
            existing_restriction_pairs = set(existing_restriction_pairs)
            id_pairs_restriction = list()
            plot_ids = spatial_join_layer.getFeatures()

            for plot in plot_ids:
                exp = "\"uebaunit\" = {plot}".format(
                    uebaunit=UEBAUNIT_TABLE_PLOT_FIELD,
                    plot=plot.attribute(ID_FIELD))
                parcels = self._uebaunit_table.getFeatures(exp)
                for parcel in parcels:
                    id_pair_restriction = (
                        parcel.attribute(UEBAUNIT_TABLE_PARCEL_FIELD),
                        "Asociada a la servidumbre {}".format(
                            plot.attribute(
                                RIGHT_OF_WAY_TABLE_IDENTIFICATOR_FIELD)))
                    id_pairs_restriction.append(id_pair_restriction)

            new_restriction_features = list()
            if id_pairs_restriction:
                for id_pair in id_pairs_restriction:
                    if not id_pair in existing_restriction_pairs:
                        #Create feature
                        new_feature = QgsVectorLayerUtils().createFeature(
                            self._restriction_layer)
                        new_feature.setAttribute(
                            RESTRICTION_TABLE_PARCEL_FIELD, id_pair[0])
                        new_feature.setAttribute(
                            RESTRICTION_TABLE_DESCRIPTION_FIELD, id_pair[1])
                        new_feature.setAttribute(
                            TYPE_FIELD,
                            COL_RESTRICTION_TYPE_RIGHT_OF_WAY_VALUE)
                        self.log.logMessage(
                            "Saving RightOfWay-Parcel: {}-{}".format(
                                id_pair[1], id_pair[0]), PLUGIN_NAME,
                            Qgis.Info)
                        new_restriction_features.append(new_feature)

                self._restriction_layer.dataProvider().addFeatures(
                    new_restriction_features)
                self.qgis_utils.message_emitted.emit(
                    QCoreApplication.translate(
                        "RightOfWay",
                        "{} out of {} records were saved into {}! {} out of {} records already existed in the database."
                    ).format(
                        len(new_restriction_features),
                        len(id_pairs_restriction), RESTRICTION_TABLE,
                        len(id_pairs_restriction) -
                        len(new_restriction_features),
                        len(id_pairs_restriction)), Qgis.Info)

            administrative_source_ids = [
                f[ID_FIELD]
                for f in self._administrative_source_layer.selectedFeatures()
            ]

            source_relation_features = self._rrr_source_relation_layer.getFeatures(
            )

            existing_source_pairs = [
                (source_relation_feature[RRR_SOURCE_SOURCE_FIELD],
                 source_relation_feature[RRR_SOURCE_RESTRICTION_FIELD])
                for source_relation_feature in source_relation_features
            ]
            existing_source_pairs = set(existing_source_pairs)

            rrr_source_relation_pairs = list()

            for administrative_source_id in administrative_source_ids:
                for restriction_feature in new_restriction_features:
                    rrr_source_relation_pair = (
                        administrative_source_id,
                        restriction_feature.attribute(ID_FIELD))
                    rrr_source_relation_pairs.append(rrr_source_relation_pair)

            new_rrr_source_relation_features = list()
            if rrr_source_relation_pairs:
                for id_pair in rrr_source_relation_pairs:
                    if not id_pair in existing_source_pairs:
                        new_feature = QgsVectorLayerUtils().createFeature(
                            self._rrr_source_relation_layer)
                        new_feature.setAttribute(RRR_SOURCE_SOURCE_FIELD,
                                                 id_pair[0])
                        new_feature.setAttribute(RRR_SOURCE_RESTRICTION_FIELD,
                                                 id_pair[1])
                        self.log.logMessage(
                            "Saving Restriction-Source: {}-{}".format(
                                id_pair[1], id_pair[0]), PLUGIN_NAME,
                            Qgis.Info)
                        new_rrr_source_relation_features.append(new_feature)

                self._rrr_source_relation_layer.dataProvider().addFeatures(
                    new_rrr_source_relation_features)
                self.qgis_utils.message_emitted.emit(
                    QCoreApplication.translate(
                        "RightOfWay",
                        "{} out of {} records were saved into {}! {} out of {} records already existed in the database."
                    ).format(
                        len(new_rrr_source_relation_features),
                        len(rrr_source_relation_pairs),
                        RRR_SOURCE_RELATION_TABLE,
                        len(rrr_source_relation_pairs) -
                        len(new_rrr_source_relation_features),
                        len(rrr_source_relation_pairs)), Qgis.Info)
Beispiel #19
0
    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 source... We cannot do anything with {} spatial sources").format(self.WIZARD_TOOL_NAME, len(features))
            self.log.logMessage("We should have got only one spatial source... We cannot do anything with {} spatial sources".format(len(features)), PLUGIN_NAME, Qgis.Warning)
        else:

            feature = features[0]
            feature_ids_dict = dict()

            if self._layers[PLOT_TABLE][LAYER] is not None:
                if self._layers[PLOT_TABLE][LAYER].selectedFeatureCount() > 0:
                    feature_ids_dict[PLOT_TABLE] = [f[ID_FIELD] for f in self._layers[PLOT_TABLE][LAYER].selectedFeatures()]

            if self._layers[BOUNDARY_TABLE][LAYER] is not None:
                if self._layers[BOUNDARY_TABLE][LAYER].selectedFeatureCount() > 0:
                    feature_ids_dict[BOUNDARY_TABLE] = [f[ID_FIELD] for f in self._layers[BOUNDARY_TABLE][LAYER].selectedFeatures()]

            if self._layers[BOUNDARY_POINT_TABLE][LAYER] is not None:
                if self._layers[BOUNDARY_POINT_TABLE][LAYER].selectedFeatureCount() > 0:
                    feature_ids_dict[BOUNDARY_POINT_TABLE] = [f[ID_FIELD] for f in self._layers[BOUNDARY_POINT_TABLE][LAYER].selectedFeatures()]

            if self._layers[SURVEY_POINT_TABLE][LAYER] is not None:
                if self._layers[SURVEY_POINT_TABLE][LAYER].selectedFeatureCount() > 0:
                    feature_ids_dict[SURVEY_POINT_TABLE] = [f[ID_FIELD] for f in self._layers[SURVEY_POINT_TABLE][LAYER].selectedFeatures()]

            if self._layers[CONTROL_POINT_TABLE][LAYER] is not None:
                if self._layers[CONTROL_POINT_TABLE][LAYER].selectedFeatureCount() > 0:
                    feature_ids_dict[CONTROL_POINT_TABLE] = [f[ID_FIELD] for f in self._layers[CONTROL_POINT_TABLE][LAYER].selectedFeatures()]

            if not feature.isValid():
                self.log.logMessage("Feature not found in layer Spatial Source...", PLUGIN_NAME, Qgis.Warning)
            else:
                spatial_source_id = feature[ID_FIELD]
                all_new_features = list()

                # Fill association table, depending on the case
                new_features = list()
                if PLOT_TABLE in feature_ids_dict:
                    # Fill uesource table
                    for plot_id in feature_ids_dict[PLOT_TABLE]:
                        new_feature = QgsVectorLayerUtils().createFeature(self._layers[UESOURCE_TABLE][LAYER])
                        new_feature.setAttribute(UESOURCE_TABLE_PLOT_FIELD, plot_id)
                        new_feature.setAttribute(UESOURCE_TABLE_SOURCE_FIELD, spatial_source_id)
                        self.log.logMessage("Saving Plot-SpatialSource: {}-{}".format(plot_id, spatial_source_id), PLUGIN_NAME, Qgis.Info)
                        new_features.append(new_feature)

                    self._layers[UESOURCE_TABLE][LAYER].dataProvider().addFeatures(new_features)
                    all_new_features.extend(new_feature)

                new_features = list()
                if BOUNDARY_TABLE in feature_ids_dict:
                    # Fill cclsource table
                    for boundary_id in feature_ids_dict[BOUNDARY_TABLE]:
                        new_feature = QgsVectorLayerUtils().createFeature(self._layers[CCLSOURCE_TABLE][LAYER])
                        new_feature.setAttribute(CCLSOURCE_TABLE_BOUNDARY_FIELD, boundary_id)
                        new_feature.setAttribute(CCLSOURCE_TABLE_SOURCE_FIELD, spatial_source_id)
                        self.log.logMessage("Saving Boundary-SpatialSource: {}-{}".format(boundary_id, spatial_source_id), PLUGIN_NAME, Qgis.Info)
                        new_features.append(new_feature)

                    self._layers[CCLSOURCE_TABLE][LAYER].dataProvider().addFeatures(new_features)
                    all_new_features.extend(new_feature)

                new_features = list()
                if BOUNDARY_POINT_TABLE in feature_ids_dict:
                    for boundary_point_id in feature_ids_dict[BOUNDARY_POINT_TABLE]:
                        new_feature = QgsVectorLayerUtils().createFeature(self._layers[POINTSOURCE_TABLE][LAYER])
                        new_feature.setAttribute(POINTSOURCE_TABLE_BOUNDARYPOINT_FIELD, boundary_point_id)
                        new_feature.setAttribute(POINTSOURCE_TABLE_SOURCE_FIELD, spatial_source_id)
                        self.log.logMessage("Saving BoundaryPoint-SpatialSource: {}-{}".format(boundary_point_id, spatial_source_id), PLUGIN_NAME, Qgis.Info)
                        new_features.append(new_feature)

                    self._layers[POINTSOURCE_TABLE][LAYER].dataProvider().addFeatures(new_features)
                    all_new_features.extend(new_feature)

                new_features = list()
                if SURVEY_POINT_TABLE in feature_ids_dict:
                    for survey_point_id in feature_ids_dict[SURVEY_POINT_TABLE]:
                        new_feature = QgsVectorLayerUtils().createFeature(self._layers[POINTSOURCE_TABLE][LAYER])
                        new_feature.setAttribute(POINTSOURCE_TABLE_SURVEYPOINT_FIELD, survey_point_id)
                        new_feature.setAttribute(POINTSOURCE_TABLE_SOURCE_FIELD, spatial_source_id)
                        self.log.logMessage("Saving SurveyPoint-SpatialSource: {}-{}".format(survey_point_id, spatial_source_id), PLUGIN_NAME, Qgis.Info)
                        new_features.append(new_feature)

                    self._layers[POINTSOURCE_TABLE][LAYER].dataProvider().addFeatures(new_features)
                    all_new_features.extend(new_feature)

                new_features = list()
                if CONTROL_POINT_TABLE in feature_ids_dict:
                    for control_point_id in feature_ids_dict[CONTROL_POINT_TABLE]:
                        new_feature = QgsVectorLayerUtils().createFeature(self._layers[POINTSOURCE_TABLE][LAYER])
                        new_feature.setAttribute(POINTSOURCE_TABLE_CONTROLPOINT_FIELD, control_point_id)
                        new_feature.setAttribute(POINTSOURCE_TABLE_SOURCE_FIELD, spatial_source_id)
                        self.log.logMessage("Saving ControlPoint-SpatialSource: {}-{}".format(control_point_id, spatial_source_id), PLUGIN_NAME, Qgis.Info)
                        new_features.append(new_feature)

                    self._layers[POINTSOURCE_TABLE][LAYER].dataProvider().addFeatures(new_features)
                    all_new_features.extend(new_feature)

                if all_new_features:
                    message = QCoreApplication.translate(self.WIZARD_NAME,
                                                   "The new spatial source (t_id={}) was successfully created and associated with the following features: {}").format(spatial_source_id, feature_ids_dict)
                else:
                    message = QCoreApplication.translate(self.WIZARD_NAME,
                                                   "The new spatial source (t_id={}) was successfully created and it wasn't associated with a spatial unit").format(spatial_source_id)

        self._layers[self.EDITING_LAYER_NAME][LAYER].committedFeaturesAdded.disconnect()
        self.log.logMessage("Spatial Source's committedFeaturesAdded SIGNAL disconnected", PLUGIN_NAME, Qgis.Info)
        self.close_wizard(message)
Beispiel #20
0
    def finish_parcel(self, plot_ids, building_ids, layerId, features):
        if len(features) != 1:
            self.log.logMessage(
                "We should have got only one predio... We cannot do anything with {} predios"
                .format(len(features)), PLUGIN_NAME, Qgis.Warning)
        else:
            fid = features[0].id()
            if not self._parcel_layer.getFeature(fid).isValid():
                self.log.logMessage("Feature not found in layer Predio...",
                                    PLUGIN_NAME, Qgis.Warning)
            else:
                parcel_id = self._parcel_layer.getFeature(fid)[ID_FIELD]

                # Fill uebaunit table
                new_features = []
                for plot_id in plot_ids:
                    new_feature = QgsVectorLayerUtils().createFeature(
                        self._uebaunit_table)
                    new_feature.setAttribute(UEBAUNIT_TABLE_PLOT_FIELD,
                                             plot_id)
                    new_feature.setAttribute(UEBAUNIT_TABLE_PARCEL_FIELD,
                                             parcel_id)
                    self.log.logMessage(
                        "Saving Plot-Parcel: {}-{}".format(plot_id, parcel_id),
                        PLUGIN_NAME, Qgis.Info)
                    new_features.append(new_feature)

                for building_id in building_ids:
                    new_feature = QgsVectorLayerUtils().createFeature(
                        self._uebaunit_table)
                    new_feature.setAttribute(UEBAUNIT_TABLE_BUILDING_FIELD,
                                             building_id)
                    new_feature.setAttribute(UEBAUNIT_TABLE_PARCEL_FIELD,
                                             parcel_id)
                    self.log.logMessage(
                        "Saving Building-Parcel: {}-{}".format(
                            building_id, parcel_id), PLUGIN_NAME, Qgis.Info)
                    new_features.append(new_feature)

                self._uebaunit_table.dataProvider().addFeatures(new_features)

                if plot_ids and building_ids:
                    self.iface.messageBar().pushMessage(
                        "Asistente LADM_COL",
                        QCoreApplication.translate(
                            "CreateParcelCadastreWizard",
                            "The new parcel (t_id={}) was successfully created and associated with its corresponding Plot (t_id={}) and Building(s) (t_id={})!"
                        ).format(parcel_id, plot_ids[0],
                                 ", ".join([str(b) for b in building_ids])),
                        Qgis.Info)
                elif plot_ids and not building_ids:
                    self.iface.messageBar().pushMessage(
                        "Asistente LADM_COL",
                        QCoreApplication.translate(
                            "CreateParcelCadastreWizard",
                            "The new parcel (t_id={}) was successfully created and associated with its corresponding Plot (t_id={})!"
                        ).format(parcel_id, plot_ids[0]), Qgis.Info)
                elif not plot_ids and building_ids:
                    self.iface.messageBar().pushMessage(
                        "Asistente LADM_COL",
                        QCoreApplication.translate(
                            "CreateParcelCadastreWizard",
                            "The new parcel (t_id={}) was successfully created and associated with its corresponding Building(s) (t_id={})!"
                        ).format(parcel_id,
                                 ", ".join([str(b) for b in building_ids])),
                        Qgis.Info)

        self._parcel_layer.committedFeaturesAdded.disconnect()
        self.log.logMessage(
            "Parcel's committedFeaturesAdded SIGNAL disconnected", PLUGIN_NAME,
            Qgis.Info)
    def post_save(self, features):
        constraint_types_of_parcels = LayerConfig.get_constraint_types_of_parcels(self.names)
        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()

            if not self._layers[self.EDITING_LAYER_NAME][LAYER].getFeature(fid).isValid():
                self.logger.warning(__name__, "Feature not found in layer {}...".format(self.EDITING_LAYER_NAME))
            else:
                parcel_id = self._layers[self.EDITING_LAYER_NAME][LAYER].getFeature(fid)[self.names.T_ID_F]

                plot_ids = list()
                building_ids = list()
                building_unit_ids = list()

                # Apply restriction to the selection
                if self.names.OP_PLOT_T in constraint_types_of_parcels[self.dict_parcel_type[self.cb_parcel_type.currentText()]]:
                    if constraint_types_of_parcels[self.dict_parcel_type[self.cb_parcel_type.currentText()]][self.names.OP_PLOT_T] is not None:
                        plot_ids = [f[self.names.T_ID_F] for f in self._layers[self.names.OP_PLOT_T][LAYER].selectedFeatures()]
                else:
                    plot_ids = [f[self.names.T_ID_F] for f in self._layers[self.names.OP_PLOT_T][LAYER].selectedFeatures()]

                if self.names.OP_BUILDING_T in constraint_types_of_parcels[self.dict_parcel_type[self.cb_parcel_type.currentText()]]:
                    if constraint_types_of_parcels[self.dict_parcel_type[self.cb_parcel_type.currentText()]][self.names.OP_BUILDING_T] is not None:
                        building_ids = [f[self.names.T_ID_F] for f in self._layers[self.names.OP_BUILDING_T][LAYER].selectedFeatures()]
                else:
                    building_ids = [f[self.names.T_ID_F] for f in self._layers[self.names.OP_BUILDING_T][LAYER].selectedFeatures()]

                if self.names.OP_BUILDING_UNIT_T in constraint_types_of_parcels[self.dict_parcel_type[self.cb_parcel_type.currentText()]]:
                    if constraint_types_of_parcels[self.dict_parcel_type[self.cb_parcel_type.currentText()]][self.names.OP_BUILDING_UNIT_T] is not None:
                        building_unit_ids = [f[self.names.T_ID_F] for f in
                                             self._layers[self.names.OP_BUILDING_UNIT_T][LAYER].selectedFeatures()]
                else:
                    building_unit_ids = [f[self.names.T_ID_F] for f in
                                         self._layers[self.names.OP_BUILDING_UNIT_T][LAYER].selectedFeatures()]

                # Fill uebaunit table
                new_features = []
                for plot_id in plot_ids:
                    new_feature = QgsVectorLayerUtils().createFeature(self._layers[self.names.COL_UE_BAUNIT_T][LAYER])
                    new_feature.setAttribute(self.names.COL_UE_BAUNIT_T_OP_PLOT_F, plot_id)
                    new_feature.setAttribute(self.names.COL_UE_BAUNIT_T_PARCEL_F, parcel_id)
                    self.logger.info(__name__, "Saving Plot-Parcel: {}-{}".format(plot_id, parcel_id))
                    new_features.append(new_feature)

                for building_id in building_ids:
                    new_feature = QgsVectorLayerUtils().createFeature(self._layers[self.names.COL_UE_BAUNIT_T][LAYER])
                    new_feature.setAttribute(self.names.COL_UE_BAUNIT_T_OP_BUILDING_F, building_id)
                    new_feature.setAttribute(self.names.COL_UE_BAUNIT_T_PARCEL_F, parcel_id)
                    self.logger.info(__name__, "Saving Building-Parcel: {}-{}".format(building_id, parcel_id))
                    new_features.append(new_feature)

                for building_unit_id in building_unit_ids:
                    new_feature = QgsVectorLayerUtils().createFeature(self._layers[self.names.COL_UE_BAUNIT_T][LAYER])
                    new_feature.setAttribute(self.names.COL_UE_BAUNIT_T_OP_BUILDING_UNIT_F, building_unit_id)
                    new_feature.setAttribute(self.names.COL_UE_BAUNIT_T_PARCEL_F, parcel_id)
                    self.logger.info(__name__, "Saving Building Unit-Parcel: {}-{}".format(building_unit_id, parcel_id))
                    new_features.append(new_feature)

                self._layers[self.names.COL_UE_BAUNIT_T][LAYER].dataProvider().addFeatures(new_features)

                if plot_ids and building_ids and building_unit_ids:
                    message = QCoreApplication.translate("WizardTranslations",
                                                   "The new parcel (t_id={}) was successfully created and associated with its corresponding Plot (t_id={}) and Building(s) (t_id={}) and Building Unit(s) (t_id={})!").format(parcel_id, ", ".join([str(b) for b in plot_ids]), ", ".join([str(b) for b in building_ids]), ", ".join([str(b) for b in building_unit_ids]))
                elif plot_ids and building_ids and not building_unit_ids:
                    message = QCoreApplication.translate("WizardTranslations",
                                                   "The new parcel (t_id={}) was successfully created and associated with its corresponding Plot (t_id={}) and Building(s) (t_id={})!").format(parcel_id, ", ".join([str(b) for b in plot_ids]), ", ".join([str(b) for b in building_ids]))
                elif plot_ids and not building_ids and building_unit_ids:
                    message = QCoreApplication.translate("WizardTranslations",
                                                   "The new parcel (t_id={}) was successfully created and associated with its corresponding Plot (t_id={}) and Building Unit(s) (t_id={})!").format(parcel_id, ", ".join([str(b) for b in plot_ids]), ", ".join([str(b) for b in building_unit_ids]))
                elif plot_ids and not building_ids and not building_unit_ids:
                    message = QCoreApplication.translate("WizardTranslations",
                                                   "The new parcel (t_id={}) was successfully created and associated with its corresponding Plot (t_id={})!").format(parcel_id, ", ".join([str(b) for b in plot_ids]))
                elif not plot_ids and building_ids and not building_unit_ids:
                    message = QCoreApplication.translate("WizardTranslations",
                                                   "The new parcel (t_id={}) was successfully created and associated with its corresponding Building(s) (t_id={})!").format(parcel_id, ", ".join([str(b) for b in building_ids]))
                elif not plot_ids and building_ids and building_unit_ids:
                    message = QCoreApplication.translate("WizardTranslations",
                                                         "The new parcel (t_id={}) was successfully created and associated with its corresponding Building(s) (t_id={}) and Building Unit(s) (t_id={})!").format(parcel_id, ", ".join([str(b) for b in building_ids]), ", ".join([str(b) for b in building_unit_ids]))
                elif not plot_ids and not building_ids and building_unit_ids:
                    message = QCoreApplication.translate("WizardTranslations",
                                                         "The new parcel (t_id={}) was successfully created and associated with its corresponding Building Unit(s) (t_id={})!").format(parcel_id, ", ".join([str(b) for b in building_unit_ids]))
                elif not plot_ids and not building_ids and not building_unit_ids:
                    message = QCoreApplication.translate("WizardTranslations",
                                                         "The new parcel (t_id={}) was successfully created but this one wasn't associated with a spatial unit").format(parcel_id)

        return message
    def fill_topology_tables_morebfs_less(self, db, use_selection=True):
        layers = {
            PLOT_TABLE: {
                'name': PLOT_TABLE,
                'geometry': QgsWkbTypes.PolygonGeometry,
                LAYER: None
            },
            MORE_BOUNDARY_FACE_STRING_TABLE: {
                'name': MORE_BOUNDARY_FACE_STRING_TABLE,
                'geometry': None,
                LAYER: None
            },
            LESS_TABLE: {
                'name': LESS_TABLE,
                'geometry': None,
                LAYER: None
            },
            BOUNDARY_TABLE: {
                'name': BOUNDARY_TABLE,
                'geometry': None,
                LAYER: None
            }
        }

        self.qgis_utils.get_layers(db, layers, load=True)
        if not layers:
            return None

        if use_selection:
            if layers[PLOT_TABLE][LAYER].selectedFeatureCount() == 0:
                if self.qgis_utils.get_layer_from_layer_tree(
                        db, PLOT_TABLE,
                        geometry_type=QgsWkbTypes.PolygonGeometry) is None:
                    self.qgis_utils.message_with_button_load_layer_emitted.emit(
                        QCoreApplication.translate(
                            "ToolBar",
                            "First load the layer {} into QGIS and select at least one plot!"
                        ).format(PLOT_TABLE),
                        QCoreApplication.translate(
                            "ToolBar", "Load layer {} now").format(PLOT_TABLE),
                        [PLOT_TABLE, None], Qgis.Warning)
                else:
                    reply = QMessageBox.question(
                        None,
                        QCoreApplication.translate("ToolBar", "Continue?"),
                        QCoreApplication.translate(
                            "ToolBar",
                            "There are no selected plots, do you like to fill the '{more}' and '{less}' tables for all the {all} plots in the data base?"
                        ).format(more=MORE_BOUNDARY_FACE_STRING_TABLE,
                                 less=LESS_TABLE,
                                 all=layers[PLOT_TABLE][LAYER].featureCount()),
                        QMessageBox.Yes, QMessageBox.No)
                    if reply == QMessageBox.Yes:
                        use_selection = False
                    else:
                        self.qgis_utils.message_emitted.emit(
                            QCoreApplication.translate(
                                "ToolBar", "First select at least one plot!"),
                            Qgis.Warning)
                        return
            else:
                reply = QMessageBox.question(
                    None, QCoreApplication.translate("ToolBar", "Continue?"),
                    QCoreApplication.translate(
                        "ToolBar",
                        "There are {selected} plots selected, do you like to fill the '{more}' and '{less}' tables just for the selected plots?\n\nIf you say 'No', the '{more}' and '{less}' tables will be filled for all plots in the database."
                    ).format(selected=layers[PLOT_TABLE]
                             [LAYER].selectedFeatureCount(),
                             more=MORE_BOUNDARY_FACE_STRING_TABLE,
                             less=LESS_TABLE), QMessageBox.Yes, QMessageBox.No)
                if reply == QMessageBox.No:
                    use_selection = False

        more_bfs_features = layers[MORE_BOUNDARY_FACE_STRING_TABLE][
            LAYER].getFeatures()
        less_features = layers[LESS_TABLE][LAYER].getFeatures()

        # Get unique pairs id_boundary-id_plot in both tables
        existing_more_pairs = [(more_bfs_feature[MOREBFS_TABLE_PLOT_FIELD],
                                more_bfs_feature[MOREBFS_TABLE_BOUNDARY_FIELD])
                               for more_bfs_feature in more_bfs_features]
        existing_more_pairs = set(existing_more_pairs)
        existing_less_pairs = [(less_feature[LESS_TABLE_PLOT_FIELD],
                                less_feature[LESS_TABLE_BOUNDARY_FIELD])
                               for less_feature in less_features]
        existing_less_pairs = set(existing_less_pairs)

        id_more_pairs, id_less_pairs = self.geometry.get_pair_boundary_plot(
            layers[BOUNDARY_TABLE][LAYER],
            layers[PLOT_TABLE][LAYER],
            use_selection=use_selection)
        if id_less_pairs:
            layers[LESS_TABLE][LAYER].startEditing()
            features = list()
            for id_pair in id_less_pairs:
                if not id_pair in existing_less_pairs:  # Avoid duplicated pairs in the DB
                    # Create feature
                    feature = QgsVectorLayerUtils().createFeature(
                        layers[LESS_TABLE][LAYER])
                    feature.setAttribute(LESS_TABLE_PLOT_FIELD, id_pair[0])
                    feature.setAttribute(LESS_TABLE_BOUNDARY_FIELD, id_pair[1])
                    features.append(feature)
            layers[LESS_TABLE][LAYER].addFeatures(features)
            layers[LESS_TABLE][LAYER].commitChanges()
            self.qgis_utils.message_emitted.emit(
                QCoreApplication.translate(
                    "ToolBar",
                    "{} out of {} records were saved into '{}'! {} out of {} records already existed in the database."
                ).format(len(features), len(id_less_pairs), LESS_TABLE,
                         len(id_less_pairs) - len(features),
                         len(id_less_pairs)), Qgis.Info)
        else:
            self.qgis_utils.message_emitted.emit(
                QCoreApplication.translate(
                    "ToolBar",
                    "No pairs id_boundary-id_plot found for '{}' table.").
                format(LESS_TABLE), Qgis.Info)

        if id_more_pairs:
            layers[MORE_BOUNDARY_FACE_STRING_TABLE][LAYER].startEditing()
            features = list()
            for id_pair in id_more_pairs:
                if not id_pair in existing_more_pairs:  # Avoid duplicated pairs in the DB
                    # Create feature
                    feature = QgsVectorLayerUtils().createFeature(
                        layers[MORE_BOUNDARY_FACE_STRING_TABLE][LAYER])
                    feature.setAttribute(MOREBFS_TABLE_PLOT_FIELD, id_pair[0])
                    feature.setAttribute(MOREBFS_TABLE_BOUNDARY_FIELD,
                                         id_pair[1])
                    features.append(feature)
            layers[MORE_BOUNDARY_FACE_STRING_TABLE][LAYER].addFeatures(
                features)
            layers[MORE_BOUNDARY_FACE_STRING_TABLE][LAYER].commitChanges()
            self.qgis_utils.message_emitted.emit(
                QCoreApplication.translate(
                    "ToolBar",
                    "{} out of {} records were saved into '{}'! {} out of {} records already existed in the database."
                ).format(len(features), len(id_more_pairs),
                         MORE_BOUNDARY_FACE_STRING_TABLE,
                         len(id_more_pairs) - len(features),
                         len(id_more_pairs)), Qgis.Info)
        else:
            self.qgis_utils.message_emitted.emit(
                QCoreApplication.translate(
                    "ToolBar",
                    "No pairs id_boundary-id_plot found for '{}' table.").
                format(MORE_BOUNDARY_FACE_STRING_TABLE), Qgis.Info)
    def fill_topology_table_pointbfs(self, db, use_selection=True):
        layers = {
            BOUNDARY_TABLE: {
                'name': BOUNDARY_TABLE,
                'geometry': None,
                LAYER: None
            },
            POINT_BOUNDARY_FACE_STRING_TABLE: {
                'name': POINT_BOUNDARY_FACE_STRING_TABLE,
                'geometry': None,
                LAYER: None
            },
            BOUNDARY_POINT_TABLE: {
                'name': BOUNDARY_POINT_TABLE,
                'geometry': None,
                LAYER: None
            }
        }

        self.qgis_utils.get_layers(db, layers, load=True)
        if not layers:
            return None

        if use_selection:
            if layers[BOUNDARY_TABLE][LAYER].selectedFeatureCount() == 0:
                if self.qgis_utils.get_layer_from_layer_tree(
                        db, BOUNDARY_TABLE) is None:
                    self.qgis_utils.message_with_button_load_layer_emitted.emit(
                        QCoreApplication.translate(
                            "ToolBar",
                            "First load the layer {} into QGIS and select at least one boundary!"
                        ).format(BOUNDARY_TABLE),
                        QCoreApplication.translate(
                            "ToolBar",
                            "Load layer {} now").format(BOUNDARY_TABLE),
                        [BOUNDARY_TABLE, None], Qgis.Warning)
                else:
                    reply = QMessageBox.question(
                        None,
                        QCoreApplication.translate("ToolBar", "Continue?"),
                        QCoreApplication.translate(
                            "ToolBar",
                            "There are no selected boundaries, do you like to fill the '{}' table for all the {} boundaries in the data base?"
                        ).format(POINT_BOUNDARY_FACE_STRING_TABLE,
                                 layers[BOUNDARY_TABLE][LAYER].featureCount()),
                        QMessageBox.Yes, QMessageBox.No)
                    if reply == QMessageBox.Yes:
                        use_selection = False
                    else:
                        self.qgis_utils.message_emitted.emit(
                            QCoreApplication.translate(
                                "ToolBar",
                                "First select at least one boundary!"),
                            Qgis.Warning)
                        return
            else:
                reply = QMessageBox.question(
                    None, QCoreApplication.translate("ToolBar", "Continue?"),
                    QCoreApplication.translate(
                        "ToolBar",
                        "There are {selected} boundaries selected, do you like to fill the '{table}' table just for the selected boundaries?\n\nIf you say 'No', the '{table}' table will be filled for all boundaries in the database."
                    ).format(selected=layers[BOUNDARY_TABLE]
                             [LAYER].selectedFeatureCount(),
                             table=POINT_BOUNDARY_FACE_STRING_TABLE),
                    QMessageBox.Yes, QMessageBox.No)
                if reply == QMessageBox.No:
                    use_selection = False

        bfs_features = layers[POINT_BOUNDARY_FACE_STRING_TABLE][
            LAYER].getFeatures()

        # Get unique pairs id_boundary-id_boundary_point
        existing_pairs = [(bfs_feature[POINT_BFS_TABLE_BOUNDARY_FIELD],
                           bfs_feature[BFS_TABLE_BOUNDARY_POINT_FIELD])
                          for bfs_feature in bfs_features]
        existing_pairs = set(existing_pairs)

        id_pairs = self.geometry.get_pair_boundary_boundary_point(
            layers[BOUNDARY_TABLE][LAYER],
            layers[BOUNDARY_POINT_TABLE][LAYER],
            use_selection=use_selection)

        if id_pairs:
            layers[POINT_BOUNDARY_FACE_STRING_TABLE][LAYER].startEditing()
            features = list()
            for id_pair in id_pairs:
                if not id_pair in existing_pairs:  # Avoid duplicated pairs in the DB
                    # Create feature
                    feature = QgsVectorLayerUtils().createFeature(
                        layers[POINT_BOUNDARY_FACE_STRING_TABLE][LAYER])
                    feature.setAttribute(POINT_BFS_TABLE_BOUNDARY_FIELD,
                                         id_pair[0])
                    feature.setAttribute(BFS_TABLE_BOUNDARY_POINT_FIELD,
                                         id_pair[1])
                    features.append(feature)
            layers[POINT_BOUNDARY_FACE_STRING_TABLE][LAYER].addFeatures(
                features)
            layers[POINT_BOUNDARY_FACE_STRING_TABLE][LAYER].commitChanges()
            self.qgis_utils.message_emitted.emit(
                QCoreApplication.translate(
                    "ToolBar",
                    "{} out of {} records were saved into {}! {} out of {} records already existed in the database."
                ).format(len(features), len(id_pairs),
                         POINT_BOUNDARY_FACE_STRING_TABLE,
                         len(id_pairs) - len(features), len(id_pairs)),
                Qgis.Info)
        else:
            self.qgis_utils.message_emitted.emit(
                QCoreApplication.translate(
                    "ToolBar",
                    "No pairs id_boundary-id_boundary_point found."),
                Qgis.Info)
Beispiel #24
0
    def fill_right_of_way_relations(self, db):
        layers = {
            db.names.LC_ADMINISTRATIVE_SOURCE_T: None,
            db.names.LC_PARCEL_T: None,
            db.names.LC_PLOT_T: None,
            db.names.LC_RESTRICTION_T: None,
            db.names.LC_RESTRICTION_TYPE_D: None,
            db.names.LC_RIGHT_OF_WAY_T: None,
            db.names.COL_RRR_SOURCE_T: None,
            db.names.LC_SURVEY_POINT_T: None,
            db.names.COL_UE_BAUNIT_T: None
        }

        # Load layers
        self.app.core.get_layers(db, layers, load=True)
        if not layers:
            return None

        exp = "\"{}\" = '{}'".format(
            db.names.ILICODE_F,
            LADMNames.RESTRICTION_TYPE_D_RIGHT_OF_WAY_ILICODE_VALUE)
        restriction_right_of_way_t_id = [
            feature for feature in layers[
                db.names.LC_RESTRICTION_TYPE_D].getFeatures(exp)
        ][0][db.names.T_ID_F]

        if layers[db.names.LC_PLOT_T].selectedFeatureCount() == 0 or layers[
                db.names.LC_RIGHT_OF_WAY_T].selectedFeatureCount(
                ) == 0 or layers[
                    db.names.LC_ADMINISTRATIVE_SOURCE_T].selectedFeatureCount(
                    ) == 0:
            if self.app.core.get_ladm_layer_from_qgis(
                    db, db.names.LC_PLOT_T,
                    EnumLayerRegistryType.IN_LAYER_TREE) is None:
                self.logger.message_with_button_load_layer_emitted.emit(
                    QCoreApplication.translate(
                        "RightOfWay",
                        "First load the layer {} into QGIS and select at least one plot!"
                    ).format(db.names.LC_PLOT_T),
                    QCoreApplication.translate("RightOfWay",
                                               "Load layer {} now").format(
                                                   db.names.LC_PLOT_T),
                    db.names.LC_PLOT_T, Qgis.Warning)
            else:
                self.logger.warning_msg(
                    __name__,
                    QCoreApplication.translate(
                        "RightOfWay",
                        "Select at least one benefited plot, one right of way and at least one administrative source to create relations!"
                    ))
                return
        else:
            ue_baunit_features = layers[db.names.COL_UE_BAUNIT_T].getFeatures()
            # Get unique pairs id_right_of_way-id_parcel
            existing_pairs = [
                (ue_baunit_feature[db.names.COL_UE_BAUNIT_T_PARCEL_F],
                 ue_baunit_feature[db.names.COL_UE_BAUNIT_T_LC_RIGHT_OF_WAY_F])
                for ue_baunit_feature in ue_baunit_features
            ]
            existing_pairs = set(existing_pairs)

            plot_ids = [
                f[db.names.T_ID_F]
                for f in layers[db.names.LC_PLOT_T].selectedFeatures()
            ]

            right_of_way_id = layers[
                db.names.LC_RIGHT_OF_WAY_T].selectedFeatures()[0].attribute(
                    db.names.T_ID_F)
            id_pairs = list()
            for plot in plot_ids:
                exp = "\"{uebaunit}\" = {plot}".format(
                    uebaunit=db.names.COL_UE_BAUNIT_T_LC_PLOT_F, plot=plot)
                parcels = layers[db.names.COL_UE_BAUNIT_T].getFeatures(exp)
                for parcel in parcels:
                    id_pair = (parcel.attribute(
                        db.names.COL_UE_BAUNIT_T_PARCEL_F), right_of_way_id)
                    id_pairs.append(id_pair)

            if len(id_pairs) < len(plot_ids):
                # If any relationship plot-parcel is not found, we don't need to continue
                self.logger.warning_msg(
                    __name__,
                    QCoreApplication.translate(
                        "RightOfWay",
                        "One or more pairs id_plot-id_parcel weren't found, this is needed to create benefited and restriction relations."
                    ))
                return

            if id_pairs:
                new_features = list()
                for id_pair in id_pairs:
                    if not id_pair in existing_pairs:
                        #Create feature
                        new_feature = QgsVectorLayerUtils().createFeature(
                            layers[db.names.COL_UE_BAUNIT_T])
                        new_feature.setAttribute(
                            db.names.COL_UE_BAUNIT_T_PARCEL_F, id_pair[0])
                        new_feature.setAttribute(
                            db.names.COL_UE_BAUNIT_T_LC_RIGHT_OF_WAY_F,
                            id_pair[1])
                        self.logger.info(
                            __name__, "Saving RightOfWay-Parcel: {}-{}".format(
                                id_pair[1], id_pair[0]))
                        new_features.append(new_feature)

                layers[db.names.COL_UE_BAUNIT_T].dataProvider().addFeatures(
                    new_features)
                self.logger.info_msg(
                    __name__,
                    QCoreApplication.translate(
                        "RightOfWay",
                        "{} out of {} records were saved into {}! {} out of {} records already existed in the database."
                    ).format(len(new_features), len(id_pairs),
                             db.names.COL_UE_BAUNIT_T,
                             len(id_pairs) - len(new_features), len(id_pairs)))

            spatial_join_layer = processing.run(
                "qgis:joinattributesbylocation", {
                    'INPUT':
                    layers[db.names.LC_PLOT_T],
                    'JOIN':
                    QgsProcessingFeatureSourceDefinition(
                        layers[db.names.LC_RIGHT_OF_WAY_T].id(), True),
                    'PREDICATE': [0],
                    'JOIN_FIELDS': [db.names.T_ID_F],
                    'METHOD':
                    0,
                    'DISCARD_NONMATCHING':
                    True,
                    'PREFIX':
                    '',
                    'OUTPUT':
                    'memory:'
                })['OUTPUT']

            restriction_features = layers[
                db.names.LC_RESTRICTION_T].getFeatures()
            existing_restriction_pairs = [
                (restriction_feature[db.names.COL_BAUNIT_RRR_T_UNIT_F],
                 restriction_feature[db.names.COL_RRR_T_DESCRIPTION_F])
                for restriction_feature in restriction_features
            ]
            existing_restriction_pairs = set(existing_restriction_pairs)
            id_pairs_restriction = list()
            plot_ids = spatial_join_layer.getFeatures()

            for plot in plot_ids:
                exp = "\"uebaunit\" = {plot}".format(
                    uebaunit=db.names.COL_UE_BAUNIT_T_LC_PLOT_F,
                    plot=plot.attribute(db.names.T_ID_F))
                parcels = layers[db.names.COL_UE_BAUNIT_T].getFeatures(exp)
                for parcel in parcels:
                    id_pair_restriction = (parcel.attribute(
                        db.names.COL_UE_BAUNIT_T_PARCEL_F),
                                           QCoreApplication.translate(
                                               "RightOfWay", "Right of way"))
                    id_pairs_restriction.append(id_pair_restriction)

            new_restriction_features = list()
            if id_pairs_restriction:
                for id_pair in id_pairs_restriction:
                    if not id_pair in existing_restriction_pairs:
                        #Create feature
                        new_feature = QgsVectorLayerUtils().createFeature(
                            layers[db.names.LC_RESTRICTION_T])
                        new_feature.setAttribute(
                            db.names.COL_BAUNIT_RRR_T_UNIT_F, id_pair[0])
                        new_feature.setAttribute(
                            db.names.COL_RRR_T_DESCRIPTION_F, id_pair[1])
                        new_feature.setAttribute(
                            db.names.LC_RESTRICTION_T_TYPE_F,
                            restriction_right_of_way_t_id)
                        self.logger.info(
                            __name__, "Saving RightOfWay-Parcel: {}-{}".format(
                                id_pair[1], id_pair[0]))
                        new_restriction_features.append(new_feature)

                layers[db.names.LC_RESTRICTION_T].dataProvider().addFeatures(
                    new_restriction_features)
                self.logger.info_msg(
                    __name__,
                    QCoreApplication.translate(
                        "RightOfWay",
                        "{} out of {} records were saved into {}! {} out of {} records already existed in the database."
                    ).format(
                        len(new_restriction_features),
                        len(id_pairs_restriction), db.names.LC_RESTRICTION_T,
                        len(id_pairs_restriction) -
                        len(new_restriction_features),
                        len(id_pairs_restriction)))

            administrative_source_ids = [
                f[db.names.T_ID_F] for f in layers[
                    db.names.LC_ADMINISTRATIVE_SOURCE_T].selectedFeatures()
            ]

            source_relation_features = layers[
                db.names.COL_RRR_SOURCE_T].getFeatures()

            existing_source_pairs = [
                (source_relation_feature[db.names.COL_RRR_SOURCE_T_SOURCE_F],
                 source_relation_feature[
                     db.names.COL_RRR_SOURCE_T_LC_RESTRICTION_F])
                for source_relation_feature in source_relation_features
            ]
            existing_source_pairs = set(existing_source_pairs)

            rrr_source_relation_pairs = list()

            for administrative_source_id in administrative_source_ids:
                for restriction_feature in new_restriction_features:
                    rrr_source_relation_pair = (administrative_source_id,
                                                restriction_feature.attribute(
                                                    db.names.T_ID_F))
                    rrr_source_relation_pairs.append(rrr_source_relation_pair)

            new_rrr_source_relation_features = list()
            if rrr_source_relation_pairs:
                for id_pair in rrr_source_relation_pairs:
                    if not id_pair in existing_source_pairs:
                        new_feature = QgsVectorLayerUtils().createFeature(
                            layers[db.names.COL_RRR_SOURCE_T])
                        new_feature.setAttribute(
                            db.names.COL_RRR_SOURCE_T_SOURCE_F, id_pair[0])
                        new_feature.setAttribute(
                            db.names.COL_RRR_SOURCE_T_LC_RESTRICTION_F,
                            id_pair[1])
                        self.logger.info(
                            __name__,
                            "Saving Restriction-Source: {}-{}".format(
                                id_pair[1], id_pair[0]))
                        new_rrr_source_relation_features.append(new_feature)

                layers[db.names.COL_RRR_SOURCE_T].dataProvider().addFeatures(
                    new_rrr_source_relation_features)
                self.logger.info_msg(
                    __name__,
                    QCoreApplication.translate(
                        "RightOfWay",
                        "{} out of {} records were saved into {}! {} out of {} records already existed in the database."
                    ).format(
                        len(new_rrr_source_relation_features),
                        len(rrr_source_relation_pairs),
                        db.names.COL_RRR_SOURCE_T,
                        len(rrr_source_relation_pairs) -
                        len(new_rrr_source_relation_features),
                        len(rrr_source_relation_pairs)))
Beispiel #25
0
    def finish_spatial_source(self, feature_ids_dict, layerId, features):
        if len(features) != 1:
            self.log.logMessage(
                "We should have got only one spatial source... We cannot do anything with {} spatial sources"
                .format(len(features)), PLUGIN_NAME, Qgis.Warning)
        else:
            feature = features[0]
            if not feature.isValid():
                self.log.logMessage(
                    "Feature not found in layer Spatial Source...",
                    PLUGIN_NAME, Qgis.Warning)
            else:
                spatial_source_id = feature[ID_FIELD]
                all_new_features = list()

                # Fill association table, depending on the case
                new_features = list()
                if PLOT_TABLE in feature_ids_dict:
                    # Fill uesource table
                    for plot_id in feature_ids_dict[PLOT_TABLE]:
                        new_feature = QgsVectorLayerUtils().createFeature(
                            self._uesource_table)
                        new_feature.setAttribute(UESOURCE_TABLE_PLOT_FIELD,
                                                 plot_id)
                        new_feature.setAttribute(UESOURCE_TABLE_SOURCE_FIELD,
                                                 spatial_source_id)
                        self.log.logMessage(
                            "Saving Plot-SpatialSource: {}-{}".format(
                                plot_id, spatial_source_id), PLUGIN_NAME,
                            Qgis.Info)
                        new_features.append(new_feature)

                    self._uesource_table.dataProvider().addFeatures(
                        new_features)
                    all_new_features.extend(new_feature)

                new_features = list()
                if BOUNDARY_TABLE in feature_ids_dict:
                    # Fill cclsource table
                    for boundary_id in feature_ids_dict[BOUNDARY_TABLE]:
                        new_feature = QgsVectorLayerUtils().createFeature(
                            self._cclsource_table)
                        new_feature.setAttribute(
                            CCLSOURCE_TABLE_BOUNDARY_FIELD, boundary_id)
                        new_feature.setAttribute(CCLSOURCE_TABLE_SOURCE_FIELD,
                                                 spatial_source_id)
                        self.log.logMessage(
                            "Saving Boundary-SpatialSource: {}-{}".format(
                                boundary_id, spatial_source_id), PLUGIN_NAME,
                            Qgis.Info)
                        new_features.append(new_feature)

                    self._cclsource_table.dataProvider().addFeatures(
                        new_features)
                    all_new_features.extend(new_feature)

                new_features = list()
                if BOUNDARY_POINT_TABLE in feature_ids_dict:
                    for boundary_point_id in feature_ids_dict[
                            BOUNDARY_POINT_TABLE]:
                        new_feature = QgsVectorLayerUtils().createFeature(
                            self._pointsource_table)
                        new_feature.setAttribute(
                            POINTSOURCE_TABLE_BOUNDARYPOINT_FIELD,
                            boundary_point_id)
                        new_feature.setAttribute(
                            POINTSOURCE_TABLE_SOURCE_FIELD, spatial_source_id)
                        self.log.logMessage(
                            "Saving BoundaryPoint-SpatialSource: {}-{}".format(
                                boundary_point_id, spatial_source_id),
                            PLUGIN_NAME, Qgis.Info)
                        new_features.append(new_feature)

                    self._pointsource_table.dataProvider().addFeatures(
                        new_features)
                    all_new_features.extend(new_feature)

                new_features = list()
                if SURVEY_POINT_TABLE in feature_ids_dict:
                    for survey_point_id in feature_ids_dict[
                            SURVEY_POINT_TABLE]:
                        new_feature = QgsVectorLayerUtils().createFeature(
                            self._pointsource_table)
                        new_feature.setAttribute(
                            POINTSOURCE_TABLE_SURVEYPOINT_FIELD,
                            survey_point_id)
                        new_feature.setAttribute(
                            POINTSOURCE_TABLE_SOURCE_FIELD, spatial_source_id)
                        self.log.logMessage(
                            "Saving SurveyPoint-SpatialSource: {}-{}".format(
                                survey_point_id, spatial_source_id),
                            PLUGIN_NAME, Qgis.Info)
                        new_features.append(new_feature)

                    self._pointsource_table.dataProvider().addFeatures(
                        new_features)
                    all_new_features.extend(new_feature)

                new_features = list()
                if CONTROL_POINT_TABLE in feature_ids_dict:
                    for control_point_id in feature_ids_dict[
                            CONTROL_POINT_TABLE]:
                        new_feature = QgsVectorLayerUtils().createFeature(
                            self._pointsource_table)
                        new_feature.setAttribute(
                            POINTSOURCE_TABLE_CONTROLPOINT_FIELD,
                            control_point_id)
                        new_feature.setAttribute(
                            POINTSOURCE_TABLE_SOURCE_FIELD, spatial_source_id)
                        self.log.logMessage(
                            "Saving ControlPoint-SpatialSource: {}-{}".format(
                                control_point_id, spatial_source_id),
                            PLUGIN_NAME, Qgis.Info)
                        new_features.append(new_feature)

                    self._pointsource_table.dataProvider().addFeatures(
                        new_features)
                    all_new_features.extend(new_feature)

                if all_new_features:
                    self.iface.messageBar().pushMessage(
                        "Asistente LADM_COL",
                        QCoreApplication.translate(
                            "CreateSpatialSourceCadastreWizard",
                            "The new spatial source (t_id={}) was successfully created and associated with the following features: {}"
                        ).format(spatial_source_id, feature_ids_dict),
                        Qgis.Info, 30)

        self._spatial_source_layer.committedFeaturesAdded.disconnect()
        self.log.logMessage(
            "Spatial Source's committedFeaturesAdded SIGNAL disconnected",
            PLUGIN_NAME, Qgis.Info)
Beispiel #26
0
    def finish_parcel(self, layerId, features):

        if len(features) != 1:
            self.log.logMessage(
                "We should have got only one predio... We cannot do anything with {} predios"
                .format(len(features)), PLUGIN_NAME, Qgis.Warning)
        else:
            fid = features[0].id()

            if not self._layers[PARCEL_TABLE]['layer'].getFeature(
                    fid).isValid():
                self.log.logMessage("Feature not found in layer Predio...",
                                    PLUGIN_NAME, Qgis.Warning)
            else:
                parcel_id = self._layers[PARCEL_TABLE]['layer'].getFeature(
                    fid)[ID_FIELD]

                plot_ids = list()
                building_ids = list()
                building_unit_ids = list()

                # Apply restriction to the selection
                if PLOT_TABLE in CONSTRAINT_TYPES_OF_PARCEL[
                        self.cb_parcel_type.currentText()]:
                    if CONSTRAINT_TYPES_OF_PARCEL[
                            self.cb_parcel_type.currentText(
                            )][PLOT_TABLE] is not None:
                        plot_ids = [
                            f[ID_FIELD] for f in self._layers[PLOT_TABLE]
                            ['layer'].selectedFeatures()
                        ]
                else:
                    plot_ids = [
                        f[ID_FIELD] for f in self._layers[PLOT_TABLE]
                        ['layer'].selectedFeatures()
                    ]

                if BUILDING_TABLE in CONSTRAINT_TYPES_OF_PARCEL[
                        self.cb_parcel_type.currentText()]:
                    if CONSTRAINT_TYPES_OF_PARCEL[
                            self.cb_parcel_type.currentText(
                            )][BUILDING_TABLE] is not None:
                        building_ids = [
                            f[ID_FIELD] for f in self._layers[BUILDING_TABLE]
                            ['layer'].selectedFeatures()
                        ]
                else:
                    building_ids = [
                        f[ID_FIELD] for f in self._layers[BUILDING_TABLE]
                        ['layer'].selectedFeatures()
                    ]

                if BUILDING_UNIT_TABLE in CONSTRAINT_TYPES_OF_PARCEL[
                        self.cb_parcel_type.currentText()]:
                    if CONSTRAINT_TYPES_OF_PARCEL[
                            self.cb_parcel_type.currentText(
                            )][BUILDING_UNIT_TABLE] is not None:
                        building_unit_ids = [
                            f[ID_FIELD]
                            for f in self._layers[BUILDING_UNIT_TABLE]
                            ['layer'].selectedFeatures()
                        ]
                else:
                    building_unit_ids = [
                        f[ID_FIELD] for f in self._layers[BUILDING_UNIT_TABLE]
                        ['layer'].selectedFeatures()
                    ]

                # Fill uebaunit table
                new_features = []
                for plot_id in plot_ids:
                    new_feature = QgsVectorLayerUtils().createFeature(
                        self._layers[UEBAUNIT_TABLE]['layer'])
                    new_feature.setAttribute(UEBAUNIT_TABLE_PLOT_FIELD,
                                             plot_id)
                    new_feature.setAttribute(UEBAUNIT_TABLE_PARCEL_FIELD,
                                             parcel_id)
                    self.log.logMessage(
                        "Saving Plot-Parcel: {}-{}".format(plot_id, parcel_id),
                        PLUGIN_NAME, Qgis.Info)
                    new_features.append(new_feature)

                for building_id in building_ids:
                    new_feature = QgsVectorLayerUtils().createFeature(
                        self._layers[UEBAUNIT_TABLE]['layer'])
                    new_feature.setAttribute(UEBAUNIT_TABLE_BUILDING_FIELD,
                                             building_id)
                    new_feature.setAttribute(UEBAUNIT_TABLE_PARCEL_FIELD,
                                             parcel_id)
                    self.log.logMessage(
                        "Saving Building-Parcel: {}-{}".format(
                            building_id, parcel_id), PLUGIN_NAME, Qgis.Info)
                    new_features.append(new_feature)

                for building_unit_id in building_unit_ids:
                    new_feature = QgsVectorLayerUtils().createFeature(
                        self._layers[UEBAUNIT_TABLE]['layer'])
                    new_feature.setAttribute(
                        UEBAUNIT_TABLE_BUILDING_UNIT_FIELD, building_unit_id)
                    new_feature.setAttribute(UEBAUNIT_TABLE_PARCEL_FIELD,
                                             parcel_id)
                    self.log.logMessage(
                        "Saving Building Unit-Parcel: {}-{}".format(
                            building_unit_id, parcel_id), PLUGIN_NAME,
                        Qgis.Info)
                    new_features.append(new_feature)

                self._layers[UEBAUNIT_TABLE]['layer'].dataProvider(
                ).addFeatures(new_features)

                if plot_ids and building_ids and building_unit_ids:
                    self.iface.messageBar().pushMessage(
                        "Asistente LADM_COL",
                        QCoreApplication.translate(
                            "CreateParcelCadastreWizard",
                            "The new parcel (t_id={}) was successfully created and associated with its corresponding Plot (t_id={}) and Building(s) (t_id={}) and Building Unit(s) (t_id={})!"
                        ).format(
                            parcel_id, ", ".join([str(b) for b in plot_ids]),
                            ", ".join([str(b) for b in building_ids]),
                            ", ".join([str(b) for b in building_unit_ids])),
                        Qgis.Info)
                elif plot_ids and building_ids and not building_unit_ids:
                    self.iface.messageBar().pushMessage(
                        "Asistente LADM_COL",
                        QCoreApplication.translate(
                            "CreateParcelCadastreWizard",
                            "The new parcel (t_id={}) was successfully created and associated with its corresponding Plot (t_id={}) and Building(s) (t_id={})!"
                        ).format(parcel_id,
                                 ", ".join([str(b) for b in plot_ids]),
                                 ", ".join([str(b) for b in building_ids])),
                        Qgis.Info)
                elif plot_ids and not building_ids and building_unit_ids:
                    self.iface.messageBar().pushMessage(
                        "Asistente LADM_COL",
                        QCoreApplication.translate(
                            "CreateParcelCadastreWizard",
                            "The new parcel (t_id={}) was successfully created and associated with its corresponding Plot (t_id={}) and Building Unit(s) (t_id={})!"
                        ).format(
                            parcel_id, ", ".join([str(b) for b in plot_ids]),
                            ", ".join([str(b) for b in building_unit_ids])),
                        Qgis.Info)
                elif plot_ids and not building_ids and not building_unit_ids:
                    self.iface.messageBar().pushMessage(
                        "Asistente LADM_COL",
                        QCoreApplication.translate(
                            "CreateParcelCadastreWizard",
                            "The new parcel (t_id={}) was successfully created and associated with its corresponding Plot (t_id={})!"
                        ).format(parcel_id,
                                 ", ".join([str(b) for b in plot_ids])),
                        Qgis.Info)
                elif not plot_ids and building_ids and not building_unit_ids:
                    self.iface.messageBar().pushMessage(
                        "Asistente LADM_COL",
                        QCoreApplication.translate(
                            "CreateParcelCadastreWizard",
                            "The new parcel (t_id={}) was successfully created and associated with its corresponding Building(s) (t_id={})!"
                        ).format(parcel_id,
                                 ", ".join([str(b) for b in building_ids])),
                        Qgis.Info)
                elif not plot_ids and building_ids and building_unit_ids:
                    self.iface.messageBar().pushMessage(
                        "Asistente LADM_COL",
                        QCoreApplication.translate(
                            "CreateParcelCadastreWizard",
                            "The new parcel (t_id={}) was successfully created and associated with its corresponding Building(s) (t_id={}) and Building Unit(s) (t_id={})!"
                        ).format(
                            parcel_id,
                            ", ".join([str(b) for b in building_ids]),
                            ", ".join([str(b) for b in building_unit_ids])),
                        Qgis.Info)
                elif not plot_ids and not building_ids and building_unit_ids:
                    self.iface.messageBar().pushMessage(
                        "Asistente LADM_COL",
                        QCoreApplication.translate(
                            "CreateParcelCadastreWizard",
                            "The new parcel (t_id={}) was successfully created and associated with its corresponding Building Unit(s) (t_id={})!"
                        ).format(
                            parcel_id,
                            ", ".join([str(b) for b in building_unit_ids])),
                        Qgis.Info)

        self._layers[PARCEL_TABLE]['layer'].committedFeaturesAdded.disconnect(
            self.finish_parcel)
        self.log.logMessage(
            "Parcel's committedFeaturesAdded SIGNAL disconnected", PLUGIN_NAME,
            Qgis.Info)
        self.close_wizard()
Beispiel #27
0
    def fill_topology_tables_morebfs_less(self, db, use_selection=True):
        layers = {
            db.names.LC_PLOT_T: None,
            db.names.MORE_BFS_T: None,
            db.names.LESS_BFS_T: None,
            db.names.LC_BOUNDARY_T: None
        }

        self.app.core.get_layers(db, layers, load=True)
        if not layers:
            return None

        if use_selection:
            if layers[db.names.LC_PLOT_T].selectedFeatureCount() == 0:
                if self.app.core.get_ladm_layer_from_qgis(
                        db, db.names.LC_PLOT_T,
                        EnumLayerRegistryType.IN_LAYER_TREE) is None:
                    self.logger.message_with_button_load_layer_emitted.emit(
                        QCoreApplication.translate(
                            "ToolBar",
                            "First load the layer {} into QGIS and select at least one plot!"
                        ).format(db.names.LC_PLOT_T),
                        QCoreApplication.translate("ToolBar",
                                                   "Load layer {} now").format(
                                                       db.names.LC_PLOT_T),
                        db.names.LC_PLOT_T, Qgis.Warning)
                else:
                    reply = QMessageBox.question(
                        None,
                        QCoreApplication.translate("ToolBar", "Continue?"),
                        QCoreApplication.translate(
                            "ToolBar",
                            "There are no selected plots. Do you want to fill the '{more}' and '{less}' tables for all the {all} plots in the database?"
                        ).format(
                            more=db.names.MORE_BFS_T,
                            less=db.names.LESS_BFS_T,
                            all=layers[db.names.LC_PLOT_T].featureCount()),
                        QMessageBox.Yes | QMessageBox.Cancel,
                        QMessageBox.Cancel)
                    if reply == QMessageBox.Yes:
                        use_selection = False
                    elif reply == QMessageBox.Cancel:
                        self.logger.warning_msg(
                            __name__,
                            QCoreApplication.translate(
                                "ToolBar", "First select at least one plot!"))
                        return
            else:
                reply = QMessageBox.question(
                    None, QCoreApplication.translate("ToolBar", "Continue?"),
                    QCoreApplication.translate(
                        "ToolBar",
                        "There are {selected} plots selected. Do you want to fill the '{more}' and '{less}' tables just for the selected plots?\n\nIf you say 'No', the '{more}' and '{less}' tables will be filled for all plots in the database."
                    ).format(selected=layers[
                        db.names.LC_PLOT_T].selectedFeatureCount(),
                             more=db.names.MORE_BFS_T,
                             less=db.names.LESS_BFS_T),
                    QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
                    QMessageBox.Cancel)
                if reply == QMessageBox.Yes:
                    use_selection = True
                elif reply == QMessageBox.No:
                    use_selection = False
                elif reply == QMessageBox.Cancel:
                    return

        tolerance = self.app.settings.tolerance
        if tolerance:
            # We need to adjust input layers to take tolerance into account
            # Use the same configuration we use in quality rule 3004 (Plots should be covered by boundaries).
            layers[db.names.LC_PLOT_T] = self.app.core.adjust_layer(
                layers[db.names.LC_PLOT_T], layers[db.names.LC_PLOT_T],
                tolerance, True, use_selection)
            layers[db.names.LC_BOUNDARY_T] = self.app.core.adjust_layer(
                layers[db.names.LC_BOUNDARY_T], layers[db.names.LC_PLOT_T],
                tolerance, True)
            if use_selection:
                layers[db.names.LC_PLOT_T].selectAll(
                )  # Because this layer is already filtered by selected features

        # Get unique pairs id_boundary-id_plot in both tables
        existing_more_pairs = set([
            (more_bfs_feature[db.names.MORE_BFS_T_LC_PLOT_F],
             more_bfs_feature[db.names.MORE_BFS_T_LC_BOUNDARY_F])
            for more_bfs_feature in layers[db.names.MORE_BFS_T].getFeatures()
        ])
        existing_less_pairs = set([
            (less_feature[db.names.LESS_BFS_T_LC_PLOT_F],
             less_feature[db.names.LESS_BFS_T_LC_BOUNDARY_F])
            for less_feature in layers[db.names.LESS_BFS_T].getFeatures()
        ])

        id_more_pairs, id_less_pairs = self.geometry.get_pair_boundary_plot(
            layers[db.names.LC_BOUNDARY_T],
            layers[db.names.LC_PLOT_T],
            db.names.T_ID_F,
            use_selection=use_selection)
        if id_less_pairs:
            layers[db.names.LESS_BFS_T].startEditing()
            features = list()
            for id_pair in id_less_pairs:
                if not id_pair in existing_less_pairs:  # Avoid duplicated pairs in the DB
                    # Create feature
                    feature = QgsVectorLayerUtils().createFeature(
                        layers[db.names.LESS_BFS_T])
                    feature.setAttribute(db.names.LESS_BFS_T_LC_PLOT_F,
                                         id_pair[0])
                    feature.setAttribute(db.names.LESS_BFS_T_LC_BOUNDARY_F,
                                         id_pair[1])
                    features.append(feature)
            layers[db.names.LESS_BFS_T].addFeatures(features)
            layers[db.names.LESS_BFS_T].commitChanges()
            self.logger.info_msg(
                __name__,
                QCoreApplication.translate(
                    "ToolBar",
                    "{} out of {} records were saved into '{}'! {} out of {} records already existed in the database."
                ).format(len(features), len(id_less_pairs),
                         db.names.LESS_BFS_T,
                         len(id_less_pairs) - len(features),
                         len(id_less_pairs)))
        else:
            self.logger.info_msg(
                __name__,
                QCoreApplication.translate(
                    "ToolBar",
                    "No pairs id_boundary-id_plot found for '{}' table.").
                format(db.names.LESS_BFS_T))

        if id_more_pairs:
            layers[db.names.MORE_BFS_T].startEditing()
            features = list()
            for id_pair in id_more_pairs:
                if not id_pair in existing_more_pairs:  # Avoid duplicated pairs in the DB
                    # Create feature
                    feature = QgsVectorLayerUtils().createFeature(
                        layers[db.names.MORE_BFS_T])
                    feature.setAttribute(db.names.MORE_BFS_T_LC_PLOT_F,
                                         id_pair[0])
                    feature.setAttribute(db.names.MORE_BFS_T_LC_BOUNDARY_F,
                                         id_pair[1])
                    features.append(feature)
            layers[db.names.MORE_BFS_T].addFeatures(features)
            layers[db.names.MORE_BFS_T].commitChanges()
            self.logger.info_msg(
                __name__,
                QCoreApplication.translate(
                    "ToolBar",
                    "{} out of {} records were saved into '{}'! {} out of {} records already existed in the database."
                ).format(len(features), len(id_more_pairs),
                         db.names.MORE_BFS_T,
                         len(id_more_pairs) - len(features),
                         len(id_more_pairs)))
        else:
            self.logger.info_msg(
                __name__,
                QCoreApplication.translate(
                    "ToolBar",
                    "No pairs id_boundary-id_plot found for '{}' table.").
                format(db.names.MORE_BFS_T))
    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()
            administrative_source_ids = [
                f[self.names.T_ID_F]
                for f in self._layers[self.names.OP_ADMINISTRATIVE_SOURCE_T]
                [LAYER].selectedFeatures()
            ]

            if not self._layers[self.EDITING_LAYER_NAME][LAYER].getFeature(
                    fid).isValid():
                self.logger.warning(
                    __name__, "Feature not found in layer {}...".format(
                        self.EDITING_LAYER_NAME))
            else:
                # feature_rrr_id: generic name used for represent id for right, restriction
                feature_rrr_id = self._layers[self.EDITING_LAYER_NAME][
                    LAYER].getFeature(fid)[self.names.T_ID_F]

                # Fill rrrfuente table
                new_features = []
                for administrative_source_id in administrative_source_ids:
                    new_feature = QgsVectorLayerUtils().createFeature(
                        self._layers[self.names.COL_RRR_SOURCE_T][LAYER])

                    new_feature.setAttribute(
                        self.names.COL_RRR_SOURCE_T_SOURCE_F,
                        administrative_source_id)
                    if self.EDITING_LAYER_NAME == self.names.OP_RIGHT_T:
                        new_feature.setAttribute(
                            self.names.COL_RRR_SOURCE_T_OP_RIGHT_F,
                            feature_rrr_id)
                    elif self.EDITING_LAYER_NAME == self.names.OP_RESTRICTION_T:
                        new_feature.setAttribute(
                            self.names.COL_RRR_SOURCE_T_OP_RESTRICTION_F,
                            feature_rrr_id)

                    self.logger.info(
                        __name__,
                        "Saving Administrative_source-{}: {}-{}".format(
                            self.WIZARD_FEATURE_NAME, administrative_source_id,
                            feature_rrr_id))
                    new_features.append(new_feature)

                self._layers[self.names.COL_RRR_SOURCE_T][LAYER].dataProvider(
                ).addFeatures(new_features)
                message = QCoreApplication.translate(
                    "WizardTranslations",
                    "The new {} (t_id={}) was successfully created and associated with its corresponding administrative source (t_id={})!"
                ).format(
                    self.WIZARD_FEATURE_NAME, feature_rrr_id,
                    ", ".join([str(b) for b in administrative_source_ids]))

        return message
    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:
            feature = features[0]
            feature_ids_dict = dict()

            if self._layers[self.names.LC_PLOT_T] is not None:
                if self._layers[
                        self.names.LC_PLOT_T].selectedFeatureCount() > 0:
                    feature_ids_dict[self.names.LC_PLOT_T] = [
                        f[self.names.T_ID_F] for f in self._layers[
                            self.names.LC_PLOT_T].selectedFeatures()
                    ]

            if self._layers[self.names.LC_BOUNDARY_T] is not None:
                if self._layers[
                        self.names.LC_BOUNDARY_T].selectedFeatureCount() > 0:
                    feature_ids_dict[self.names.LC_BOUNDARY_T] = [
                        f[self.names.T_ID_F] for f in self._layers[
                            self.names.LC_BOUNDARY_T].selectedFeatures()
                    ]

            if self._layers[self.names.LC_BOUNDARY_POINT_T] is not None:
                if self._layers[
                        self.names.LC_BOUNDARY_POINT_T].selectedFeatureCount(
                        ) > 0:
                    feature_ids_dict[self.names.LC_BOUNDARY_POINT_T] = [
                        f[self.names.T_ID_F] for f in self._layers[
                            self.names.LC_BOUNDARY_POINT_T].selectedFeatures()
                    ]

            if self._layers[self.names.LC_SURVEY_POINT_T] is not None:
                if self._layers[self.names.
                                LC_SURVEY_POINT_T].selectedFeatureCount() > 0:
                    feature_ids_dict[self.names.LC_SURVEY_POINT_T] = [
                        f[self.names.T_ID_F] for f in self._layers[
                            self.names.LC_SURVEY_POINT_T].selectedFeatures()
                    ]

            if self._layers[self.names.LC_CONTROL_POINT_T] is not None:
                if self._layers[self.names.
                                LC_CONTROL_POINT_T].selectedFeatureCount() > 0:
                    feature_ids_dict[self.names.LC_CONTROL_POINT_T] = [
                        f[self.names.T_ID_F] for f in self._layers[
                            self.names.LC_CONTROL_POINT_T].selectedFeatures()
                    ]

            if not feature.isValid():
                self.logger.warning(
                    __name__, "Feature not found in layer Spatial Source...")
            else:
                spatial_source_id = feature[self.names.T_ID_F]
                all_new_features = list()

                # Fill association table, depending on the case
                new_features = list()
                if self.names.LC_PLOT_T in feature_ids_dict:
                    # Fill uesource table
                    for plot_id in feature_ids_dict[self.names.LC_PLOT_T]:
                        new_feature = QgsVectorLayerUtils().createFeature(
                            self._layers[self.names.COL_UE_SOURCE_T])
                        new_feature.setAttribute(
                            self.names.COL_UE_SOURCE_T_LC_PLOT_F, plot_id)
                        new_feature.setAttribute(
                            self.names.COL_UE_SOURCE_T_SOURCE_F,
                            spatial_source_id)
                        self.logger.info(
                            __name__,
                            "Saving Plot-SpatialSource: {}-{}".format(
                                plot_id, spatial_source_id))
                        new_features.append(new_feature)

                    self._layers[self.names.COL_UE_SOURCE_T].dataProvider(
                    ).addFeatures(new_features)
                    all_new_features.extend(new_feature)

                new_features = list()
                if self.names.LC_BOUNDARY_T in feature_ids_dict:
                    # Fill cclsource table
                    for boundary_id in feature_ids_dict[
                            self.names.LC_BOUNDARY_T]:
                        new_feature = QgsVectorLayerUtils().createFeature(
                            self._layers[self.names.COL_CCL_SOURCE_T])

                        # Todo: Update when ili2db issue is solved.
                        # Todo: When an abstract class only implements a concrete class, the name of the attribute is different if two or more classes are implemented.
                        new_feature.setAttribute(
                            self.names.COL_CCL_SOURCE_T_BOUNDARY_F,
                            boundary_id)
                        new_feature.setAttribute(
                            self.names.COL_CCL_SOURCE_T_SOURCE_F,
                            spatial_source_id)
                        self.logger.info(
                            __name__,
                            "Saving Boundary-SpatialSource: {}-{}".format(
                                boundary_id, spatial_source_id))
                        new_features.append(new_feature)

                    self._layers[self.names.COL_CCL_SOURCE_T].dataProvider(
                    ).addFeatures(new_features)
                    all_new_features.extend(new_feature)

                new_features = list()
                if self.names.LC_BOUNDARY_POINT_T in feature_ids_dict:
                    for boundary_point_id in feature_ids_dict[
                            self.names.LC_BOUNDARY_POINT_T]:
                        new_feature = QgsVectorLayerUtils().createFeature(
                            self._layers[self.names.COL_POINT_SOURCE_T])
                        new_feature.setAttribute(
                            self.names.COL_POINT_SOURCE_T_LC_BOUNDARY_POINT_F,
                            boundary_point_id)
                        new_feature.setAttribute(
                            self.names.COL_POINT_SOURCE_T_SOURCE_F,
                            spatial_source_id)
                        self.logger.info(
                            __name__,
                            "Saving BoundaryPoint-SpatialSource: {}-{}".format(
                                boundary_point_id, spatial_source_id))
                        new_features.append(new_feature)

                    self._layers[self.names.COL_POINT_SOURCE_T].dataProvider(
                    ).addFeatures(new_features)
                    all_new_features.extend(new_feature)

                new_features = list()
                if self.names.LC_SURVEY_POINT_T in feature_ids_dict:
                    for survey_point_id in feature_ids_dict[
                            self.names.LC_SURVEY_POINT_T]:
                        new_feature = QgsVectorLayerUtils().createFeature(
                            self._layers[self.names.COL_POINT_SOURCE_T])
                        new_feature.setAttribute(
                            self.names.COL_POINT_SOURCE_T_LC_SURVEY_POINT_F,
                            survey_point_id)
                        new_feature.setAttribute(
                            self.names.COL_POINT_SOURCE_T_SOURCE_F,
                            spatial_source_id)
                        self.logger.info(
                            __name__,
                            "Saving SurveyPoint-SpatialSource: {}-{}".format(
                                survey_point_id, spatial_source_id))
                        new_features.append(new_feature)

                    self._layers[self.names.COL_POINT_SOURCE_T].dataProvider(
                    ).addFeatures(new_features)
                    all_new_features.extend(new_feature)

                new_features = list()
                if self.names.LC_CONTROL_POINT_T in feature_ids_dict:
                    for control_point_id in feature_ids_dict[
                            self.names.LC_CONTROL_POINT_T]:
                        new_feature = QgsVectorLayerUtils().createFeature(
                            self._layers[self.names.COL_POINT_SOURCE_T])
                        new_feature.setAttribute(
                            self.names.COL_POINT_SOURCE_T_LC_CONTROL_POINT_F,
                            control_point_id)
                        new_feature.setAttribute(
                            self.names.COL_POINT_SOURCE_T_SOURCE_F,
                            spatial_source_id)
                        self.logger.info(
                            __name__,
                            "Saving ControlPoint-SpatialSource: {}-{}".format(
                                control_point_id, spatial_source_id))
                        new_features.append(new_feature)

                    self._layers[self.names.COL_POINT_SOURCE_T].dataProvider(
                    ).addFeatures(new_features)
                    all_new_features.extend(new_feature)

                if all_new_features:
                    message = QCoreApplication.translate(
                        "WizardTranslations",
                        "The new spatial source (t_id={}) was successfully created and associated with the following features: {}"
                    ).format(spatial_source_id, feature_ids_dict)
                else:
                    message = QCoreApplication.translate(
                        "WizardTranslations",
                        "The new spatial source (t_id={}) was successfully created and it wasn't associated with a spatial unit"
                    ).format(spatial_source_id)

        return message