Exemplo n.º 1
0
 def __init__(self, *args, **kwargs):
     #Use a different pixmap
     px = QPixmap(':/plugins/stdm/images/icons/code.png')
     kwargs['pixmap'] = px
     self._code = None
     self._current_profile = current_profile()
     self._admin_hierarchy_code = None
     ForeignKeyLineEdit.__init__(self, *args, **kwargs)
     self.code_generator = CodeGenerator(self.entity, self.column)
Exemplo n.º 2
0
    def __init__(self, *args, **kwargs):
        # Use a different pixmap
        px = GuiUtils.get_icon_pixmap('code.png')
        kwargs['pixmap'] = px

        self._code = None
        self._current_profile = current_profile()
        self._admin_hierarchy_code = None

        ForeignKeyLineEdit.__init__(self, *args, **kwargs)
        self.code_generator = CodeGenerator(self.entity, self.column)
        self.code_columns = code_columns(self.entity, self.column.name)
        self.setText('')
Exemplo n.º 3
0
    def __init__(self, *args, **kwargs):
        # Use a different pixmap
        px = QPixmap(':/plugins/stdm/images/icons/code.png')
        kwargs['pixmap'] = px

        self._code = None
        self._current_profile = current_profile()
        self._admin_hierarchy_code = None

        ForeignKeyLineEdit.__init__(self, *args, **kwargs)
        self.code_generator = CodeGenerator(self.entity, self.column)
        self.code_columns = code_columns(self.entity, self.column.name)
        self.setText('')
Exemplo n.º 4
0
class AutoGeneratedLineEdit(ForeignKeyLineEdit):
    """
    Custom implementation for selecting and displaying administrative areas
    using the name and corresponding code.
    """
    def __init__(self, *args, **kwargs):
        #Use a different pixmap
        px = QPixmap(':/plugins/stdm/images/icons/code.png')
        kwargs['pixmap'] = px
        self._code = None
        self._current_profile = current_profile()
        self._admin_hierarchy_code = None
        ForeignKeyLineEdit.__init__(self, *args, **kwargs)
        self.code_generator = CodeGenerator(self.entity, self.column)

    def format_display(self):
        try:
            self.setText(self._code)
        except RuntimeError:
            QMessageBox.warning(
                None,
                QApplication.translate('AutoGeneratedLineEdit', "Value Error"),
                'The change is not saved. '
                'Please use the form to edit data.')
        except TypeError:
            pass

    def parent_entity_model(self):
        #Use default admin unit model class.
        return AdminSpatialUnitSet

    def _search_current_item_index(self, model, parent_index):
        #Recursively search for model index corresponding to current item
        if self.current_item is None:
            return None

        current_item_idx = None

        if model.hasChildren(parent_index):
            row_count = model.rowCount(parent_index)
            for i in range(row_count):
                #Check value from previous iteration
                if not current_item_idx is None:
                    break

                c_idx = model.index(i, 0, parent_index)
                node = c_idx.internalPointer()
                id = node.data(2)

                #Item found
                if id == self.current_item.id:
                    current_item_idx = c_idx
                    break

                else:
                    #Search children indices
                    current_item_idx = self._search_current_item_index(
                        model, c_idx)

        return current_item_idx

    def _select_current_item(self, model, selection_model, tv):
        #Selects the row corresponding to the current item
        if self._current_item is None:
            return

        root_idx = QModelIndex()
        current_item_idx = self._search_current_item_index(model, root_idx)

        #Expand items at the current item index
        self._expand_parent_indices(current_item_idx, tv)

        #Select item
        selection_model.select(
            current_item_idx,
            QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows)

    def _expand_parent_indices(self, ref_index, tv):
        """
        Expand all parents of ref_index so that the hierarchy is better
        visualized.
        """
        parent_idx = ref_index.parent()
        while parent_idx.isValid():
            tv.expand(parent_idx)
            parent_idx = parent_idx.parent()

    def on_load_foreign_key_browser(self):
        if self.column.prefix_source == self.tr('None'):
            self.set_code_from_no_prefix()

        elif self.column.prefix_source == 'admin_spatial_unit_set':
            self.set_code_from_admin_unit()

        elif self.column.prefix_source == '':
            pass
        else:
            self.set_code_from_lookup()
        self.show_clear_button()

    def set_code_from_lookup(self):
        """
        Creates code from a lookup value code.
        Creates a code containing lookup value code and serial number.
        """
        lookup_selector = LookupValueSelector(iface.mainWindow(),
                                              self.column.prefix_source)
        result = lookup_selector.exec_()

        if result == QDialog.Accepted:
            self.current_item = lookup_selector
            self._code = self.code_generator.generate(
                lookup_selector.selected_code, self.column.separator,
                self.column.leading_zero)
            self.format_display()

    def set_code_from_admin_unit(self):
        """
        Set code from administrative unit. Creates code containing admin
        unit codes and serial number.
        """
        # Show the selector for administrative units
        au_selector = AdminUnitSelector(self.parent())
        au_selector.setManageMode(False)
        item_model = au_selector.adminUnitManager.model()
        selection_model = au_selector.adminUnitManager.selection_model()
        # Highlight previously selected item
        self._select_current_item(item_model, selection_model,
                                  au_selector.adminUnitManager.tvAdminUnits)
        if au_selector.exec_() == QDialog.Accepted:
            self.current_item = au_selector.selectedAdminUnit
            self._admin_hierarchy_code = self.current_item.hierarchyCode(
                self.column.separator)
            self._code = self.code_generator.generate(
                self._admin_hierarchy_code, self.column.separator,
                self.column.leading_zero)
            self.format_display()

    def set_code_from_no_prefix(self):
        """
        Set code from None prefix. Creates a serial number without prefix.
        """
        self.current_item = ''
        # The prefix and separator should be '' for a serial.
        self._code = self.code_generator.generate('', '',
                                                  self.column.leading_zero)
        self._code = self._code[1:]
        self.format_display()
