Пример #1
0
class FrmCategorias( QMainWindow, Ui_FrmCategorias ):
    '''
    classdocs
    '''

    def __init__( self, parent = None ):
        '''
        Constructor
        '''
        super( FrmCategorias, self ).__init__( parent )
        self.setupUi( self )
        QSqlDatabase.database().open()

        self.model = CategoriesModel()

        self.catproxymodel = TreeFilterProxyModel()
        self.catproxymodel.setSourceModel( self.model )
        self.catproxymodel.setFilterKeyColumn( 0 )
        self.catproxymodel.setFilterCaseSensitivity( Qt.CaseInsensitive )

        self.view.setModel( self.catproxymodel )
        self.view.setColumnWidth( 0, 200 )
        self.view.setColumnHidden( 1, True )

    @pyqtSlot()
    def on_actionAddSub_triggered( self ):
        index = self.view.selectionModel().currentIndex()
        model = self.view.model()

        dlg = dlgCategoriesMod( self )
        if dlg.exec_() == QDialog.Accepted:
            if not model.insertRow( 0, index ):
                return QMessageBox.critical( self, qApp.organizationName(),
                                             "No se pudo insertar la categoria" )

            for column in range( model.columnCount( index ) ):
                child = model.index( 0, column, index )
                model.setData( child, [dlg.txtName.text(), 0], Qt.EditRole )

    @pyqtSlot()
    def on_actionAdd_triggered( self ):
        index = self.view.selectionModel().currentIndex()
        model = self.view.model()

        dlg = dlgCategoriesMod( self )
        if dlg.exec_() == QDialog.Accepted:
            if not model.insertRow( index.row() + 1, index.parent() ):
                return QMessageBox.critical( self, qApp.organizationName(),
                                             "No se pudo insertar la categoria" )


            for column in range( model.columnCount( index.parent() ) ):
                child = model.index( index.row() + 1, column, index.parent() )
                model.setData( child, [ dlg.txtName.text(), 0], Qt.EditRole )

    @pyqtSlot()
    def on_actionEditar_triggered( self ):
        index = self.view.selectionModel().currentIndex()
        model = self.view.model()

        dlg = dlgCategoriesMod( self )
        dlg.txtName.setText( index.data().toString() )
        if dlg.exec_() == QDialog.Accepted:
            if not model.setData( index, [dlg.txtName.text(), index.data()] ):
                raise Exception( "No se pudo editar la categoria" )





    @pyqtSlot()
    def on_actionDelete_triggered( self ):
        index = self.view.selectionModel().currentIndex()
        if not self.model.removeRow( index.row(), index.parent() ):
            QMessageBox.critical( self, qApp.organizationName(),
                                  "No se pudo borrar la categoria"\
                                  + "tenga en cuenta que no podra borrar"\
                                  + " categorias que el sistema ya"\
                                  + "este utilizando" )

    @pyqtSlot( "QString" )
    def on_txtSearch_textEdited( self , text ):
        self.catproxymodel.setFilterRegExp( text )
