Пример #1
0
    def __init__(self, entity_document, document_model, parent=None):
        QObject.__init__(self, parent)
        self.containers = OrderedDict()
        self._canEdit = True

        self.document_model = document_model
        self.curr_profile = current_profile()

        self.entity_supporting_doc = entity_document.document_type_entity

        check_doc_type_model = entity_model(self.entity_supporting_doc)
        doc_type_obj = check_doc_type_model()
        doc_type_list = doc_type_obj.queryObject().all()
        self.doc_types = [(doc.id, doc.value) for doc in doc_type_list]
        self.doc_types = dict(self.doc_types)

        for id in self.doc_types.keys():
            document_type_class[id] = self.document_model
        # Container for document references based on their unique IDs
        self._docRefs = []

        # Set default manager for document viewing
        self._doc_view_manager = DocumentViewManager(self.parent_widget())

        self.doc_type_mapping = OrderedDict()

        for id, value in self.doc_types.items():
            self.doc_type_mapping[id] = value
Пример #2
0
    def __init__(self, title='', parent=None):
        self._title = title
        self._parent = parent

        # Set default manager for document viewing
        self._doc_view_manager = DocumentViewManager(self._parent)
        self._doc_view_manager.setWindowTitle(self._title)
        self._network_doc_path = network_document_path()
        self._network_manager = NetworkFileManager(self._network_doc_path)
Пример #3
0
    def __init__(self, title='', parent=None):
        self._title = title
        self._parent = parent

        # Set default manager for document viewing
        self._doc_view_manager = DocumentViewManager(self._parent)
        self._doc_view_manager.setWindowTitle(self._title)
        self._network_doc_path = network_document_path()
        self._network_manager = NetworkFileManager(self._network_doc_path)
Пример #4
0
class _EntityDocumentViewerHandler(object):
    """
    Class that loads the document viewer to display all documents
    pertaining to a given entity record.
    """
    def __init__(self, title='', parent=None):
        self._title = title
        self._parent = parent

        # Set default manager for document viewing
        self._doc_view_manager = DocumentViewManager(self._parent)
        self._doc_view_manager.setWindowTitle(self._title)
        self._network_doc_path = network_document_path()
        self._network_manager = NetworkFileManager(self._network_doc_path)

    def _create_document_viewer(self, d):
        doc_widget_proxy = DocumentWidget(fileManager=self._network_manager,
                                          mode=DOWNLOAD_MODE,
                                          view_manager=self._doc_view_manager)
        doc_widget_proxy.setModel(d)
        # Load proxies to the document view manager
        return self._doc_view_manager.load_viewer(doc_widget_proxy, False)

    def load(self, documents):
        # Reset viewer
        self._doc_view_manager.reset()

        # Assert if the root document directory exists
        if not self.root_directory_exists():
            base_msg = QApplication.translate(
                'EntityBrowser', 'The root document directory does not exist')
            msg = u'{0}:\n{1}'.format(base_msg, self._network_doc_path)
            QMessageBox.critical(self._parent, self._title, msg)

            return

        # Configure progress bar
        num_docs = len(documents)
        prog_dlg = QProgressDialog('', None, 0, num_docs, self._parent)
        prog_dlg.setWindowModality(Qt.WindowModal)
        prog_msg = QApplication.translate('EntityBrowser',
                                          'Loading {0:d} of {1:d}')

        QApplication.setOverrideCursor(Qt.WaitCursor)

        # Create document widgets proxies
        # for loading into the doc viewer
        for i, d in enumerate(documents):
            #Update progress dialog
            p_msg = prog_msg.format((i + 1), num_docs)
            prog_dlg.setLabelText(p_msg)
            prog_dlg.setValue(i)

            status = self._create_document_viewer(d)

            if not status:
                QApplication.restoreOverrideCursor()
                prog_dlg.hide()

            QApplication.processEvents()

        prog_dlg.setValue(num_docs)

        #cRestore pointer cursor
        QApplication.restoreOverrideCursor()

        self._doc_view_manager.setVisible(True)

    def root_directory_exists(self):
        # Returns True if the root document
        # directory exists, otherwise False.
        dir = QDir(self._network_doc_path)

        return dir.exists()