Exemplo n.º 5
0
class AutoGeneratedLineEdit(ForeignKeyLineEdit):
    """
    Custom implementation for selecting and displaying administrative areas
    using the name and corresponding code.
    """
    def __init__(self, *args, **kwargs):
        #Use a different pixmap
        px = QPixmap(':/plugins/stdm/images/icons/code.png')
        kwargs['pixmap'] = px
        self._code = None
        self._current_profile = current_profile()
        self._admin_hierarchy_code = None

        ForeignKeyLineEdit.__init__(self, *args, **kwargs)
        self.code_generator = CodeGenerator(self.entity, self.column)
        self.code_columns = code_columns(self.entity, self.column.name)

    def format_display(self):
        try:
            self.setText(self._code)
        except RuntimeError:
            QMessageBox.warning(
                None,
                QApplication.translate('AutoGeneratedLineEdit', "Value Error"),
                'The change is not saved. '
                'Please use the form to edit data.')
        except TypeError:
            pass

    def parent_entity_model(self):
        #Use default admin unit model class.
        return AdminSpatialUnitSet

    def _search_current_item_index(self, model, parent_index):
        #Recursively search for model index corresponding to current item
        if self.current_item is None:
            return None

        current_item_idx = None

        if model.hasChildren(parent_index):
            row_count = model.rowCount(parent_index)
            for i in range(row_count):
                #Check value from previous iteration
                if not current_item_idx is None:
                    break

                c_idx = model.index(i, 0, parent_index)
                node = c_idx.internalPointer()
                id = node.data(2)

                #Item found
                if id == self.current_item.id:
                    current_item_idx = c_idx
                    break

                else:
                    #Search children indices
                    current_item_idx = self._search_current_item_index(
                        model, c_idx)

        return current_item_idx

    def _select_current_item(self, model, selection_model, tv):
        #Selects the row corresponding to the current item
        if self._current_item is None:
            return

        root_idx = QModelIndex()
        current_item_idx = self._search_current_item_index(model, root_idx)

        #Expand items at the current item index
        self._expand_parent_indices(current_item_idx, tv)

        #Select item
        selection_model.select(
            current_item_idx,
            QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows)

    def _expand_parent_indices(self, ref_index, tv):
        """
        Expand all parents of ref_index so that the hierarchy is better
        visualized.
        """
        parent_idx = ref_index.parent()
        while parent_idx.isValid():
            tv.expand(parent_idx)
            parent_idx = parent_idx.parent()

    def on_load_foreign_key_browser(self):
        """
        When the generate button is clicked, generate code.
        :return:
        :rtype:
        """
        self.setReadOnly(not self.column.enable_editing)

        if self.column.prefix_source == self.tr('None'):
            self.set_code_from_no_prefix()

        elif self.column.prefix_source == 'admin_spatial_unit_set':
            self.set_code_from_admin_unit()

        elif self.column.prefix_source == self.column.columns_name:
            self.set_code_from_columns()

        elif self.column.prefix_source in self.code_columns:
            self.set_code_from_code_column()

        elif self.column.prefix_source == '':
            pass

        else:
            self.set_code_from_lookup()
        self.show_clear_button()

    def set_code_from_lookup(self):
        """
        Creates code from a lookup value code.
        Creates a code containing lookup value code and serial number.
        """
        if self.column.prefix_source != self.column.columns_name:
            lookup_selector = LookupValueSelector(iface.mainWindow(),
                                                  self.column.prefix_source)
            result = lookup_selector.exec_()

            if result == QDialog.Accepted:
                self.current_item = lookup_selector
                self._code = self.code_generator.generate(
                    lookup_selector.selected_code, self.column.separator,
                    self.column.leading_zero)
                self.format_display()

    def set_code_from_code_column(self):
        """
        Creates code using a serial number created from a linked code column.
        .. versionadded:: 1.7.5
        """
        parent_form = self.parent().parent().parent().parent().parent().parent(
        )
        parent_code_value_handler = parent_form.attribute_mapper(
            self.column.prefix_source).valueHandler()
        # parent_widget = parent_code_value_handler.control
        parent_widget_separator = parent_code_value_handler.control.column.separator
        parent_code_value = parent_code_value_handler.value()
        if parent_code_value is None:
            self._code = None
        else:
            codes = parent_code_value.split(parent_widget_separator)
            if len(codes) > 0:
                self._code = codes[-1]
            else:
                self._code = None

        self.current_item = ''

        self.format_display()

    def set_code_from_columns(self):
        """
        Creates code from a filled column values with a serial number at the end.
        .. versionadded:: 1.7.5
        """
        parent_form = self.parent().parent().parent().parent().parent().parent(
        )
        prefix_code = []

        for i, column_name in enumerate(self.column.columns):
            column = parent_form._entity.columns[column_name]

            separator = self.column.column_separators[i]
            try:
                id_value = parent_form.attribute_mapper(
                    column_name).valueHandler().value()
            except Exception:
                id_value = parent_form.entity_editor.attribute_mapper(
                    column_name).valueHandler().value()

            if column.TYPE_INFO in [
                    'LOOKUP', 'ADMIN_SPATIAL_UNIT', 'FOREIGN_KEY'
            ]:

                code = entity_id_to_attr(column.entity_relation.parent, 'code',
                                         id_value)
                prefix_code.append(u'{}{}'.format(code, separator))

            else:
                prefix_code.append(u'{}{}'.format(id_value, separator))

        self.current_item = ''
        code = u''.join(prefix_code)

        if self.column.disable_auto_increment:
            self._code = code
        else:
            # The prefix and separator should be '' for a serial.
            self._code = self.code_generator.generate(
                code, self.column.column_separators[-1],
                self.column.leading_zero)

        self.format_display()

    def set_code_from_admin_unit(self):
        """
        Set code from administrative unit. Creates code containing admin
        unit codes and serial number.
        """
        # Show the selector for administrative units
        au_selector = AdminUnitSelector(self.parent())
        au_selector.setManageMode(False)
        item_model = au_selector.adminUnitManager.model()
        selection_model = au_selector.adminUnitManager.selection_model()
        # Highlight previously selected item
        self._select_current_item(item_model, selection_model,
                                  au_selector.adminUnitManager.tvAdminUnits)
        if au_selector.exec_() == QDialog.Accepted:
            self.current_item = au_selector.selectedAdminUnit
            self._admin_hierarchy_code = self.current_item.hierarchyCode(
                self.column.separator)

            self._code = self.code_generator.generate(
                self._admin_hierarchy_code, self.column.separator,
                self.column.leading_zero, self.column.hide_prefix)
            self.format_display()

    def code(self):
        """
        Returns the code.
        :return:
        :rtype:
        """
        return self._code

    def set_code_from_no_prefix(self):
        """
        Set code from None prefix. Creates a serial number without prefix.
        """
        self.current_item = ''
        # The prefix and separator should be '' for a serial.
        self._code = self.code_generator.generate('', '',
                                                  self.column.leading_zero)
        self._code = self._code[1:]
        self.format_display()