Пример #2
0
class FrmArticlesNew( QDialog, Ui_frmArticlesNew ):
    '''
    classdocs
    '''

    def __init__( self, parent = None ):
        '''
        Constructor
        '''
        super( FrmArticlesNew, self ).__init__( parent )
        self.user = user.LoggedUser
        self.setupUi( self )
        self.catmodel = CategoriesModel()

        self.catproxymodel = TreeFilterProxyModel()
        self.catproxymodel.setSourceModel( self.catmodel )
        self.catproxymodel.setFilterKeyColumn( 0 )
        self.catproxymodel.setFilterCaseSensitivity( Qt.CaseInsensitive )



        self.catvalid = False
        self.cat_id = 0
        self.brand_id = 0
        self.isc = Decimal( 0 )
        self.dai = Decimal( 0 )
        self.comission = Decimal( 0 )
        self.profit = Decimal( 0 )


        self.categoriesview.setModel( self.catproxymodel )
        self.categoriesview.setColumnHidden( 1, True )
        self.categoriesview.resizeColumnToContents( 0 )

        self.brandsmodel = QSqlQueryModel()

        self.cargarMarcas()

        self.brandsproxymodel = QSortFilterProxyModel()
        self.brandsproxymodel.setSourceModel( self.brandsmodel )
        self.brandsproxymodel.setFilterKeyColumn( 1 )
        self.brandsproxymodel.setFilterCaseSensitivity( Qt.CaseInsensitive )
        self.brandsview.setModel( self.brandsproxymodel )
        self.brandsview.setModelColumn( 1 )



        self.buttonBox.rejected.connect( self.reject )
        self.categoriesview.selectionModel().selectionChanged[QItemSelection, QItemSelection].connect( self.update_category )
        self.brandsview.selectionModel().selectionChanged[QItemSelection, QItemSelection].connect( self.updateBrand )

    def cargarMarcas( self ):
        if not QSqlDatabase.database().isOpen():
            if not QSqlDatabase.database().open():
                raise Exception( "No se pudo abrir la base de datos" )

        self.brandsmodel.setQuery( """
        SELECT idmarca, nombre 
        FROM marcas
        """ )
        if  QSqlDatabase.database().isOpen():
            QSqlDatabase.database().close()


    @pyqtSlot()
    def on_buttonBox_accepted( self ):
        if self.valid:
            if QMessageBox.question( self,
                                     qApp.organizationName(),
                                     u"¿Esta seguro que desea añadir el producto?",
                                     QMessageBox.Ok |
                                     QMessageBox.Cancel ) == QMessageBox.Ok:
                if not self.save():
                    QMessageBox.critical( self,
                                          qApp.organizationName(),
                                          u"Lo sentimos pero no se ha"\
                                          + " podido guardar el articulo" )
                else:
                    super( FrmArticlesNew, self ).accept()
        else:
            QMessageBox.warning( self,
                                 qApp.organizationName(),
                                 u"Lo sentimos pero los datos no son"\
                                 + " validos, recuerde elegir una subcategoria"\
                                 + " y una marca" )


    def save( self ):
        """
        Guardar el nuevo articulo en la base de datos
        """
        query = QSqlQuery()
        result = False
        try:
            if not QSqlDatabase.database().isOpen():
                if not QSqlDatabase.open():
                    raise UserWarning( u"No se pudo conectar con la"\
                                       + " base de datos" )


            query.prepare( """
                    CALL spAgregarArticulos(
                        :activo,
                        :marca, 
                        :subcategoria, 
                        :dai,
                        :isc, 
                        :comision, 
                        :ganancia 
                        )
                        """ )
            query.bindValue( ":activo", 1 )
            query.bindValue( ":marca", self.brand_id )
            query.bindValue( ":subcategoria", self.cat_id )
            query.bindValue( ":dai", str( self.dai ) )
            query.bindValue( ":isc", str( self.isc ) )
            query.bindValue( ":comision", str( self.comission ) )
            query.bindValue( ":ganancia", str( self.profit ) )

            if not query.exec_():
                raise Exception( "No se pudo ejecutar la consulta" )

            result = True

        except UserWarning as inst:
            logging.error( query.lastError().text() )
            logging.error( unicode( inst ) )
        except Exception as inst:
            logging.critical( query.lastError().text() )
            logging.critical( unicode( inst ) )

        return result

    @pyqtSlot( unicode )
    def on_txtCategorySearch_textChanged( self, text ):
        self.catproxymodel.setFilterFixedString( text )

    @pyqtSlot( unicode )
    def on_txtBrandSearch_textChanged( self, text ):
        self.brandsproxymodel.setFilterFixedString( text )

    @property
    def valid( self ):
        return self.catvalid and self.brand_id != 0

    @pyqtSlot()
    def on_btnAgregarMarca_pressed( self ):
        marca = ["", True]
        marca_descripcion = ""
        while marca_descripcion == "" and marca[1] == True:
            marca = QInputDialog.getText( self, "Agregar Marca",
                                          "Ingrese la Marca" )
            marca_descripcion = marca[0].strip()
            if marca_descripcion != "":
                proxy = self.brandsproxymodel
                proxy.setFilterRegExp( "^" + marca_descripcion + "$" )

                if proxy.rowCount() > 0:
                    QMessageBox.information( None, "Crear Marca",
                                         "La marca %s ya existe" %
                                          marca_descripcion )
                    marca = ["", True]
                    marca_descripcion = ""

        self.brandsproxymodel.setFilterRegExp( "" )

        if marca[1]:
            if QMessageBox.question( self, qApp.organizationName(),
                                      u"¿Está seguro que desea crear la marca %s ?" %
                                      marca_descripcion,
                                      QMessageBox.Yes | QMessageBox.No
                                       ) == QMessageBox.Yes:
                if not QSqlDatabase.database().isOpen():
                    if not QSqlDatabase.database().open():

                        raise Exception( "No se pudo abrir la base de datos" )
                query = QSqlQuery()
                query.prepare( "INSERT INTO marcas(nombre) VALUES (:marca)" )
                query.bindValue( ":marca", marca_descripcion )
                if not query.exec_():
                    logging.error( query.lastError().text() )
                    QMessageBox.warning( None, "Error al crear la marca",
                                          "No se pudo insertar la marca" )
                else:
                    self.cargarMarcas()


    @pyqtSlot( float )
    def on_sbDAI_valueChanged( self, value ):
        try:
            self.dai = Decimal( str( value ) )
        except ValueError:
            self.dai = 0

    @pyqtSlot( float )
    def on_sbISC_valueChanged( self, value ):
        try:
            self.isc = Decimal( str( value ) )
        except ValueError:
            self.isc = 0


    @pyqtSlot( float )
    def on_sbComission_valueChanged( self, value ):
        try:
            self.comission = Decimal( str( value ) )

        except ValueError:
            self.comission = 0

    @pyqtSlot( float )
    def on_sbProfit_valueChanged( self, value ):
        try:
            self.profit = Decimal( str( value ) )
        except ValueError:
            self.profit = 0

    def updateBrand( self, selected, _deselected ):
        if self.brandsproxymodel.rowCount() >= 0:
            self.brand_id = self.brandsproxymodel.index( 
                                   selected.indexes()[0].row(),
                                    0 ).data().toInt()[0]


    def update_category( self, selected, _deselected ):
        try:
            row = selected.indexes()[0].row()
            parent = selected.indexes()[0].parent()
            self.catvalid = parent.data().toString() != ""
            self.cat_id = self.catproxymodel.data( 
                              self.catproxymodel.index( row, 1,
                                         parent ), Qt.DisplayRole )
        except IndexError:
            pass
