Exemple #1
0
class CExportPage1(QtGui.QWizardPage, Ui_ExportPage1, CExportHelperMixin, CConstructHelperMixin, CContainerPreferencesMixin):
    def __init__(self, parent):
        QtGui.QWizardPage.__init__(self, parent)
        self.setupUi(self)
        CExportHelperMixin.__init__(self)
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(1)
        self.progressBar.setText('')

        self.setTitle(u'Экспорт справочников')
        self.setSubTitle(u'для выполнения шага нажмите на кнопку "Экспорт"')

        self.addModels('RefBooks', CRefBooksModel(self))
        self.setModels(self.tblRefBooks, self.modelRefBooks, self.selectionModelRefBooks)

        self.setExportMode(False)
        self.aborted = False
        self.done = False
        self._refBooks = OrderedDict()
        self.parent = parent
        self.loadPreferences(getPref(QtGui.qApp.preferences.windowPrefs, self.objectName(), {}))
        self.connect(parent, QtCore.SIGNAL('rejected()'), self.abort)

    def setExportMode(self, flag):
        """
            Настройка активных кнопок в зависимости от текущего состояния.
        """
        self.btnCancel.setEnabled(flag)
        self.btnExport.setEnabled(not flag)
        self.btnExport.setEnabled(not flag)

    def log(self, str, forceLog = True):
        """
            Вывод сообщения в окно отчета.
        """
        self.logBrowser.append(str)
        self.logBrowser.update()

    def export(self):
        (result, rc) = QtGui.qApp.call(self, self.exportInt)
        self.setExportMode(False)
        if self.aborted or not result:
            self.progressBar.setText(u'прервано')
        else:
            self.progressBar.setText(u'готово')
            self.done = True
            self.emit(QtCore.SIGNAL('completeChanged()'))

    def prepareToExport(self):
        self.done = False
        self.aborted = False
        self.emit(QtCore.SIGNAL('completeChanged()'))
        self.setExportMode(True)
        output = self.createXML()
        self.progressBar.reset()
        items = self.modelRefBooks.items()
        self._refBooks = self.modelRefBooks.getRBStructure()
        self.progressBar.setMaximum(len(items))
        self.progressBar.setValue(0)
        return output, items

    def exportInt(self):
        out, items = self.prepareToExport()
        refBooksOut = CRefBooksStreamWriter(self)
        refBooksOut.setCodec(QtCore.QTextCodec.codecForName('cp1251'))
        refBooksOut.writeFileHeader(out, self.parent.getFullXmlFileName(), QtCore.QDate.currentDate())
        for item in items:
            QtGui.qApp.processEvents()
            if self.aborted:
                break
            self.progressBar.step()
            rbData = self.getRBData(item)
            if rbData:
                refBooksOut.writeRecord(item, rbData)

        refBooksOut.writeFileFooter()
        out.close()

    def getRBData(self, item):
        """
            item: (rbTableName, keyColumnName)
            depends: self._refBooks
            Загрузка справочника из БД
        """
        columns = self._refBooks.get(item[0], {}).get('cols', None)
        if columns is None:
            return None
        fields = columns.keys()
        db = QtGui.qApp.db
        stmt = db.selectStmt(item[0], map(lambda x: '`'+x+'`', fields))
        query = db.query(stmt)
        result = []
        while query.next():
            record = query.record()
            recordValues = {}
            for field in fields:
                recordValues[field] = forceString(record.value(field))
            result.append(recordValues)
        return result

# *****************************************************************************************

    def getTxtFileName(self):
        lpuCode = forceString(QtGui.qApp.db.translate(
            'Organisation', 'id', QtGui.qApp.currentOrgId() , 'infisCode'))
        return forceString(lpuCode + u'.TXT')

    def createTxt(self):
        txt = QFile(os.path.join(self.parent.getTmpDir(), self.getTxtFileName()))
        txt.open(QIODevice.WriteOnly | QIODevice.Text)
        txtStream =  QTextStream(txt)
        txtStream.setCodec('CP866')
        return txt,  txtStream


    def validatePage(self):
        return True

# *****************************************************************************************

    def createXML(self):
        outFile = QtCore.QFile(self.parent.getFullXmlFileName())
        outFile.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text)
        return outFile

# *****************************************************************************************

    def isComplete(self):
        return self.done


    def abort(self):
        self.aborted = True
        self.savePreferences()


    @QtCore.pyqtSignature('')
    def on_btnExport_clicked(self):
        self.export()


    @QtCore.pyqtSignature('')
    def on_btnCancel_clicked(self):
        self.abort()