Exemplo n.º 6
0
class AutoGeneratedLineEdit(ForeignKeyLineEdit):
    """
    Custom implementation for selecting and displaying administrative areas
    using the name and corresponding code.
    """
    def __init__(self, *args, **kwargs):
        # Use a different pixmap
        px = QPixmap(':/plugins/stdm/images/icons/code.png')
        kwargs['pixmap'] = px

        self._code = None
        self._current_profile = current_profile()
        self._admin_hierarchy_code = None

        ForeignKeyLineEdit.__init__(self, *args, **kwargs)
        self.code_generator = CodeGenerator(self.entity, self.column)
        self.code_columns = code_columns(self.entity, self.column.name)
        self.setText('')

    def format_display(self):
        try:
            self.setText(self._code)
        except RuntimeError:
            QMessageBox.warning(
                None,
                QApplication.translate(
                    'AutoGeneratedLineEdit',
                    "Value Error"
                ),
                'The change is not saved. '
                'Please use the form to edit data.'
            )
        except TypeError:
            pass

    def parent_entity_model(self):
        #Use default admin unit model class.
        return AdminSpatialUnitSet

    def _search_current_item_index(self, model, parent_index):
        #Recursively search for model index corresponding to current item
        if self.current_item is None:
            return None

        current_item_idx = None

        if model.hasChildren(parent_index):
            row_count = model.rowCount(parent_index)
            for i in range(row_count):
                #Check value from previous iteration
                if not current_item_idx is None:
                    break

                c_idx = model.index(i, 0, parent_index)
                node = c_idx.internalPointer()
                id = node.data(2)

                #Item found
                if id == self.current_item.id:
                    current_item_idx = c_idx
                    break

                else:
                    #Search children indices
                    current_item_idx = self._search_current_item_index(
                        model,
                        c_idx
                    )

        return current_item_idx

    def _select_current_item(self, model, selection_model, tv):
        #Selects the row corresponding to the current item
        if self._current_item is None:
            return

        root_idx = QModelIndex()
        current_item_idx = self._search_current_item_index(model, root_idx)

        #Expand items at the current item index
        self._expand_parent_indices(current_item_idx, tv)

        #Select item
        selection_model.select(
            current_item_idx,
            QItemSelectionModel.ClearAndSelect|QItemSelectionModel.Rows
        )

    def _expand_parent_indices(self, ref_index, tv):
        """
        Expand all parents of ref_index so that the hierarchy is better
        visualized.
        """
        parent_idx = ref_index.parent()
        while parent_idx.isValid():
            tv.expand(parent_idx)
            parent_idx = parent_idx.parent()

    def on_load_foreign_key_browser(self):
        """
        When the generate button is clicked, generate code.
        :return:
        :rtype:
        """
        self.setReadOnly(not self.column.enable_editing)

        if self.column.prefix_source == self.tr('None'):
            self.set_code_from_no_prefix()

        elif self.column.prefix_source == 'admin_spatial_unit_set':
            self.set_code_from_admin_unit()

        elif self.column.prefix_source == self.column.columns_name:
            self.set_code_from_columns()

        elif self.column.prefix_source in self.code_columns:
            self.set_code_from_code_column()

        elif self.column.prefix_source == '':
            pass

        else:
            self.set_code_from_lookup()
        self.show_clear_button()

    def set_code_from_lookup(self):
        """
        Creates code from a lookup value code.
        Creates a code containing lookup value code and serial number.
        """
        if self.column.prefix_source != self.column.columns_name:
            lookup_selector = LookupValueSelector(
                iface.mainWindow(), self.column.prefix_source
            )
            result = lookup_selector.exec_()

            if result == QDialog.Accepted:
                self.current_item = lookup_selector
                self._code = self.code_generator.generate(
                    lookup_selector.selected_code,
                    self.column.separator,
                    self.column.leading_zero
                )
                self.format_display()

    def set_code_from_code_column(self):
        """
        Creates code using a serial number created from a linked code column.
        .. versionadded:: 1.7.5
        """
        #parent_form = self.parent().parent().parent().parent().parent().parent()
        parent_form = self.entity_dialog
        
        parent_code_value_handler = parent_form.attribute_mapper(
            self.column.prefix_source).valueHandler()
        # parent_widget = parent_code_value_handler.control
        parent_widget_separator = parent_code_value_handler.control.column.separator
        parent_code_value = parent_code_value_handler.value()
        if parent_code_value is None:
            self._code = None
        else:
            codes = parent_code_value.split(parent_widget_separator)
            if len(codes) > 0:
                self._code = codes[-1]
            else:
                self._code = None

        self.current_item = ''

        self.format_display()

    def set_code_from_columns(self):
        """
        Creates code from a filled column values with a serial number at the end.
        .. versionadded:: 1.7.5
        """
        prefix_code = []
        column_complete = True

        for i, column_name in enumerate(self.column.columns):

            col_value = self.column_value(self.entity_dialog, column_name)

            if col_value is None:
                column_complete = False
                break

            padded_val = self.padded_value(str(col_value), self.column, i)

            separator = self.column.column_separators[i]

            prefix_code.append(u'{}{}'.format(padded_val, separator))

        self.current_item = ''
        code = u''.join(prefix_code)

        if self.column.disable_auto_increment:
            self._code = code
        else:
            # The prefix and separator should be '' for a serial.
            self._code = self.code_generator.generate(
                code,
                self.column.column_separators[-1],
                self.column.leading_zero
            )

        if not column_complete:
            self._code = ''
        self.format_display()

    def column_value(self, entity_dialog, column_name):
        value = entity_dialog.attribute_mapper(column_name).valueHandler().value()
        column = entity_dialog.entity.columns[column_name]
        if column.TYPE_INFO in ['LOOKUP', 'ADMIN_SPATIAL_UNIT', 'FOREIGN_KEY']:
            col_value = entity_id_to_attr(column.entity_relation.parent, 'code', value)
        else:
            col_value = value
        return col_value

    def padding_direction(self, directions, index):
        pad_dir = 'PAD_LEFT'
        if len(directions) > 0:
            pad_dir = directions[index]
        return pad_dir

    def pad_value(self, value, pad_len, pad_dir):
        if pad_dir == 'PAD_LEFT':
            pv = ('0'*pad_len) + value
        else:
            pv = value + ('0'*pad_len)
        return pv

    def padded_value(self, value, column, index):
        if len(column.char_lengths) < 0:
            return value

        if index > len(column.char_lengths):
            return value

        char_len = int(column.char_lengths[index])

        if len(value) >= char_len:
            return value

        pad_len = char_len - len(value)
        pad_dir = self.padding_direction(column.pad_dir, index)
        padded_v = self.pad_value(value, pad_len, pad_dir)
        return padded_v

    def set_code_from_admin_unit(self):
        """
        Set code from administrative unit. Creates code containing admin
        unit codes and serial number.
        """
        # Show the selector for administrative units
        au_selector = AdminUnitSelector(self.parent())
        au_selector.setManageMode(False)
        item_model = au_selector.adminUnitManager.model()
        selection_model = au_selector.adminUnitManager.selection_model()
        # Highlight previously selected item
        self._select_current_item(
            item_model,
            selection_model,
            au_selector.adminUnitManager.tvAdminUnits
        )
        if au_selector.exec_() == QDialog.Accepted:
            self.current_item = au_selector.selectedAdminUnit
            self._admin_hierarchy_code = self.current_item.hierarchyCode(
                self.column.separator
            )

            self._code = self.code_generator.generate(
                self._admin_hierarchy_code,
                self.column.separator,
                self.column.leading_zero,
                self.column.hide_prefix
            )
            self.format_display()

    def code(self):
        """
        Returns the code.
        :return:
        :rtype:
        """
        return self._code

    def set_code_from_no_prefix(self):
        """
        Set code from None prefix. Creates a serial number without prefix.
        """
        self.current_item = ''
        # The prefix and separator should be '' for a serial.
        self._code = self.code_generator.generate(
            '',
            '',
            self.column.leading_zero
        )
        self._code = self._code[1:]
        self.format_display()