Пример #3
0
class FrmAccounts( QMainWindow, Ui_frmAccounts ):
    """

    """
    def __init__( self, parent = None ):
        super( FrmAccounts, self ).__init__( parent )

        self.setupUi( self )
        self.user = user.LoggedUser

        QSqlDatabase.database().open()
#        self.accountsTree.setModel( AccountsModel( 1 ) )



        self.model = AccountsModel( 1 )

        self.filtermodel = TreeFilterProxyModel()
        self.filtermodel.setShowAllChildren( True )
        self.filtermodel.setSourceModel( self.model )
        self.filtermodel.setFilterKeyColumn( DESCRIPCION )
        self.filtermodel.setFilterCaseSensitivity( Qt.CaseInsensitive )

        self.accountsTree.setModel( self.filtermodel )

        self.accountsTree.setColumnHidden( IDCUENTA, True )
        self.accountsTree.setColumnHidden( HIJOS, True )
        self.accountsTree.setColumnHidden( PADRE, True )

        self.accountsTree.setColumnWidth( CODIGO, 240 )
        self.accountsTree.setColumnWidth( DESCRIPCION, 240 )
        self.accountsTree.expandAll()

    @pyqtSlot()
    def on_btnAdd_clicked( self ):
        proxyindex = self.accountsTree.currentIndex()
        row = proxyindex.row()
        index = self.accountsTree.model().mapToSource( 
                           self.accountsTree.model().index( 
                                   row, CODIGO, proxyindex.parent() ) )


        dlg = DlgAccountMod( self )
        if dlg.exec_() == QDialog.Accepted:
            try:
                self.accountsTree.model().sourceModel().insertRows( 
                                                 index.row(),
                                                 1,
                                                 index,
                                                 " ".join( [txt.text() for txt in dlg.txtCodes ] ),
                                                 dlg.txtDescription.text(),
                                                 1 if dlg.cbEsdebe.checkState() == Qt.CheckState else 0
                                                   )
            except UserWarning as inst:
                logging.error( inst )
                QMessageBox.critical( self, qApp.organizationName(), unicode( inst ) )
            except Exception as inst:
                logging.critical( inst )

    @pyqtSlot()
    def on_btnModify_clicked( self ):
        index = self.accountsTree.currentIndex()
        dlg = DlgAccountMod( self )
        row = index.row()
        codes = self.accountsTree.model().index( row, CODIGO, index.parent() ).data().toString()
        codes = codes.split( ' ' )
        for id, code in enumerate( codes ):
            dlg.txtCodes[id].setText( code )

        dlg.txtDescription.setText( self.accountsTree.model().index( row, DESCRIPCION, index.parent() ).data().toString() )
        dlg.cbEsdebe.setCheckState( Qt.Checked if self.accountsTree.model().index( row, ESDEBE, index.parent() ).data().toInt()[0] else Qt.Unchecked )
        if dlg.exec_() == QDialog.Accepted:
            self.accountsTree.model().setData( 
              self.accountsTree.model().index( 
                      row, DESCRIPCION, index.parent() ), dlg.txtDescription.text() )
            self.accountsTree.model().setData( 
              self.accountsTree.model().index( 
                    row, CODIGO, index.parent() ), " ".join( [txt.text() for txt in dlg.txtCodes ] ) )

            self.accountsTree.model().setData( 
                    self.accountsTree.model().index( 
                        row, ESDEBE, index.parent() ), 1 if dlg.cbEsdebe.checkState() == Qt.Checked else 0 )


    @pyqtSlot( "QString" )
    def on_txtSearch_textEdited( self , text ):
        self.filtermodel.setFilterRegExp( text )