Exemple #2
0
class CConnectionDialog(QtGui.QDialog, Ui_connectionDialog):

    iniFileName = 'connections.ini'

    def __init__(self, parent):
        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)

        self.edtConnectionName.completer().setCompletionMode(
            QtGui.QCompleter.UnfilteredPopupCompletion)
        self.connect(self, QtCore.SIGNAL('accepted()'),
                     self.saveConnectionInfo)
        self.connectionInfo = OrderedDict()
        self.loadConnectionInfo()

    def setDriverName(self, val):
        pass

    def driverName(self):
        return 'mysql'

    def setServerName(self, val):
        self.edtServerName.setText(val)

    def setConnectionName(self, name):
        defaultName = u'Основной'
        connectionIndex = self.edtConnectionName.findText(name)
        if connectionIndex < 0:
            connectionIndex = self.edtConnectionName.findText(defaultName)
        if connectionIndex < 0:
            connectionIndex = self.edtConnectionName.findText(
                self.serverName())

        if connectionIndex < 0:
            self.edtConnectionName.setEditText(defaultName)
        else:
            self.edtConnectionName.setCurrentIndex(connectionIndex)

    def connectionName(self):
        return self.edtConnectionName.currentText()

    def serverName(self):
        return str(self.edtServerName.text())

    def setServerPort(self, val):
        self.edtServerPort.setValue(val)

    def serverPort(self):
        return self.edtServerPort.value()

    def setDatabsaseName(self, val):
        self.edtDatabaseName.setText(val)

    def setLoggerDbName(self, val):
        self.edtLoggerDbName.setText(val)

    def databaseName(self):
        return self.edtDatabaseName.text()

    def loggerDbName(self):
        if self.edtLoggerDbName.text():
            return self.edtLoggerDbName.text()
        else:
            self.edtLoggerDbName.setText(u"logger")
            return self.edtLoggerDbName.text()

    def setCompressData(self, val):
        self.chkCompressData.setChecked(bool(val))

    def compressData(self):
        return self.chkCompressData.isChecked()

    def setUserName(self, val):
        self.edtUserName.setText(val)

    def userName(self):
        return self.edtUserName.text()

    def setPassword(self, val):
        self.edtPassword.setText(val)

    def password(self):
        return str(self.edtPassword.text())

    def setNewAuthorizationScheme(self, val):
        checkedValue = bool(val)
        self.chkAutScheme.setChecked(checkedValue)
        self.on_chkAutScheme_clicked(checkedValue)

    def newAuthorizationScheme(self):
        return self.chkAutScheme.isChecked()

    def connectionOrgId(self):
        connectionInfo = self.connectionInfo.get(
            self.edtConnectionName.currentText(), None)
        return connectionInfo[3] if connectionInfo else 0

    def connectionLogin(self):
        connectionInfo = self.connectionInfo.get(
            self.edtConnectionName.currentText(), None)
        return connectionInfo[4] if connectionInfo else u''

    def connectionOrgStructureId(self):
        connectionInfo = self.connectionInfo.get(
            self.edtConnectionName.currentText(), None)
        return connectionInfo[5] if connectionInfo else 0

    @QtCore.pyqtSlot(bool)
    def saveConnectionInfo(self):
        settings = CPreferences.getSettings(self.iniFileName)
        settings.beginGroup(self.edtConnectionName.currentText())
        settings.setValue('host', toVariant(self.serverName()))
        settings.setValue('port', toVariant(self.serverPort()))
        settings.setValue('database', toVariant(self.databaseName()))
        settings.setValue('loggerdb', toVariant(self.loggerDbName()))
        #        settings.setValue('orgId', toVariant(QtGui.qApp.currentOrgId()))
        settings.endGroup()
        settings.sync()

    def loadConnectionInfo(self):
        self.connectionInfo.clear()
        settings = CPreferences.getSettings(self.iniFileName)
        for connectionName in settings.childGroups():
            settings.beginGroup(connectionName)
            self.connectionInfo[connectionName] = (
                forceString(settings.value('host', connectionName)),
                forceInt(settings.value('port', 0)),
                forceString(settings.value('database', u's11')),
                forceRef(settings.value('orgId', None)),
                forceString(settings.value('login', u'')),
                forceRef(settings.value('orgStructureId', None)),
                forceString(settings.value('loggerdb', u'logger')))
            settings.endGroup()
        self.edtConnectionName.addItems(self.connectionInfo.keys())

    @QtCore.pyqtSlot(bool)
    def on_chkAutScheme_clicked(self, checked):
        self.groupBox.setEnabled(not checked)

    @QtCore.pyqtSlot(int)
    def on_edtConnectionName_currentIndexChanged(self, index):
        currentText = self.edtConnectionName.currentText()
        if currentText in self.connectionInfo.keys():
            host, port, database = self.connectionInfo[currentText][:3]
            loggerdb = self.connectionInfo[currentText][6]
            self.setServerName(host)
            self.setServerPort(port)
            self.setDatabsaseName(database)
            self.setLoggerDbName(loggerdb)

    @QtCore.pyqtSlot()
    def on_btnDelConnectionInfo_clicked(self):
        settings = CPreferences.getSettings(self.iniFileName)
        currentText = self.edtConnectionName.currentText()
        if currentText in settings.childGroups():
            settings.remove(currentText)
            settings.sync()
        self.connectionInfo.pop(currentText, None)
        self.edtConnectionName.clear()
        self.edtConnectionName.addItems(self.connectionInfo.keys())
        self.edtConnectionName.setCurrentIndex(0)