def openConect(self, usu, passw, host, port, dbase, direct=False): self.usuario = usu self.password = passw self.mhost = host self.mdbase = dbase self.mport = port url = host + ":" + port + "/" + dbase + "/" self.urlServer = QUrl(url) self.token.clear() self.boolConnect = False marray = QJsonArray() if self.versionct == "4": marray.append(self.usuario) marray.append(self.password) if direct: return self.callDirect("open@", "common.db.login", marray) else: self.call("open@", "common.db.login", marray) else: marray.append(self.usuario) marray.append({"password": self.password}) # mapass = QJsonValue({"password",self.password}) # marray.append(mapass.toObject()) if direct: return self.callDirect("open@", "common.db.login", marray) else: self.call("open@", "common.db.login", marray)
def exportJson(self): from PySide2.QtCore import QJsonDocument, QByteArray, QJsonArray jDoc = QJsonDocument() jObj = dict() if self._oroborusFlag == False: jObj["oroborusFlag"] = self._oroborusFlag if self._cycleFlag == False: jObj["cycleFlag"] = self._cycleFlag if self._radius != 100: jObj["radius"] = self._radius if self._speedRatio != 1.0: jObj["speedRatio"] = self._speedRatio if self._lineWidth != 1: jObj["lineWidth"] = self._lineWidth digitsArray = QJsonArray() for d in self._digitsList: digitsArray.append(int(d)) jObj["digits"] = digitsArray jObj["scale"] = self._scale if self._dotColor != QColor(Qt.green): jObj["dotColor"] = self._dotColor.name() if self._lineColor != QColor(Qt.black): jObj["lineColor"] = self._lineColor.name() jDoc.setObject(jObj) jsonString = jDoc.toJson(QJsonDocument.Compact).data().decode() return jsonString
def calendarShortNamesMonths(self, language=""): if language == "": language = QLocale.system().name() myLocale = QLocale(language) lista = QJsonArray() for i in range(1, 13): lista.append(myLocale.monthName(i, QLocale.ShortFormat)) return lista
def calendarLongNamesDays(self, language=""): if language == "": language = QLocale.system().name() myLocale = QLocale(language) lista = QJsonArray() for i in range(1, 8): lista.append(myLocale.dayName(i, QLocale.LongFormat)) return lista
def cb(res: ChallengeRsp): if res.qtype == 'roundSummary': prg_data = [{ 'wrd': asdict(i)['prg'][0]['wrd'], 'prg': asdict(i)['prg'][0]["prg"], 'def_': asdict(i)['prg'][0]['def_'] } for i in res.pdata.round] self.roundSummary.emit(QJsonArray.fromVariantList(prg_data)) else: self.newCard.emit(QJsonValue(asdict(res)))
def __init__(self, objname, parent=None): QObjectListModel.__init__(self, parent) self.setObjectName(str(objname)) self.m_locale = QLocale("es") #temp, auto changue when login #self.m_proxy = ProxyModelJson() self.m_order = "" self.boolMetadata = False self.m_fields = QJsonArray() #[]#QJsonArray self.m_fieldsPoint = [] #5.2up self.m_maxLimit = 100 self.m_domain = QJsonArray() #[]#QJsonArray self.m_orderTryton = QJsonArray() #[]#QJsonArray self.m_preferences = {} self.m_qjsonnetwork = QJsonNetwork() self.m_fieldsFormatDecimal = [] #QJsonArray self.m_fieldsFormatDateTime = [] #QJsonArray self.m_model_method_search = "" self.m_hasIndexOfId = {} self.m_engine = None #QQmlApplicationEngine() self.autoBusy = True self.boolSynchro = True # add synchronous call (calldirect), best performance!
def getListCoreTranslations(self): dircorelan = QDir(self.mDir + QDir.separator() + "corelocale") if dircorelan.exists(): fileNames = dircorelan.entryList(["*.qm"]) listLocale = QJsonArray() for i in range(len(fileNames)): locale = "" locale = fileNames[i] locale = locale.split('.')[0] listLocale.append(locale) listLocale.append("en") return listLocale return QJsonArray()
def __init__(self, parent=None): QObject.__init__(self, parent) self.parent = parent self.usuario = "" self.password = "" self.token = [] self.mmethod = "" self.mpid = "" self.mparams = [] self.mid = 0 self.boolConnect = False self.intCountConnect = 0 self.intReply = 0 self.intReplyMax = 2 self.urlServer = QUrl() self.versionct = "4" #trytond self.mhost = "" self.mdbase = "" self.mport = "" self.preferences = {} self.boolRun = False self.boolDirect = False self.boolRecursive = False self.mtypeCall = "order" self.mDir = QDir.currentPath() self.tempCallData = QJsonArray() self.tempCallFunctionArgs = QJsonArray() self.m_engine = QQmlApplicationEngine() # connect(managerAccess, SIGNAL(finished(QNetworkReply*)), # this, SLOT(replyFinishedOrder(QNetworkReply*))); self.managerAccess = QNetworkAccessManager(self) self.managerAccess.finished[QNetworkReply].connect( self.replyFinishedOrder)
def calendarMonth(self, anno, mes): lista = QJsonArray() mmap = {} dateFirtDay = QDate(anno, mes, 1) daysMes = dateFirtDay.daysInMonth() dayWeekFirst = dateFirtDay.dayOfWeek() if (dayWeekFirst == 1): dayWeekFirst = 8 dateLast1 = dateFirtDay.addDays(-(dayWeekFirst - 1)) diaLast1 = dateLast1.day() mesLast = dateLast1.month() annoLast = dateLast1.year() dateNext1 = dateFirtDay.addDays(daysMes) mesNext = dateNext1.month() annoNext = dateNext1.year() for i in range(0, dayWeekFirst - 1): # for(int i=0, len = dayWeekFirst-1; i<len;i++): mmap["dia"] = diaLast1 + i mmap["mes"] = mesLast mmap["anno"] = annoLast mmap["type"] = -1 lista.append(mmap) for i in range(1, daysMes + 1): #for(int i=1, len = daysMes; i<=len;i++): mmap["dia"] = i mmap["mes"] = mes mmap["anno"] = anno mmap["type"] = 0 lista.append(mmap) for i in range(1, (42 - daysMes - (dayWeekFirst - 1)) + 1): #for(int i=1, len = (42-daysMes-(dayWeekFirst-1)); i<=len;i++): mmap["dia"] = i mmap["mes"] = mesNext mmap["anno"] = annoNext mmap["type"] = 1 lista.append(mmap) return lista
def updateRecords(self, ids): #update record with tryton, self.openBusy() params = QJsonArray() params.append(ids) params.append(self.m_fields) params.append(self.m_preferences) if self.boolSynchro: # result = self.m_qjsonnetwork.callDirect("updateRecords"+self.objectName(), self.m_model_method_search+".read" ,params) result = self.m_qjsonnetwork.recursiveCall( "updateRecords" + self.objectName(), self.m_model_method_search + ".read", params) reValue = result["data"] if reValue.__class__() == {}: if reValue.__contains__("result"): if reValue["result"].__class__() == []: self.addResult(reValue["result"], True) self.closeBusy() else: self.m_qjsonnetwork.call("updateRecords" + self.objectName(), self.m_model_method_search + ".read", params)
class QJsonNetwork(QObject): def __init__(self, parent=None): QObject.__init__(self, parent) self.parent = parent self.usuario = "" self.password = "" self.token = [] self.mmethod = "" self.mpid = "" self.mparams = [] self.mid = 0 self.boolConnect = False self.intCountConnect = 0 self.intReply = 0 self.intReplyMax = 2 self.urlServer = QUrl() self.versionct = "4" #trytond self.mhost = "" self.mdbase = "" self.mport = "" self.preferences = {} self.boolRun = False self.boolDirect = False self.boolRecursive = False self.mtypeCall = "order" self.mDir = QDir.currentPath() self.tempCallData = QJsonArray() self.tempCallFunctionArgs = QJsonArray() self.m_engine = QQmlApplicationEngine() # connect(managerAccess, SIGNAL(finished(QNetworkReply*)), # this, SLOT(replyFinishedOrder(QNetworkReply*))); self.managerAccess = QNetworkAccessManager(self) self.managerAccess.finished[QNetworkReply].connect( self.replyFinishedOrder) # self.connect(self.managerAccess, SIGNAL("finished(QNetworkReply*)"), # self, self.replyFinishedOrder) ##ifndef QT_NO_SSL # self.connect(self.managerAccess, SIGNAL("sslErrors(QNetworkReply *, const QList<QSslError> &)"), # self, self.slotSslError) @Slot(str) def setVersionTryton(self, ver): self.versionct = ver def setEngine(self, engine): #QQmlApplicationEngine *engine=nullptr); self.m_engine = engine def clearMessagesWarning(self): root = self.m_engine.rootObjects()[0] QMetaObject.invokeMethod(root, "clearMessages") @Slot() def saveLastCall(self): self.tempCallData.append(self.boolDirect) self.tempCallData.append(self.mtypeCall) self.tempCallData.append(self.mpid) self.tempCallData.append(self.mmethod) self.tempCallData.append(self.mparams) @Slot() def runLastCall(self): if not self.tempCallData.isEmpty(): if self.tempCallData.count() == 5: if str(self.tempCallData.at(1).toString()) == "order": if self.tempCallData.at(0).toBool( ) == True: #// call direct obsolete, betterbetter to use recursivecall if not self.tempCallFunctionArgs.isEmpty(): nameObject = self.tempCallFunctionArgs.at( 0).toString() nameFunction = self.tempCallFunctionArgs.at( 1).toString() root = self.m_engine.rootObjects()[0] object_qml = root.findChild(QObject, nameObject) if self.tempCallFunctionArgs.at(2).isArray(): args = self.tempCallFunctionArgs.at( 2).toArray() #.toVariantList() if args.count() == 0: QMetaObject.invokeMethod( object_qml, nameFunction) else: root.setProperty("argsFucntionLastCall", args) QMetaObject.invokeMethod( object_qml, nameFunction) # https://bugreports.qt.io/browse/PYSIDE-1262 # Q_ARG missing, invokeMethod doesn't work currently with arguments in PySide2. # if args.count()==1: # print("\nnnn",args.at(0),"\nnnnn") # QMetaObject.invokeMethod(object_qml, nameFunction, # QGenericArgument(QByteArray(b'QVariant'), 69)) # # if args.count()==2: # QMetaObject.invokeMethod(object_qml, nameFunction, # QGenericArgument('QVariant', args.at(0)), # QGenericArgument('QVariant', args.at(1))) # # if args.count()==3: # QMetaObject.invokeMethod(object_qml, nameFunction, # QGenericArgument('QVariant', args.at(0)), # QGenericArgument('QVariant', args.at(1)), # QGenericArgument('QVariant', args.at(2))) # # if args.count()==4: # QMetaObject.invokeMethod(object_qml, nameFunction, # QGenericArgument('QVariant', args.at(0)), # QGenericArgument('QVariant', args.at(1)), # QGenericArgument('QVariant', args.at(2)), # QGenericArgument('QVariant', args.at(3))) # else: self.call( self.tempCallData.at(2).toString(), self.tempCallData.at(3).toString(), self.tempCallData.at(4).toArray()) if self.tempCallData.at(1).toString() == "report": self.runReport( self.tempCallData.at(2).toString(), self.tempCallData.at(3).toString(), self.tempCallData.at(4).toArray()) self.tempCallData = QJsonArray() self.tempCallFunctionArgs = QJsonArray() @Slot("QNetworkReply*") def replyFinishedOrder(self, reply): if self.boolDirect == False: data = reply.readAll() self.processingData(data, reply) # reply.deleteLater() @Slot("QNetworkReply*", "const QList<QSslError> &") def slotSslError(self, reply, errors): for error in errors: print("ssl error", error.errorString()) # foreach (const QSslError &error, errors) # fprintf(stderr, "SSL error: %s\n", qPrintable(error.errorString())); signalResponse = Signal(str, int, "QJsonObject") def getId(self): self.mid += 1 return self.mid #QUrl redirectUrlComp(const QUrl& possibleRedirectUrl,const QUrl& oldRedirectUrl) const; def redirectUrlComp(self, possibleRedirectUrl, oldRedirectUrl): redirectUrl = QUrl() if possibleRedirectUrl.isEmpty( ) == False and possibleRedirectUrl != oldRedirectUrl: redirectUrl = possibleRedirectUrl return redirectUrl @Slot(result=bool) def isRunning(self): if self.boolRecursive == True: return True return self.boolRun @Slot(str, str, str, str, str) @Slot(str, str, str, str, str, bool) def openConect(self, usu, passw, host, port, dbase, direct=False): self.usuario = usu self.password = passw self.mhost = host self.mdbase = dbase self.mport = port url = host + ":" + port + "/" + dbase + "/" self.urlServer = QUrl(url) self.token.clear() self.boolConnect = False marray = QJsonArray() if self.versionct == "4": marray.append(self.usuario) marray.append(self.password) if direct: return self.callDirect("open@", "common.db.login", marray) else: self.call("open@", "common.db.login", marray) else: marray.append(self.usuario) marray.append({"password": self.password}) # mapass = QJsonValue({"password",self.password}) # marray.append(mapass.toObject()) if direct: return self.callDirect("open@", "common.db.login", marray) else: self.call("open@", "common.db.login", marray) @Slot(str, str, QJsonArray) def call(self, pid, method, par): self.clearMessagesWarning() if self.boolRun == False: self.boolRun = True self.boolDirect = False self.mtypeCall = "order" self.mpid = pid self.mmethod = method self.mparams = par self.initOrderConnect() else: if pid != self.mpid: self.signalResponse.emit("run@", 8, {}) @Slot() def initOrderConnect(self): bparams = self.prepareParams() request = self.prepareRequest() self.managerAccess.post(request, bparams) # reply.readyRead.connect(self.slotReadyRead) # reply.error[QNetworkReply.NetworkError].connect(self..slotError) # reply.sslErrors.connect(self.slotSslErrors) @Slot(QJsonArray) def saveFunction(self, by403): if by403.count() == 3: #objectqml functon args self.tempCallFunctionArgs = by403 else: self.tempCallFunctionArgs = QJsonArray() @Slot(str, str, QJsonArray, result="QJsonObject") def callDirect(self, pid, method, par): if self.boolRecursive == False: self.clearMessagesWarning() resultObject = {} if self.boolRun == False: self.boolRun = True self.boolDirect = True self.mtypeCall = "order" self.mpid = pid self.mmethod = method self.mparams = par bparams = self.prepareParams() request = self.prepareRequest() reply = self.data_request(request, bparams) data = reply.readAll() ## QByteArray parseError = QJsonParseError() resultObject["data"] = "error" document = QJsonDocument.fromJson(data, parseError) error = reply.error() statusCode = reply.attribute( QNetworkRequest.HttpStatusCodeAttribute) if QNetworkReply.NoError == error: if parseError.error == True: resultObject["data"] = "error" else: if document.isObject(): jv = document.object() if jv.__contains__("result"): resultObject["data"] = jv else: if self.boolRecursive: if jv.__contains__("error"): if jv["error"].__class__() == []: if jv["error"].__contains__( "UserWarning" ) or jv["error"][0].__contains__( "403") or jv["error"][ 0].__contains__("401"): resultObject["data"] = jv elif self.mpid == "open@": resultObject["data"] = jv else: if document.isArray() == True: resultObject["data"] = document.array() else: resultObject["data"] = "error" else: if statusCode == 401 or statusCode == 403: resultObject["data"] = statusCode self.processingData(data, reply) # cath return resultObject else: resultObject["data"] = "error" if pid != self.mpid: self.signalResponse.emit("run@", 8, {}) return resultObject def data_request(self, request, bparams): connection_loop = QEventLoop() QObject.connect(self.managerAccess, SIGNAL("finished( QNetworkReply* )"), connection_loop, SLOT("quit()")) reply = self.managerAccess.post(request, bparams) connection_loop.exec_() #sleep #reply->bytesAvailable(); #reply.deleteLater() return reply def processingData(self, data, reply): parseError = QJsonParseError() error = reply.error() errorString = reply.errorString() statusCode = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) fraseStatusCode = reply.attribute( QNetworkRequest.HttpReasonPhraseAttribute) redirectUrl = QUrl( reply.attribute(QNetworkRequest.RedirectionTargetAttribute)) redirectUrlFix = self.redirectUrlComp(redirectUrl, self.urlServer) # print(errorString, statusCode) resultObject = { "status": statusCode, "fraseStatus": fraseStatusCode, "errorString": errorString } result = False # QJsonValue result=false; Bug QJsonValue(True) if self.mpid == "open@": resultObject["credentials"] = False if QNetworkReply.NoError == error: if redirectUrlFix.isEmpty() == False: if self.boolDirect == False: print("se redireciona", redirectUrl) self.urlServer = redirectUrl self.initOrderConnect() self.signalResponse.emit(self.mpid, 1, resultObject) else: document = QJsonDocument.fromJson(data, parseError) if parseError.error == True: resultObject["data"] = data.__str__() self.signalResponse.emit(self.mpid, 4, resultObject) #redireccion else: if document.isArray() == True: result = document.array() else: #supuestamente es un object json if self.mpid == "open@": if document.object().__contains__( "result") == True: if document.object()["result"].__class__( ) == []: if document.object()["result"].__len__( ) == 2: self.token = document.object( )["result"] self.boolConnect = True self.intCountConnect += 1 resultObject["credentials"] = True result = document.object() resultObject["data"] = result if self.boolDirect == False: self.signalResponse.emit(self.mpid, 2, resultObject) #ok else: #and report if self.mpid == "open@" and result.__contains__( "error") == False and self.boolRecursive == False: resultObject["extra"] = "direct" self.signalResponse.emit(self.mpid, 2, resultObject) # elif self.mpid=="open@" and result.__contains__("error")==False and resultObject["credentials"] == False and self.boolRecursive == True: # self.signalResponse.emit(self.mpid, 2, resultObject) elif result.__contains__("error") == True: if self.boolRecursive == True: if result["error"].__class__( ) == [] and result["error"].__contains__( "UserWarning" ) == False and result["error"][0].__contains__( "403") == False and result["error"][ 0].__contains__("401") == False: self.signalResponse.emit( self.mpid, 2, resultObject) elif document.isObject(): self.signalResponse.emit(self.mpid, 2, resultObject) else: print(error, statusCode, errorString) #, resultObject) if self.boolRecursive == True: if resultObject['status'] != 401 and resultObject[ 'status'] != 403: self.signalResponse.emit( self.mpid, 3, resultObject) #//error comunicacion else: self.signalResponse.emit(self.mpid, 3, resultObject) #//error comunicacion self.boolRun = False reply.deleteLater() # void processingData(const QByteArray &data, QNetworkReply *reply); @Slot(str, str, QJsonArray) def runReport(self, pid, method, par): self.boolDirect = True self.mtypeCall = "report" self.mpid = pid self.mmethod = method self.mparams = par # bparams = self.prepareParams() request = self.prepareRequest() # reply = self.data_request(request, bparams) data = reply.readAll() parseError = QJsonParseError() resultObject = {} resultObject["data"] = "error" document = QJsonDocument.fromJson(data, parseError) if parseError.error == True: resultObject["data"] = "error" else: if document.isObject(): jv = document.object() if jv.__contains__( "result") == True and jv["result"].__class__() == []: #tryton 4.0 #'result': ['pdf', {'base64':wwwwww, '__class__':'bytes'}, False,'Printis'] jre = jv["result"] namesecs = "tryton_" + self.mpid + str( QDateTime.currentMSecsSinceEpoch()) + "." + jre[0] mdir = QDir(self.mDir + QDir.separator() + "tempReports") if mdir.exists() == False: s = QDir(self.mDir) s.mkdir("tempReports") filename = self.mDir + QDir.separator( ) + "tempReports" + QDir.separator() + namesecs file = QFile(filename) if file.open(QIODevice.WriteOnly) == False: #error self.signalResponse.emit(self.mpid, 7, {}) print("error", filename, file.errorString()) else: bafile = QByteArray.fromBase64( jre[1]["base64"].encode()) file.write(bafile) file.close() QDesktopServices.openUrl(QUrl(filename)) else: if document.isArray() == True: self.signalResponse.emit(self.mpid, 7, {}) self.processingData(data, reply) def prepareRequest(self): request = QNetworkRequest() request.setUrl(self.urlServer) request.setRawHeader(QByteArray(b"content-type"), QByteArray(b"application/json")) request.setRawHeader(QByteArray(b"charset"), QByteArray(b"utf-8")) if self.mpid != "open@": tokenStr = self.usuario + ":" + str(int( self.token[0])) + ":" + str( self.token[1]) if self.token != [] else "" tokenByte = QByteArray(tokenStr.encode()) tokenByteComplete = QByteArray(b"Session ") + tokenByte.toBase64() request.setRawHeader(QByteArray(b"authorization"), tokenByteComplete) return request def prepareParams(self): objParams = { "method": self.mmethod, "params": self.mparams, "id": self.getId() } return QJsonDocument(objParams).toJson(QJsonDocument.Compact) @Slot("QJsonObject") def setPreferences(self, preferences): self.preferences = preferences @Slot(str, str, QJsonArray, result="QJsonObject") def recursiveCall(self, pid, method, par): self.clearMessagesWarning() self.boolRecursive = True result = self.callDirect(pid, method, par) if result["data"].__contains__("result"): if self.mpid != "open@": self.boolRecursive = False return result not_complete = True while not_complete: reValue = result["data"] if reValue.__class__() == 0 and (reValue == 401 or reValue == 403): mok = False textinput = self.tr("Re-enter Password:"******"Password", textinput, QLineEdit.Password) if mok: result = self.openConect(self.usuario, inputPass, self.mhost, self.mport, self.mdbase, True) else: not_complete = False result['data'] = 'error' self.boolRecursive = False root = self.m_engine.rootObjects()[0] QMetaObject.invokeMethod(root, "backLogin") elif reValue.__class__() == {}: if reValue.__contains__("result"): if self.mpid != "open@": not_complete = False else: if self.boolConnect: result = self.callDirect(pid, method, par) else: mok = False textinput = self.tr( "Incorrect, Re-enter Password:"******"Incorrect Password", textinput, QLineEdit.Password) if mok: result = self.openConect( self.usuario, inputPass, self.mhost, self.mport, self.mdbase, True) else: not_complete = False self.boolRecursive = False result['data'] = 'error' root = self.m_engine.rootObjects()[0] QMetaObject.invokeMethod(root, "backLogin") elif reValue.__contains__("error"): if reValue["error"].__class__() == []: if 'UserWarning' in reValue["error"]: cb = QCheckBox("Always ignore this warning.") msgBox = QMessageBox() msgBox.setText(reValue["error"][1][0]) msgBox.setInformativeText(reValue["error"][1][1]) msgBox.setStandardButtons(QMessageBox.No | QMessageBox.Yes) msgBox.setDefaultButton(QMessageBox.Yes) msgBox.setCheckBox(cb) rbox = msgBox.exec_() if rbox == QMessageBox.Yes: result = self.callDirect( pid, 'model.res.user.warning.create', [[{ 'always': cb.isChecked(), 'user': self.token[0], 'name': reValue["error"][1][0] }], self.preferences]) if result["data"].__contains__("result"): result = self.callDirect(pid, method, par) else: not_complete = False result['data'] = 'error' elif reValue["error"][0].__contains__( "403") or reValue["error"][0].__contains__( "401"): mok = False textinput = self.tr("Re-enter Password:"******"error"][0].__contains__("401"): textinput = "Authorization Required \n" + textinput inputPass, mok = QInputDialog.getText( None, "Password", textinput, QLineEdit.Password) if mok: result = self.openConect( self.usuario, inputPass, self.mhost, self.mport, self.mdbase, True) else: not_complete = False result['data'] = 'error' self.boolRecursive = False root = self.m_engine.rootObjects()[0] QMetaObject.invokeMethod(root, "backLogin") else: not_complete = False else: not_complete = False else: not_complete = False self.boolRecursive = False return result
class ModelJson(QObjectListModel): def __init__(self, objname, parent=None): QObjectListModel.__init__(self, parent) self.setObjectName(str(objname)) self.m_locale = QLocale("es") #temp, auto changue when login #self.m_proxy = ProxyModelJson() self.m_order = "" self.boolMetadata = False self.m_fields = QJsonArray() #[]#QJsonArray self.m_fieldsPoint = [] #5.2up self.m_maxLimit = 100 self.m_domain = QJsonArray() #[]#QJsonArray self.m_orderTryton = QJsonArray() #[]#QJsonArray self.m_preferences = {} self.m_qjsonnetwork = QJsonNetwork() self.m_fieldsFormatDecimal = [] #QJsonArray self.m_fieldsFormatDateTime = [] #QJsonArray self.m_model_method_search = "" self.m_hasIndexOfId = {} self.m_engine = None #QQmlApplicationEngine() self.autoBusy = True self.boolSynchro = True # add synchronous call (calldirect), best performance! def prepareDeletion(self): if self.boolSynchro == False: self.m_qjsonnetwork.signalResponse.disconnect(self.slotJsonConnect) self.setFields(QJsonArray()) self.clear() @Slot(int, result=int) def indexisOfId(self, mid): #el index del record en el modelo, no en el proxy return self.m_hasIndexOfId.get(mid, -1) @Slot(bool) def activateMetadata(self, meta): self.boolMetadata = meta @Slot("QJsonObject") def setPreferences(self, preferences): self.m_preferences = preferences @Slot(str) def setOrderInternal( self, order ): # only proxy, defaul false, no es necesario con order tryton self.m_order = order if self.m_order != "": self.m_proxy.setSortData("order") self.m_proxy.setSortLocaleAware(True) self.m_proxy.sort(0, Qt.AscendingOrder) self.m_proxy.setSortRole(self.ObjectRole) @Slot(str, QJsonArray, int, QJsonArray, QJsonArray) def setSearch(self, model_method_search, domain, maxlimit, ordertryton, fields): self.m_maxLimit = maxlimit self.m_domain = domain #.toVariantList() self.m_orderTryton = ordertryton #.toVariantList() self.setFields(fields) self.m_model_method_search = model_method_search @Slot(str) def setModelMethod(self, model_method_search): self.m_model_method_search = model_method_search @Slot(QJsonArray) def setDomain(self, domain): self.m_domain = domain @Slot(int) def setMaxLimit(self, maxlimit): self.m_maxLimit = maxlimit @Slot(QJsonArray) def setOrder(self, ordertryton): self.m_orderTryton = ordertryton @Slot(QJsonArray) def setFields(self, fields): # si es [], son todos self.m_fields = fields self.m_fieldsPoint = [] for f in self.m_fields.toVariantList(): if f.find(".") != -1: self.m_fieldsPoint.append(f) @Slot(str) def setLanguage(self, language): self.m_locale = QLocale(language) @Slot() @Slot(QJsonArray) @Slot(QJsonArray, int) def find(self, domain=QJsonArray(), maxlimit=-1): # if domain!=QJsonArray(): self.m_domain = domain #.toVariantList() self.initSearch(maxlimit) @Slot() @Slot(int) def initSearch(self, maxlimit=-1): self.clear() self.m_hasIndexOfId = {} self.nextSearch(maxlimit) def addResult(self, result, update=False): #QJsonArray jsonobj = {} mis = self._count() for res in result: mid = int(res["id"]) mapJsonDoc = res jsonobj = {} order = "" if self.m_order == "" else mapJsonDoc[ self.m_order].strip() metadata = "" jsonobj = mapJsonDoc if self.boolMetadata: doct = QJsonDocument(mapJsonDoc) metadata = doct.toJson( QJsonDocument.Compact).data().decode("utf-8") # if self.m_fields!= QJsonArray(): if len(self.m_fieldsPoint) > 0: fieldsdoc = list(mapJsonDoc) for fp in self.m_fieldsPoint: if fp not in fieldsdoc: lfp = fp.split(".") for li in range(len(lfp) - 1): lfp[li] = lfp[li] + "." temp = jsonobj[lfp[0]] for c in lfp[1:]: if temp != None: temp = temp[c] jsonobj[fp] = temp for vp in self.m_fieldsFormatDecimal: v = vp[0] if jsonobj.__contains__(v): if jsonobj[v] != None: if jsonobj[v].__contains__("decimal"): jsonobj[v + "_format"] = self.m_locale.toString( float(jsonobj[v]["decimal"]), 'f', vp[1]) #add suport else: jsonobj[v + "_format"] = "" else: jsonobj[v + "_format"] = "" for v in self.m_fieldsFormatDateTime: mfield = v[0] mformat = v[1] if jsonobj.__contains__(mfield): mdateTime = QDateTime() if jsonobj[mfield] != None: if jsonobj[mfield].__contains__("__class__"): if jsonobj[mfield]["__class__"] == "date": mdateTime = QDateTime( QDate(jsonobj[mfield]["year"], jsonobj[mfield]["month"], jsonobj[mfield]["day"]), QTime()) if jsonobj[mfield]["__class__"] == "datetime": mdateTime = QDateTime( QDate(jsonobj[mfield]["year"], jsonobj[mfield]["month"], jsonobj[mfield]["day"]), QTime(jsonobj[mfield]["hour"], jsonobj[mfield]["minute"], jsonobj[mfield]["second"])) jsonobj[mfield + "_format"] = mdateTime.toString(mformat) else: jsonobj[mfield + "_format"] = "" else: jsonobj[mfield + "_format"] = "" if update == False: dataJson = DataJson(mid, order, jsonobj, metadata, self) self.append(dataJson) self.m_hasIndexOfId[mid] = mis mis += 1 else: index = self.indexisOfId(mid) if index != -1: self.at(index).setProperty("order", order) self.at(index).setProperty("json", jsonobj) self.at(index).setProperty("metadata", metadata) @Slot() @Slot(int) def nextSearch(self, maxlimit=-1): # metodo asincronico self.openBusy() limit = self.m_maxLimit if maxlimit != -1: limit = maxlimit params = QJsonArray() params.append(self.m_domain) params.append(self._count()) params.append(limit) params.append(self.m_orderTryton) params.append(self.m_fields) params.append(self.m_preferences) if self.boolSynchro: # result = self.m_qjsonnetwork.callDirect("nextSearch"+self.objectName(), self.m_model_method_search+".search_read" ,params) result = self.m_qjsonnetwork.recursiveCall( "nextSearch" + self.objectName(), self.m_model_method_search + ".search_read", params) reValue = result["data"] if reValue.__class__() == {}: if reValue.__contains__("result"): if reValue["result"].__class__() == []: self.addResult(reValue["result"]) self.closeBusy() else: self.m_qjsonnetwork.call( "nextSearch" + self.objectName(), self.m_model_method_search + ".search_read", params) @Slot(QJsonArray) # metodo asincronico def updateRecords(self, ids): #update record with tryton, self.openBusy() params = QJsonArray() params.append(ids) params.append(self.m_fields) params.append(self.m_preferences) if self.boolSynchro: # result = self.m_qjsonnetwork.callDirect("updateRecords"+self.objectName(), self.m_model_method_search+".read" ,params) result = self.m_qjsonnetwork.recursiveCall( "updateRecords" + self.objectName(), self.m_model_method_search + ".read", params) reValue = result["data"] if reValue.__class__() == {}: if reValue.__contains__("result"): if reValue["result"].__class__() == []: self.addResult(reValue["result"], True) self.closeBusy() else: self.m_qjsonnetwork.call("updateRecords" + self.objectName(), self.m_model_method_search + ".read", params) @Slot(int) def removeItem(self, mid): # elimina solo en memory, no afecta a base datos index = self.indexisOfId(mid) if index != -1: self.m_hasIndexOfId.pop(mid) self.removeAt(index) @Slot(QJsonArray) def addFieldFormatDecimal(self, fields): #ModelArticulo.addFieldFormatDecimal(['total_amount']); self.m_fieldsFormatDecimal = [] for v in fields.toVariantList(): if v.__class__() == '': self.m_fieldsFormatDecimal.append([v, 2]) elif v.__class__() == []: if v.__len__() == 2: if v[0].__class__() == '' and v[1].__class__() == 0: self.m_fieldsFormatDecimal.append(v) @Slot(QJsonArray) def addFieldFormatDateTime(self, fields): #ModelArticulo.addFieldFormatDateTime([['invoice_date','dd/MM/yy'],['create_date','dd/MM/yy hh:mm:ss']]); self.m_fieldsFormatDateTime = [] for v in fields.toVariantList(): if v.__class__() == []: if v.__len__() == 2: if v[0].__class__() == '' and v[1].__class__() == '': self.m_fieldsFormatDateTime.append(v) signalResponse = Signal(str, int) signalResponseData = Signal(str, int, "QJsonObject") #QJsonObject = dict @Slot(str, int, dict) # obsoleto mejor usar calldirect! def slotJsonConnect(self, pid, option, data): #cath datos de call, if pid == "nextSearch" + self.objectName(): if option == 2: #result dataObject = data["data"] if dataObject.__contains__("result"): if dataObject["result"].__class__() == []: self.addResult(dataObject["result"]) self.signalResponseData.emit( "nextSearch", option, {}) # ok envio emit de confirmacion else: #print("la data",data) self.signalResponseData.emit( "nextSearch", 5, data) #puede ser un error 403 timeout else: self.signalResponseData.emit("nextSearch", option, data) #dejo cruzar los datos if pid == "updateRecords" + self.objectName(): if option == 2: #result dataObject = data["data"] if dataObject.__contains__("result"): if dataObject["result"].__class__() == []: self.addResult(dataObject["result"], True) self.signalResponseData.emit( "updateRecords", option, {}) # ok envio emit de confirmacion else: #print("la data",data) self.signalResponseData.emit( "updateRecords", 5, data) #puede ser un error 403 timeout else: self.signalResponseData.emit("nextSearch", option, data) #dejo cruzar los datos def setProxy(self, proxp): self.m_proxy = proxp def setJsonConnect(self, jchac): #=None):#(QJsonNetwork *jchac=nullptr); self.m_qjsonnetwork = jchac self.connectSlotJC() def connectSlotJC(self): if self.boolSynchro == False: self.m_qjsonnetwork.signalResponse.connect(self.slotJsonConnect) # self.connect(self.m_qjsonnetwork, SIGNAL(signalResponse(QString,int,QJsonObject)), # self, SLOT(slotJsonConnect(QString,int,QJsonObject))); def setEngine(self, engine): self.m_engine = engine def openBusy(self): if self.autoBusy: if self.m_engine != None: root = self.m_engine.rootObjects()[0] QMetaObject.invokeMethod(root, "openBusy") def closeBusy(self): if self.autoBusy: if self.m_engine != None: root = self.m_engine.rootObjects()[0] QMetaObject.invokeMethod(root, "closeBusy") @Slot(bool) def setAutoBusy(self, busy): self.autoBusy = busy @Slot(bool) def setSynchro(self, syn): self.boolSynchro = syn self.connectSlotJC() def initProxy(self): if self.m_order != "": self.m_proxy.setSortData("order") self.m_proxy.setSortLocaleAware(True) self.m_proxy.sort(0, Qt.AscendingOrder) self.m_proxy.setSortRole(self.ObjectRole) self.m_proxy.setFilterRoles("metadata") self.m_proxy.setFilterRole(self.ObjectRole) self.m_proxy.setDynamicSortFilter(True) self.m_proxy.setSourceModel(self) def isJsonObject(self, mtextdoc): pass
def nextSearch(self, maxlimit=-1): # metodo asincronico self.openBusy() limit = self.m_maxLimit if maxlimit != -1: limit = maxlimit params = QJsonArray() params.append(self.m_domain) params.append(self._count()) params.append(limit) params.append(self.m_orderTryton) params.append(self.m_fields) params.append(self.m_preferences) if self.boolSynchro: # result = self.m_qjsonnetwork.callDirect("nextSearch"+self.objectName(), self.m_model_method_search+".search_read" ,params) result = self.m_qjsonnetwork.recursiveCall( "nextSearch" + self.objectName(), self.m_model_method_search + ".search_read", params) reValue = result["data"] if reValue.__class__() == {}: if reValue.__contains__("result"): if reValue["result"].__class__() == []: self.addResult(reValue["result"]) self.closeBusy() else: self.m_qjsonnetwork.call( "nextSearch" + self.objectName(), self.m_model_method_search + ".search_read", params)
def find(self, domain=QJsonArray(), maxlimit=-1): # if domain!=QJsonArray(): self.m_domain = domain #.toVariantList() self.initSearch(maxlimit)
def prepareDeletion(self): if self.boolSynchro == False: self.m_qjsonnetwork.signalResponse.disconnect(self.slotJsonConnect) self.setFields(QJsonArray()) self.clear()
def runLastCall(self): if not self.tempCallData.isEmpty(): if self.tempCallData.count() == 5: if str(self.tempCallData.at(1).toString()) == "order": if self.tempCallData.at(0).toBool( ) == True: #// call direct obsolete, betterbetter to use recursivecall if not self.tempCallFunctionArgs.isEmpty(): nameObject = self.tempCallFunctionArgs.at( 0).toString() nameFunction = self.tempCallFunctionArgs.at( 1).toString() root = self.m_engine.rootObjects()[0] object_qml = root.findChild(QObject, nameObject) if self.tempCallFunctionArgs.at(2).isArray(): args = self.tempCallFunctionArgs.at( 2).toArray() #.toVariantList() if args.count() == 0: QMetaObject.invokeMethod( object_qml, nameFunction) else: root.setProperty("argsFucntionLastCall", args) QMetaObject.invokeMethod( object_qml, nameFunction) # https://bugreports.qt.io/browse/PYSIDE-1262 # Q_ARG missing, invokeMethod doesn't work currently with arguments in PySide2. # if args.count()==1: # print("\nnnn",args.at(0),"\nnnnn") # QMetaObject.invokeMethod(object_qml, nameFunction, # QGenericArgument(QByteArray(b'QVariant'), 69)) # # if args.count()==2: # QMetaObject.invokeMethod(object_qml, nameFunction, # QGenericArgument('QVariant', args.at(0)), # QGenericArgument('QVariant', args.at(1))) # # if args.count()==3: # QMetaObject.invokeMethod(object_qml, nameFunction, # QGenericArgument('QVariant', args.at(0)), # QGenericArgument('QVariant', args.at(1)), # QGenericArgument('QVariant', args.at(2))) # # if args.count()==4: # QMetaObject.invokeMethod(object_qml, nameFunction, # QGenericArgument('QVariant', args.at(0)), # QGenericArgument('QVariant', args.at(1)), # QGenericArgument('QVariant', args.at(2)), # QGenericArgument('QVariant', args.at(3))) # else: self.call( self.tempCallData.at(2).toString(), self.tempCallData.at(3).toString(), self.tempCallData.at(4).toArray()) if self.tempCallData.at(1).toString() == "report": self.runReport( self.tempCallData.at(2).toString(), self.tempCallData.at(3).toString(), self.tempCallData.at(4).toArray()) self.tempCallData = QJsonArray() self.tempCallFunctionArgs = QJsonArray()
def saveFunction(self, by403): if by403.count() == 3: #objectqml functon args self.tempCallFunctionArgs = by403 else: self.tempCallFunctionArgs = QJsonArray()