Пример #5
0
class SourceDocumentManager(QObject):
    """
    Manages the display of source documents in vertical layout container(s).
    """
    # Signal raised when a document is removed from its container.
    documentRemoved = pyqtSignal(int, str, list)
    fileUploaded = pyqtSignal('PyQt_PyObject')

    def __init__(self, entity_document, document_model, parent=None):
        QObject.__init__(self, parent)
        self.containers = OrderedDict()
        self._canEdit = True

        self.document_model = document_model
        self.curr_profile = current_profile()

        self.entity_supporting_doc = entity_document.document_type_entity

        check_doc_type_model = entity_model(self.entity_supporting_doc)
        doc_type_obj = check_doc_type_model()
        doc_type_list = doc_type_obj.queryObject().all()
        self.doc_types = [(doc.id, doc.value) for doc in doc_type_list]
        self.doc_types = dict(self.doc_types)

        for id in self.doc_types.keys():
            document_type_class[id] = self.document_model
        # Container for document references based on their unique IDs
        self._docRefs = []

        # Set default manager for document viewing
        self._doc_view_manager = DocumentViewManager(self.parent_widget())

        self.doc_type_mapping = OrderedDict()

        for id, value in self.doc_types.items():
            self.doc_type_mapping[id] = value

    def reset(self):
        """
        Removes all ids and corresponding containers.
        """
        containers = self.containers
        self.containers.clear()
        del self._docRefs[:]
        return containers

    def clear(self):
        """
        Clears all document widgets from all containers.
        """
        for cont_id, container in self.containers.items():
            doc_widgets = container.parentWidget().findChildren(DocumentWidget)
            for doc_widget in doc_widgets:
                doc_widget.deleteLater()
                doc_widget = None

    def parent_widget(self):
        """
        :return: Instance of widget that is the parent container of this document manager.
        """
        parent_widg = self.parent()

        if isinstance(parent_widg, QWidget):
            return parent_widg

        return None

    def setEditPermissions(self, state):
        '''
        Sets whether the user can edit existing source document records.
        This applies for all containers managed by this class.
        '''
        self._canEdit = state

    def registerContainer(self, container, id):
        '''
        Register a container for displaying the document widget
        '''
        if container is not None:
            self.containers[id] = container

    def removeContainer(self, containerid):
        """
        Removes the container with the specified ID from the
        document manager.
        """
        if containerid in self.containers:
            del self.containers[containerid]

    def container(self, containerid):
        '''
        Get the container from the given id
        '''
        container = None

        if containerid in self.containers:
            container = self.containers[containerid]

        return container

    def registeredIds(self):
        '''
        Returns a list of registered Ids.
        '''
        return list(self.containers.keys())

    def insertDocumentFromFile(self, path, doc_type_id, entity, record_count=1):
        """
        Insert a new document into one of the registered containers with the
        document type id. This document is registered
        :param path: The local user path of the document
        :type path: String
        :param doc_type_id: The entity document type id
        :type doc_type_id: Integer
        :param entity: The entity in which the document is inserted into.
        :type entity: Entity class
        :param record_count: The number of records for which a
        document is uploaded. Default is 1. For instance, more
        records could be used in STR wizard in multi-party.
        :type record_count: Integer
        :return: None
        :rtype: NoneType
        """
        if len(self.containers) > 0:
            if doc_type_id in self.containers:
                container = self.containers[doc_type_id]

                # Check if the file exists
                if QFile.exists(path):

                    network_location = network_document_path()

                    if not network_location:
                        self._doc_repository_error()

                        return

                    # Check if the directory exists
                    doc_dir = QDir(network_location)

                    if not doc_dir.exists():
                        msg = QApplication.translate(
                            "sourceDocumentManager",
                            "The root document "
                            "repository '{0}' does "
                            "not exist.\nPlease "
                            "check the path settings."
                        )
                        parent = self.parent()
                        if not isinstance(parent, QWidget):
                            parent = None

                        QMessageBox.critical(
                            parent,
                            QApplication.translate(
                                "sourceDocumentManager",
                                "Document Manager"
                            ),
                            msg.format(network_location)
                        )
                        return

                    for i in range(record_count):
                        # Use the default network file manager
                        networkManager = NetworkFileManager(
                            network_location, self.parent()
                        )
                        # Add document widget
                        docWidg = DocumentWidget(
                            self.document_model,
                            networkManager,
                            parent=self.parent(),
                            view_manager=self._doc_view_manager
                        )
                        # Connect slot once the document
                        # has been successfully uploaded.
                        docWidg.fileUploadComplete.connect(
                            lambda: self.onFileUploadComplete(doc_type_id)
                        )
                        self._linkWidgetRemovedSignal(docWidg)

                        doc_type_entity = entity.supporting_doc.document_type_entity
                        doc_type_value = entity_id_to_attr(
                            doc_type_entity, 'value', doc_type_id
                        )

                        docWidg.setFile(
                            path, entity.name, doc_type_value, doc_type_id
                        )
                        container.addWidget(docWidg)

    def onFileUploadComplete(self, documenttype):
        """
        Slot raised when a source file has been successfully
        uploaded into the central document repository.
        Raises a signal that passes the resulting source
        document from the upload operation.
        """
        docWidget = self.sender()
        if isinstance(docWidget, DocumentWidget):
            self.fileUploaded.emit(docWidget.sourceDocument(documenttype))
            self._docRefs.append(docWidget.fileUUID)

    def set_source_documents(self, source_docs):
        """
        :param source_docs: Supporting document objects
        to be inserted in their respective containers.
        :type source_docs: list
        """
        for source_doc in source_docs:
            if hasattr(source_doc, 'document_type'):
                document_type = source_doc.document_type
                self.insertDocFromModel(source_doc, document_type)

    def insertDocFromModel(self, sourcedoc, containerid):
        """
        Renders the source document info from a subclass of 'SupportingDocumentMixin'.
        """
        # Check if the document has already been inserted in the manager.
        docIndex = getIndex(self._docRefs, sourcedoc.document_identifier)
        if docIndex != -1:
            return

        if len(self.containers) > 0:
            if containerid in self.containers:
                container = self.containers[containerid]

                network_location = source_document_location('')

                if not network_location:
                    self._doc_repository_error()

                    return

                networkManager = NetworkFileManager(network_document_path())
                # Add document widget
                docWidg = DocumentWidget(
                    self.document_model,
                    networkManager,
                    mode=DOWNLOAD_MODE,
                    canRemove=self._canEdit,
                    view_manager=self._doc_view_manager
                )

                self._linkWidgetRemovedSignal(docWidg)
                docWidg.setModel(sourcedoc)
                container.addWidget(docWidg)

                self._docRefs.append(sourcedoc.document_identifier)

    def _doc_repository_error(self):
        msg = QApplication.translate(
            "sourceDocumentManager",
            "Document repository could not be found.\nPlease "
            "check the path settings."
        )
        QMessageBox.critical(None,
                             QApplication.translate("sourceDocumentManager",
                                                    "Document Manager"), msg)

    def networkResource(self):
        '''
        Get the network resource location from the registry.
        '''
        regConfig = RegistryConfig()
        networkResReg = regConfig.read([NETWORK_DOC_RESOURCE])

        if len(networkResReg) == 0:
            networkLocation = "C:/"
        else:
            networkLocation = networkResReg[NETWORK_DOC_RESOURCE]

        return networkLocation

    def attributeMapping(self, editing=False):
        """
        Returns the mapping of source document information for display of the summary
        documents contained in a stdm.navigation.TreeLoader object.
        """
        srcDocMapping = OrderedDict()

        for k, v in self.containers.items():

            if not v is None:
                docItems = OrderedDict()
                widgCount = v.count()

                for w in range(widgCount):
                    docWidg = v.itemAt(w).widget()
                    if editing:
                        srcFilePath = str(docWidg._displayName)
                        locTr = QApplication.translate(
                            "sourceDocumentManager", "File Name"
                        )
                    else:
                        srcFilePath = str(docWidg.fileInfo.absoluteFilePath())
                        locTr = QApplication.translate(
                            "sourceDocumentManager", "Location"
                        )
                    locTxt = "%s %s" % (locTr, str(w + 1))
                    docItems[locTxt] = srcFilePath

                docTypeText = "%s (%s)" % (self.doc_type_mapping[k], str(widgCount))
                srcDocMapping[docTypeText] = docItems

        return srcDocMapping

    def model_objects(self, dtype=None):
        """
        Returns all supporting document models based on
        the file uploads contained in the document manager.
        """
        all_doc_objs = []
        for doc_type_id, container in self.containers.items():
            doc_widget_count = container.count()
            # loop through all document
            # widgets and get their objects.
            for doc_widget in range(doc_widget_count):
                docWidg = container.itemAt(doc_widget).widget()
                source_doc = docWidg.sourceDocument(doc_type_id)
                all_doc_objs.append(source_doc)

        return all_doc_objs

    def clean_up(self):
        """
        Clears all unsaved files that had initially
        been uploaded in the corresponding containers.
        :return: Document widgets whose referenced
        files could not be deleted.
        :rtype: list
        """
        delete_error_docs = []

        for k, v in self.containers.items():
            layout_item = v.takeAt(0)

            while layout_item is not None:
                doc_widg = layout_item.widget()

                if not doc_widg.clean_up():
                    delete_error_docs.append(doc_widg)

                layout_item = v.takeAt(0)

        return delete_error_docs

    def onDocumentRemoved(self, containerid):
        """
        Slot raised when a document is removed from the container.
        Propagate signal.
        """
        remDocWidget = self.sender()

        doc_uuid = None
        if remDocWidget:
            self.container(containerid).removeWidget(remDocWidget)

            # Remove document reference in the list
            if remDocWidget.mode() == UPLOAD_MODE:
                doc_uuid = remDocWidget.fileUUID

            elif remDocWidget.mode() == DOWNLOAD_MODE:
                doc_uuid = remDocWidget.fileUUID

            if doc_uuid:
                # Remove corresponding viewer
                self._doc_view_manager.remove_viewer(doc_uuid)

                try:
                    self._docRefs.remove(doc_uuid)

                except ValueError:
                    pass
            remDocWidget.deleteLater()

        self.documentRemoved.emit(
            containerid,
            remDocWidget.fileUUID,
            remDocWidget.removed_doc
        )

    def eventFilter(self, watched, e):
        '''
        Intercept signals raised by the
        widgets managed by this container.
        For future implementations.
        '''
        pass

    def _addDocumentReference(self, docid):
        """
        Add a document reference to the
        list that the document manager
        contains
        """
        docIndex = getIndex(self._docRefs, docid)

        if docIndex == -1:
            self._docRefs.append(docid)

    def documentReferences(self):
        """
        Returns a list of document ids in the document manager.
        """
        return self._docRefs

    def _installEventFilter(self, widget):
        """
        Installs an event filter for the
        widget so that the class can now handle the
        events raised by widget.
        """
        widget.installEventFilter(self)

    def _linkWidgetRemovedSignal(self, widget):
        """
        Connects 'destroyed' signal raised
        when a widget is removed from the container.
        """
        widget.referencesRemoved.connect(self.onDocumentRemoved)
Пример #6
0
class _EntityDocumentViewerHandler(object):
    """
    Class that loads the document viewer to display all documents
    pertaining to a given entity record.
    """
    def __init__(self, title='', parent=None):
        self._title = title
        self._parent = parent

        # Set default manager for document viewing
        self._doc_view_manager = DocumentViewManager(self._parent)
        self._doc_view_manager.setWindowTitle(self._title)
        self._network_doc_path = network_document_path()
        self._network_manager = NetworkFileManager(self._network_doc_path)

    def _create_document_viewer(self, d):
        doc_widget_proxy = DocumentWidget(
            fileManager=self._network_manager,
            mode=DOWNLOAD_MODE,
            view_manager=self._doc_view_manager
        )
        doc_widget_proxy.setModel(d)
        # Load proxies to the document view manager
        return self._doc_view_manager.load_viewer(doc_widget_proxy, False)

    def load(self, documents):
        # Reset viewer
        self._doc_view_manager.reset()

        # Assert if the root document directory exists
        if not self.root_directory_exists():
            base_msg = QApplication.translate(
                'EntityBrowser',
                'The root document directory does not exist'
            )
            msg = u'{0}:\n{1}'.format(base_msg, self._network_doc_path)
            QMessageBox.critical(self._parent, self._title, msg)

            return

        # Configure progress bar
        num_docs = len(documents)
        prog_dlg = QProgressDialog('', None, 0, num_docs, self._parent)
        prog_dlg.setWindowModality(Qt.WindowModal)
        prog_msg = QApplication.translate(
            'EntityBrowser',
            'Loading {0:d} of {1:d}'
        )

        QApplication.setOverrideCursor(Qt.WaitCursor)

        # Create document widgets proxies
        # for loading into the doc viewer
        for i, d in enumerate(documents):
            #Update progress dialog
            p_msg = prog_msg.format((i+1), num_docs)
            prog_dlg.setLabelText(p_msg)
            prog_dlg.setValue(i)

            status = self._create_document_viewer(d)

            if not status:
                QApplication.restoreOverrideCursor()
                prog_dlg.hide()

            QApplication.processEvents()

        prog_dlg.setValue(num_docs)

        #cRestore pointer cursor
        QApplication.restoreOverrideCursor()

        self._doc_view_manager.setVisible(True)

    def root_directory_exists(self):
        # Returns True if the root document
        # directory exists, otherwise False.
        dir = QDir(self._network_doc_path)

        return dir.exists()