diff --git a/3rdParty/TargomanDBM b/3rdParty/TargomanDBM index 75bcb7da..3b26e253 160000 --- a/3rdParty/TargomanDBM +++ b/3rdParty/TargomanDBM @@ -1 +1 @@ -Subproject commit 75bcb7da44eb84619c39c2be5b87a6da9f9bb03d +Subproject commit 3b26e2530c6d9292d5f8eb83c32906eb78701f23 diff --git a/App/Server/APICache.hpp b/App/Server/APICache.hpp index b6e0271e..aba3137e 100644 --- a/App/Server/APICache.hpp +++ b/App/Server/APICache.hpp @@ -41,27 +41,27 @@ struct stuCacheValue { QVariant Value; qint32 TTL; - stuCacheValue(){} - stuCacheValue(const QVariant& _value, qint32 _ttl) : InsertionTime(QTime::currentTime()),Value(_value), TTL(_ttl){} - stuCacheValue(const stuCacheValue& _other) : InsertionTime(_other.InsertionTime),Value(_other.Value), TTL(_other.TTL){} + stuCacheValue() { ; } + stuCacheValue(const QVariant& _value, qint32 _ttl) : InsertionTime(QTime::currentTime()),Value(_value), TTL(_ttl) { ; } + stuCacheValue(const stuCacheValue& _other) : InsertionTime(_other.InsertionTime),Value(_other.Value), TTL(_other.TTL) { ; } }; typedef QHash Cache_t; class InternalCache { public: - static void setValue(const QString& _key, const QVariant& _value, qint32 _ttl){ + static void setValue(const QString& _key, const QVariant& _value, qint32 _ttl) { QMutexLocker Locker(&InternalCache::Lock); - if(InternalCache::Cache.size() < static_cast(ServerConfigs::MaxCachedItems.value())) + if (InternalCache::Cache.size() < static_cast(ServerConfigs::MaxCachedItems.value())) InternalCache::Cache.insert(_key, stuCacheValue(_value, _ttl)); } - static QVariant storedValue(const QString& _key){ + static QVariant storedValue(const QString& _key) { QMutexLocker Locker(&InternalCache::Lock); auto StoredValue = InternalCache::Cache.find(_key); - if(StoredValue == InternalCache::Cache.end()) + if (StoredValue == InternalCache::Cache.end()) return QVariant(); Locker.unlock(); - if(StoredValue->InsertionTime.secsTo(QTime::currentTime()) > StoredValue->TTL) + if (StoredValue->InsertionTime.secsTo(QTime::currentTime()) > StoredValue->TTL) return QVariant(); return StoredValue->Value; } @@ -76,13 +76,13 @@ class InternalCache class CentralCache { public: - static bool isValid(){return CentralCache::Connector.isNull() == false;} - static void setup(intfCacheConnector* _connector){ CentralCache::Connector.reset(_connector); } - static void setValue(const QString& _key, const QVariant& _value, qint32 _ttl){ - if(CentralCache::Connector.isNull() == false) + static bool isValid() {return CentralCache::Connector.isNull() == false;} + static void setup(intfCacheConnector* _connector) { CentralCache::Connector.reset(_connector); } + static void setValue(const QString& _key, const QVariant& _value, qint32 _ttl) { + if (CentralCache::Connector.isNull() == false) CentralCache::Connector->setKeyVal(_key, _value, _ttl); } - static QVariant storedValue(const QString& _key){ + static QVariant storedValue(const QString& _key) { return CentralCache::Connector.isNull() ? QVariant() : CentralCache::Connector->getValue(_key); } diff --git a/App/Server/OpenAPIGenerator.cpp b/App/Server/OpenAPIGenerator.cpp index 94f8264a..ae2ed2b1 100644 --- a/App/Server/OpenAPIGenerator.cpp +++ b/App/Server/OpenAPIGenerator.cpp @@ -31,22 +31,18 @@ using namespace DBM; QJsonObject OpenAPIGenerator::CachedJson; -QJsonObject initializeObject(const QString &_host = "127.0.0.1", const quint16 _port = 80) -{ +QJsonObject initializeObject(const QString &_host = "127.0.0.1", const quint16 _port = 80) { - if (ServerConfigs::BaseOpenAPIObjectFile.value().size()) - { + if (ServerConfigs::BaseOpenAPIObjectFile.value().size()) { QFile File(ServerConfigs::BaseOpenAPIObjectFile.value()); File.open(QIODevice::ReadOnly); if (File.isReadable() == false) throw exTargomanAPI("Unable to open: <" + ServerConfigs::BaseOpenAPIObjectFile.value() + "> for reading"); QJsonDocument JsonDoc = QJsonDocument::fromBinaryData(File.readAll()); - if(JsonDoc.isNull() || JsonDoc.isObject() == false) + if (JsonDoc.isNull() || JsonDoc.isObject() == false) throw exTargomanAPI("Invalid json reading from: <" + ServerConfigs::BaseOpenAPIObjectFile.value() + ">"); return JsonDoc.object(); - } - else - { + } else { QString HostPort; if (_port == 80) HostPort = _host; @@ -83,10 +79,8 @@ QJsonObject initializeObject(const QString &_host = "127.0.0.1", const quint16 _ } } -QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _port) -{ - if (OpenAPIGenerator::CachedJson.isEmpty() == false) - { +QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _port) { + if (OpenAPIGenerator::CachedJson.isEmpty() == false) { QJsonObject Return = OpenAPIGenerator::CachedJson; QString HostPort; @@ -107,7 +101,7 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ QJsonObject PathsObject; QJsonArray TagsArray; - foreach(const QString& Key, RESTAPIRegistry::Registry.keys()){ + foreach(const QString& Key, RESTAPIRegistry::Registry.keys()) { QString PathString = Key.split(" ").last(); QString HTTPMethod = Key.split(" ").first().toLower(); QStringList PKInPathStorage; @@ -125,12 +119,11 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ APIObject->BaseMethod.parameterNames().at(i); }; - auto mapTypeToValidOpenAPIType = [](enuVarComplexity _complexity, QString _typeName){ + auto mapTypeToValidOpenAPIType = [](enuVarComplexity _complexity, QString _typeName) { if (_typeName.startsWith(TAPI_HELEPER_QSP_M2STR_PREFIX)) _typeName = _typeName.mid(sizeof(TAPI_HELEPER_QSP_M2STR_PREFIX), _typeName.size() - static_cast(sizeof(TAPI_HELEPER_QSP_M2STR_PREFIX)) - 1); - switch(_complexity) - { + switch (_complexity) { case COMPLEXITY_Number: case COMPLEXITY_Boolean: case COMPLEXITY_Integral: @@ -149,7 +142,7 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ case COMPLEXITY_Object: return "object"; case COMPLEXITY_File: - if(_typeName == "TAPI::Files_t") + if (_typeName == "TAPI::Files_t") return "string"; return "file"; } @@ -160,31 +153,26 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ if (_typeName.startsWith(TAPI_HELEPER_QSP_M2STR_PREFIX)) _typeName = _typeName.mid(sizeof(TAPI_HELEPER_QSP_M2STR_PREFIX), _typeName.size() - static_cast(sizeof(TAPI_HELEPER_QSP_M2STR_PREFIX)) - 1); - switch(_complexity) - { + switch (_complexity) { case COMPLEXITY_Number: case COMPLEXITY_Integral: if (_typeName.endsWith("int8")) { _paramSpecs["format"] = "int32"; _paramSpecs["minimum"] = _typeName.startsWith("uint") ? 0 : -128; _paramSpecs["maximum"] = _typeName.startsWith("uint") ? 255 : 127; - } - else if (_typeName.endsWith("int16")) { + } else if (_typeName.endsWith("int16")) { _paramSpecs["format"] = "int32"; _paramSpecs["minimum"] = _typeName.startsWith("uint") ? 0 : -32768 ; _paramSpecs["maximum"] = _typeName.startsWith("uint") ? 65535 : 32767; - } - else if (_typeName.endsWith("int32")) { + } else if (_typeName.endsWith("int32")) { _paramSpecs["format"] = "int32"; if (_typeName.startsWith("uint")) _paramSpecs["minimum"] = 0; - } - else if (_typeName.endsWith("int64")) { + } else if (_typeName.endsWith("int64")) { _paramSpecs["format"] = "int64"; if (_typeName.startsWith("uint")) _paramSpecs["minimum"] = 0; - } - else if (_typeName.endsWith("float")) _paramSpecs["format"] = "int64"; + } else if (_typeName.endsWith("float")) _paramSpecs["format"] = "int64"; else if (_typeName.endsWith("double")) _paramSpecs["format"] = "double"; break; case COMPLEXITY_Complex: @@ -214,31 +202,31 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ ParamSpecs["description"] = (_argMan->isNullable() ? "Null to keep as is or " : "") + _argMan->description(_fields); ParamSpecs["type"] = mapTypeToValidOpenAPIType(_argMan->complexity(), _typeName); addExtraParamsByType(ParamSpecs, _argMan->complexity(), _typeName); - if(_argMan->isNullable()) + if (_argMan->isNullable()) ParamSpecs["nullable"] = true; - if(_argMan->complexity() == COMPLEXITY_Enum) + if (_argMan->complexity() == COMPLEXITY_Enum) ParamSpecs["enum"] = QJsonArray::fromStringList(_argMan->options()); - if(_defaultValue.isValid() && _defaultValue != QRequired){ + if (_defaultValue.isValid() && _defaultValue != QRequired) { ParamSpecs["default"] = _defaultValue == QNull || _argMan->isNullable() ? QJsonValue() : _defaultValue.toString(); - if(addExample){ - if(_argMan->isNullable()) + if (addExample) { + if (_argMan->isNullable()) ParamSpecs["example"] = QJsonValue(); - if(_argMan->complexity() == COMPLEXITY_Object) + if (_argMan->complexity() == COMPLEXITY_Object) ParamSpecs["example"] = QJsonObject(); else ParamSpecs["example"] = _defaultValue.toString(); } - }else{ - if(_argMan->isNullable() == false){ - if(addExample){ + } else { + if (_argMan->isNullable() == false) { + if (addExample) { ParamSpecs["required"] = true; ParamSpecs["example"] = _argMan->defaultVariant().toString(); - }else + } else ParamSpecs["example"] = QJsonValue(); - }else if (addExample) + } else if (addExample) ParamSpecs["example"] = QJsonValue(); - if(_defaultValue == QRequired) + if (_defaultValue == QRequired) ParamSpecs["required"] = true; } }; @@ -254,16 +242,16 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ return; QJsonObject ParamSpecs; - if(ParamType == PARAM_PKSBYPATH){ - if(_pksByPathsStorage){ + if (ParamType == PARAM_PKSBYPATH) { + if (_pksByPathsStorage) { QList PKs; foreach(auto Item, APIObject->Parent->filterItems(qhttp::EHTTP_DELETE)) - if(Item.isPrimaryKey()) + if (Item.isPrimaryKey()) PKs.append(Item); - foreach(auto PK, PKs){ + foreach(auto PK, PKs) { _pksByPathsStorage->append(PK.name()); intfAPIArgManipulator* ArgSpecs; - if(PK.parameterType()< TAPI_BASE_USER_DEFINED_TYPEID) + if (PK.parameterType()< TAPI_BASE_USER_DEFINED_TYPEID) ArgSpecs = gOrderedMetaTypeInfo.at(PK.parameterType()); else ArgSpecs = gUserDefinedTypesInfo.at(PK.parameterType()- TAPI_BASE_USER_DEFINED_TYPEID); @@ -280,17 +268,17 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ return; } - if(HTTPMethod == "get" || HTTPMethod == "delete"){ - if(_pksByPathsStorage){ - if(ParamType == PARAM_ORMFIELDS){ - foreach(auto Item, APIObject->Parent->filterItems(HTTPMethod == "get" ? qhttp::EHTTP_GET : qhttp::EHTTP_DELETE)){ - if(Item.isFilterable()== false || Item.isPrimaryKey()) + if (HTTPMethod == "get" || HTTPMethod == "delete") { + if (_pksByPathsStorage) { + if (ParamType == PARAM_ORMFIELDS) { + foreach(auto Item, APIObject->Parent->filterItems(HTTPMethod == "get" ? qhttp::EHTTP_GET : qhttp::EHTTP_DELETE)) { + if (Item.isFilterable()== false || Item.isPrimaryKey()) continue; QJsonObject ParamSpecs; ParamSpecs["in"] = "query"; ParamSpecs["name"] = Item.name(); intfAPIArgManipulator* ArgSpecs; - if(Item.parameterType()< TAPI_BASE_USER_DEFINED_TYPEID) + if (Item.parameterType()< TAPI_BASE_USER_DEFINED_TYPEID) ArgSpecs = gOrderedMetaTypeInfo.at(Item.parameterType()); else ArgSpecs = gUserDefinedTypesInfo.at(Item.parameterType()- TAPI_BASE_USER_DEFINED_TYPEID); @@ -307,7 +295,7 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ } return ; } - if(ParamType == PARAM_ORMFIELDS) + if (ParamType == PARAM_ORMFIELDS) return; ParamSpecs["in"] = "query"; @@ -334,7 +322,7 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ PathInfo["tags"] = QJsonArray({TagName}); PathInfo["produces"] = QJsonArray({"application/json"}); - if (HTTPMethod != "get" && HTTPMethod != "delete"){ + if (HTTPMethod != "get" && HTTPMethod != "delete") { quint8 RequiredFiles = 0; for (quint8 i=0; i< APIObject->BaseMethod.parameterCount(); ++i) if (QMetaType::typeName(APIObject->BaseMethod.parameterType(i)) == QStringLiteral(PARAM_FILE)) @@ -343,7 +331,7 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ RequiredFiles += 2; QJsonObject Properties; - for (quint8 i=0; i< APIObject->BaseMethod.parameterCount(); ++i){ + for (quint8 i=0; i< APIObject->BaseMethod.parameterCount(); ++i) { QString ParamType = QMetaType::typeName(APIObject->BaseMethod.parameterType(i)); if ( ParamType == PARAM_HEADERS || ParamType == PARAM_REMOTE_IP @@ -353,23 +341,23 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ ) continue; - if (ParamType == PARAM_ORMFIELDS){ + if (ParamType == PARAM_ORMFIELDS) { auto Items = APIObject->Parent->filterItems(HTTPMethod == "put" ? qhttp::EHTTP_PUT : HTTPMethod == "patch" ? qhttp::EHTTP_PATCH : qhttp::EHTTP_BIND); - foreach(auto Item, Items){ + foreach(auto Item, Items) { QJsonObject ParamSpecs; intfAPIArgManipulator* ArgSpecs; - if(Item.parameterType()< TAPI_BASE_USER_DEFINED_TYPEID) + if (Item.parameterType()< TAPI_BASE_USER_DEFINED_TYPEID) ArgSpecs = gOrderedMetaTypeInfo.at(Item.parameterType()); else ArgSpecs = gUserDefinedTypesInfo.at(Item.parameterType()- TAPI_BASE_USER_DEFINED_TYPEID); - if (!ArgSpecs){ + if (!ArgSpecs) { Item.registerTypeIfNotRegisterd(APIObject->Parent); - if(Item.parameterType()< TAPI_BASE_USER_DEFINED_TYPEID) + if (Item.parameterType()< TAPI_BASE_USER_DEFINED_TYPEID) ArgSpecs = gOrderedMetaTypeInfo.at(Item.parameterType()); else ArgSpecs = gUserDefinedTypesInfo.at(Item.parameterType()- TAPI_BASE_USER_DEFINED_TYPEID); @@ -377,18 +365,18 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ Q_ASSERT(ArgSpecs); QVariant DefaultValue = QVariant(); - if(Item.defaultValue() == QAuto) + if (Item.defaultValue() == QAuto) continue; - if(Item.defaultValue() == QInvalid) + if (Item.defaultValue() == QInvalid) throw exTargomanAPI("Invalid Item exported for PUT method: " + Item.name()); - if(HTTPMethod == "put"){ - if(Item.defaultValue() == QNull) + if (HTTPMethod == "put") { + if (Item.defaultValue() == QNull) DefaultValue = QNull; else if (Item.defaultValue() == QRequired) DefaultValue = QRequired; else DefaultValue = Item.toString(Item.defaultValue()); - }else if(Item.isReadOnly()) + } else if (Item.isReadOnly()) continue; fillParamTypeSpec(ArgSpecs, @@ -400,8 +388,7 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ ); Properties[Item.name()] = ParamSpecs; } - } - else { + } else { QJsonObject ParamSpecs; fillParamTypeSpec(APIObject->argSpecs(i), APIObject->Parent->filterItems(), @@ -414,25 +401,25 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ } QJsonArray Parameters; - for(quint8 i=0; i< APIObject->BaseMethod.parameterCount(); ++i) + for (quint8 i=0; i< APIObject->BaseMethod.parameterCount(); ++i) addParamSpecs( Parameters, i, _pksByPathsStorage); - if(RequiredFiles > 0){ + if (RequiredFiles > 0) { PathInfo["consumes"] = QJsonArray({"multipart/form-data"}); - for(auto Prop = Properties.begin(); Prop != Properties.end(); ++Prop){ + for (auto Prop = Properties.begin(); Prop != Properties.end(); ++Prop) { QJsonObject PropVal = Prop.value().toObject(); PropVal.insert("name", Prop.key()); PropVal.insert("in", "formData"); Parameters.append(PropVal); } - }else{ + } else { QJsonArray RequiredFields; - for(auto PropertyIter = Properties.begin(); + for (auto PropertyIter = Properties.begin(); PropertyIter != Properties.end(); PropertyIter++ ) - if(PropertyIter->toObject().value("required").toBool()) + if (PropertyIter->toObject().value("required").toBool()) RequiredFields.append(PropertyIter.key()); PathInfo["consumes"] = QJsonArray({"application/json"}); Parameters.append(QJsonObject({ @@ -448,13 +435,12 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ })); } PathInfo["parameters"] = Parameters; - } - else { + } else { QJsonArray Parameters; - for(quint8 i=0; i< APIObject->BaseMethod.parameterCount(); ++i) + for (quint8 i=0; i< APIObject->BaseMethod.parameterCount(); ++i) addParamSpecs(Parameters, i, _pksByPathsStorage); - if(Parameters.size()) + if (Parameters.size()) PathInfo["parameters"] = Parameters; } @@ -465,12 +451,12 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ //{"5XX", QJsonObject({{"description", "Unexpected error"}})}, }); QJsonObject ResponseModel = DefaultResponses; - if(HTTPMethod == "get"){ + if (HTTPMethod == "get") { QJsonObject Properties; - foreach(auto Item, APIObject->Parent->filterItems()){ + foreach(auto Item, APIObject->Parent->filterItems()) { QJsonObject ParamSpecs; intfAPIArgManipulator* ArgSpecs; - if(Item.parameterType()< TAPI_BASE_USER_DEFINED_TYPEID) + if (Item.parameterType()< TAPI_BASE_USER_DEFINED_TYPEID) ArgSpecs = gOrderedMetaTypeInfo.at(Item.parameterType()); else ArgSpecs = gUserDefinedTypesInfo.at(Item.parameterType()- TAPI_BASE_USER_DEFINED_TYPEID); @@ -484,7 +470,7 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ Properties.insert(Item.name(), ParamSpecs); } - if(Properties.size()) + if (Properties.size()) ResponseModel["200"] = QJsonObject({ {"description", "Success"}, @@ -495,14 +481,14 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ }); } - if(APIObject->requiresJWT()){ + if (APIObject->requiresJWT()) { ResponseModel["401"] = QJsonObject({{"description", "Authorization information is missing or invalid"}}); ResponseModel["403"] = QJsonObject({{"description", "Access forbidden"}}); } PathInfo["responses"] = ResponseModel; - if(APIObject->requiresJWT()){ + if (APIObject->requiresJWT()) { PathInfo["security"] = QJsonArray({ QJsonObject({ {"Bearer", QJsonArray()} @@ -512,28 +498,28 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ return PathInfo; }; - auto add2Paths = [PathString, HTTPMethod](QJsonObject& PathsObject, const QJsonObject& _currPathMethodInfo, QStringList* _pksByPathsStorage, bool _multiPK = false){ - if(HTTPMethod == "delete" && _currPathMethodInfo.value("parameters").toArray().isEmpty()) + auto add2Paths = [PathString, HTTPMethod](QJsonObject& PathsObject, const QJsonObject& _currPathMethodInfo, QStringList* _pksByPathsStorage, bool _multiPK = false) { + if (HTTPMethod == "delete" && _currPathMethodInfo.value("parameters").toArray().isEmpty()) return; QString Path = PathString; - if(_pksByPathsStorage){ + if (_pksByPathsStorage) { if (_multiPK) Path += "/{" + _pksByPathsStorage->join("_1};{") + "_1},{" + _pksByPathsStorage->join("_2};{") + "_2},..."; else Path += "/{" + _pksByPathsStorage->join("};{") + "}"; } - if(PathsObject.contains(Path)){ + if (PathsObject.contains(Path)) { QJsonObject CurrPathObject = PathsObject.value(Path).toObject(); CurrPathObject[HTTPMethod] = _currPathMethodInfo; PathsObject[Path] = CurrPathObject; - }else + } else PathsObject[Path] = QJsonObject({ {HTTPMethod, _currPathMethodInfo} }); }; - if(APIObject->requiresPrimaryKey()){ + if (APIObject->requiresPrimaryKey()) { add2Paths(PathsObject, createPathInfo(&PKInPathStorage), &PKInPathStorage, false); - /* if(HTTPMethod == "delete"){ + /* if (HTTPMethod == "delete") { PKInPathStorage.clear(); add2Paths(PathsObject, createPathInfo(&PKInPathStorage), &PKInPathStorage, true); }*/ @@ -544,20 +530,20 @@ QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _ QList Filters = APIObject->Parent->filterItems(); QStringList ModelDescription; - foreach(auto Filter, Filters){ + foreach(auto Filter, Filters) { QString FilterInfo = "* " + Filter.name(); QStringList Flags; - if(Filter.isSortable()) Flags.append("Sortable"); - if(Filter.isFilterable()) Flags.append("Filterable"); - if(Filter.isPrimaryKey()) Flags.append("*PrimaryKey*"); - if(Filter.isSelfIdentifier()) Flags.append("**SelfIdentifier**"); - if(Filter.isVirtual()) Flags.append("Virtual"); - if(Flags.size()) + if (Filter.isSortable()) Flags.append("Sortable"); + if (Filter.isFilterable()) Flags.append("Filterable"); + if (Filter.isPrimaryKey()) Flags.append("*PrimaryKey*"); + if (Filter.isSelfIdentifier()) Flags.append("**SelfIdentifier**"); + if (Filter.isVirtual()) Flags.append("Virtual"); + if (Flags.size()) FilterInfo += " (" + Flags.join("|") + ")"; ModelDescription.append(FilterInfo); } - /*if(false && ModelDescription.size()){ + /*if (false && ModelDescription.size()) { TagsArray.append(QJsonObject({ {"name", TagName}, {"description", QString("Model:\n" + ModelDescription.join("\n"))} diff --git a/App/Server/RESTAPIRegistry.cpp b/App/Server/RESTAPIRegistry.cpp index 986a89ae..3e43fd2b 100644 --- a/App/Server/RESTAPIRegistry.cpp +++ b/App/Server/RESTAPIRegistry.cpp @@ -75,7 +75,7 @@ const QMap MetaTypeInfoMap = { template<> std::function tmplAPIArg<_baseType, _complexity, false, true>::optionsLambda = nullptr; \ \ template<> std::function tmplAPIArg::toVariantLambda = \ - [](NULLABLE_TYPE(_baseType) _value){return NULLABLE_IS_NULL(_value) ? QVariant() : tmplAPIArg<_baseType, _complexity, false, true>::toVariant(*_value);}; \ + [](NULLABLE_TYPE(_baseType) _value) {return NULLABLE_IS_NULL(_value) ? QVariant() : tmplAPIArg<_baseType, _complexity, false, true>::toVariant(*_value);}; \ template<> std::function tmplAPIArg::fromVariantLambda = \ [](const QVariant& _value, const QByteArray& _paramName) -> NULLABLE_TYPE(_baseType) { \ if (!_value.isValid() || _value.isNull()) return NULLABLE_TYPE(_baseType)(); \ @@ -117,8 +117,8 @@ DO_ON_TYPE_NULLABLE_VALID(COMPLEXITY_Integral, float, nullptr, nullptr, nullpt DO_ON_TYPE_NULLABLE_VALID(COMPLEXITY_Integral, double, nullptr, nullptr, nullptr) DO_ON_TYPE_NULLABLE_VALID(COMPLEXITY_Integral, bool, [](const QVariant& _value, const QByteArray& _paramName) -> bool { - if(_value.toString() == "false" || _value.toString() == "0") return false; - if(_value.toString() == "true" || _value.toString() == "1") return true; + if (_value.toString() == "false" || _value.toString() == "0") return false; + if (_value.toString() == "true" || _value.toString() == "1") return true; throw exHTTPBadRequest(_paramName + " is not a valid bool"); }, [](const QVariant& _val) -> QVariant {return !(_val == "false" || _val == "0");}, @@ -136,7 +136,7 @@ struct stuNullableQtType { stuNullableQtType(const std::function& _registrar, intfAPIArgManipulator* _manipulator) : registerInMetaTypes(_registrar), ArgManipulator(_manipulator) - {} + { ; } }; /***********************************************************************************************/ @@ -165,7 +165,7 @@ void RESTAPIRegistry::registerRESTAPI(intfPureModule* _module, const QMetaMethod RESTAPIRegistry::registerMetaTypeInfoMap(); - try{ + try { RESTAPIRegistry::validateMethodInputAndOutput(_method); QString MethodName = _method.name().constData(); MethodName = MethodName.mid(MethodName.indexOf("api",0,Qt::CaseInsensitive) + 3); @@ -173,7 +173,7 @@ void RESTAPIRegistry::registerRESTAPI(intfPureModule* _module, const QMetaMethod QString MethodSignature, MethodDoc; bool Found = false; for (int i=0; i<_module->metaObject()->methodCount(); ++i) - if(_module->metaObject()->method(i).name() == "signOf" + MethodName){ + if (_module->metaObject()->method(i).name() == "signOf" + MethodName) { _module->metaObject()->method(i).invoke(_module, Qt::DirectConnection, Q_RETURN_ARG(QString, MethodSignature) @@ -186,7 +186,7 @@ void RESTAPIRegistry::registerRESTAPI(intfPureModule* _module, const QMetaMethod throw exRESTRegistry("Seems that you have not use API macro to define your API: " + MethodName); for (int i=0; i<_module->metaObject()->methodCount(); ++i) - if(_module->metaObject()->method(i).name() == "docOf" + MethodName){ + if (_module->metaObject()->method(i).name() == "docOf" + MethodName) { _module->metaObject()->method(i).invoke(_module, Qt::DirectConnection, Q_RETURN_ARG(QString, MethodDoc) @@ -200,7 +200,7 @@ void RESTAPIRegistry::registerRESTAPI(intfPureModule* _module, const QMetaMethod auto makeMethodName = [MethodName](int _start) -> QString{ - if(MethodName.size() >= _start) + if (MethodName.size() >= _start) return MethodName.at(_start-1).toLower() + MethodName.mid(_start); return ""; }; @@ -210,24 +210,24 @@ void RESTAPIRegistry::registerRESTAPI(intfPureModule* _module, const QMetaMethod MethodSignature = MethodSignature.trimmed().replace("','", QString("'%1'").arg(COMMA_SIGN)); bool DQuoteStarted = false, BackslashFound = false; QString CommaReplacedMethodSignature; - for(int i=0; i< MethodSignature.size(); ++i){ - if(DQuoteStarted){ - if(MethodSignature.at(i).toLatin1() == ',') + for (int i=0; i< MethodSignature.size(); ++i) { + if (DQuoteStarted) { + if (MethodSignature.at(i).toLatin1() == ',') CommaReplacedMethodSignature += COMMA_SIGN; else if (MethodSignature.at(i).toLatin1() == '\\') { BackslashFound = true; - }else if (MethodSignature.at(i).toLatin1() == '"') { + } else if (MethodSignature.at(i).toLatin1() == '"') { CommaReplacedMethodSignature += '"'; - if(BackslashFound) + if (BackslashFound) BackslashFound = false; else DQuoteStarted = false; - }else + } else CommaReplacedMethodSignature += MethodSignature.at(i); - }else if (MethodSignature.at(i).toLatin1() == '"'){ + } else if (MethodSignature.at(i).toLatin1() == '"') { CommaReplacedMethodSignature += '"'; DQuoteStarted = true; - }else + } else CommaReplacedMethodSignature += MethodSignature.at(i); } @@ -235,7 +235,7 @@ void RESTAPIRegistry::registerRESTAPI(intfPureModule* _module, const QMetaMethod QVariantList DefaultValues; quint8 ParamIndex = 0; bool ContainsFileInput = false; - foreach(auto Param, CommaReplacedMethodSignature.split(',')){ + foreach(auto Param, CommaReplacedMethodSignature.split(',')) { if (ParamIndex >= _method.parameterCount()) break; @@ -268,8 +268,7 @@ void RESTAPIRegistry::registerRESTAPI(intfPureModule* _module, const QMetaMethod DefaultValues.append(Value.mid(Value.indexOf("::") + 2)); else DefaultValues.append(Value); - } - else if (ArgSpecs->isNullable()) + } else if (ArgSpecs->isNullable()) throw exRESTRegistry("Nullable parameter: <"+_method.parameterNames().value(ParamIndex)+"> on method: <" + MethodName + "> must have default value" ); else DefaultValues.append(QVariant()); @@ -283,48 +282,43 @@ void RESTAPIRegistry::registerRESTAPI(intfPureModule* _module, const QMetaMethod if (ContainsFileInput) throw exRESTRegistry("file input can not be used with GET method: "+ MethodName); RESTAPIRegistry::addRegistryEntry(RESTAPIRegistry::Registry, _module, Method, "GET", makeMethodName(sizeof("GET"))); - } - else if(MethodName.startsWith("POST")) + } else if (MethodName.startsWith("POST")) RESTAPIRegistry::addRegistryEntry(RESTAPIRegistry::Registry, _module, Method, "POST", makeMethodName(sizeof("POST"))); - else if(MethodName.startsWith("PUT")) + else if (MethodName.startsWith("PUT")) RESTAPIRegistry::addRegistryEntry(RESTAPIRegistry::Registry, _module, Method, "PUT", makeMethodName(sizeof("PUT"))); - else if(MethodName.startsWith("CREATE")) + else if (MethodName.startsWith("CREATE")) RESTAPIRegistry::addRegistryEntry(RESTAPIRegistry::Registry, _module, Method, "PUT", makeMethodName(sizeof("CREATE"))); - else if(MethodName.startsWith("PATCH")) + else if (MethodName.startsWith("PATCH")) RESTAPIRegistry::addRegistryEntry(RESTAPIRegistry::Registry, _module, Method, "PATCH", makeMethodName(sizeof("PATCH"))); else if (MethodName.startsWith("DELETE")) { if (ContainsFileInput) throw exRESTRegistry("file input can not be used with DELETE method: "+ MethodName); RESTAPIRegistry::addRegistryEntry(RESTAPIRegistry::Registry, _module, Method, "DELETE", makeMethodName(sizeof("DELETE"))); - } - else if (MethodName.startsWith("UPDATE")) + } else if (MethodName.startsWith("UPDATE")) RESTAPIRegistry::addRegistryEntry(RESTAPIRegistry::Registry, _module, Method, "PATCH", makeMethodName(sizeof("UPDATE"))); else if (MethodName.startsWith("WS")) { #ifdef TARGOMAN_API_ENABLE_WEBSOCKET - if(ContainsFileInput) + if (ContainsFileInput) throw exRESTRegistry("file input can not be used with WebSockets: "+ MethodName); RESTAPIRegistry::addRegistryEntry(RESTAPIRegistry::WSRegistry, _module, Method, "WS", makeMethodName(sizeof("WS"))); #else throw exRESTRegistry("Websockets are not enabled in this QRestServer please compile with websockets support"); #endif - } - else if(ContainsFileInput) + } else if (ContainsFileInput) throw exRESTRegistry("methods with file input must specifically contain HTTP method: " + MethodName); else { RESTAPIRegistry::addRegistryEntry(RESTAPIRegistry::Registry, _module, Method, "GET", MethodName.at(0).toLower() + MethodName.mid(1)); RESTAPIRegistry::addRegistryEntry(RESTAPIRegistry::Registry, _module, Method, "POST", MethodName.at(0).toLower() + MethodName.mid(1)); } - } - catch(Targoman::Common::exTargomanBase& ex) { + } catch (Targoman::Common::exTargomanBase& ex) { TargomanError("Fatal Error: "< RESTAPIRegistry::extractMethods(QHash& _registry, const QString& _module, bool _showTypes, bool _prettifyTypes) -{ +QMap RESTAPIRegistry::extractMethods(QHash& _registry, const QString& _module, bool _showTypes, bool _prettifyTypes) { static auto type2Str = [_prettifyTypes](int _typeID) { - if(_prettifyTypes == false || _typeID > QMetaType::User) + if (_prettifyTypes == false || _typeID > QMetaType::User) return QString(QMetaType::typeName(_typeID)); return gOrderedMetaTypeInfo.at(_typeID)->PrettyTypeName; @@ -332,20 +326,20 @@ QMap RESTAPIRegistry::extractMethods(QHash Methods; - foreach(const QString& Key, _registry.keys()){ + foreach(const QString& Key, _registry.keys()) { QString Path = Key.split(" ").last(); - if(Path.startsWith(_module) == false) + if (Path.startsWith(_module) == false) continue; clsAPIObject* APIObject = _registry.value(Key); QStringList Parameters; - for(quint8 i=0; i< APIObject->BaseMethod.parameterCount(); ++i){ + for (quint8 i=0; i< APIObject->BaseMethod.parameterCount(); ++i) { static auto defaultValue = [](clsAPIObject* _apiObject, quint8 i) -> QString{ - if(_apiObject->RequiredParamsCount > i) + if (_apiObject->RequiredParamsCount > i) return ""; intfAPIArgManipulator* ArgManipulator = _apiObject->argSpecs(i); - if(ArgManipulator){ - switch(ArgManipulator->complexity()){ + if (ArgManipulator) { + switch (ArgManipulator->complexity()) { case COMPLEXITY_Number: case COMPLEXITY_Boolean: case COMPLEXITY_Integral: @@ -387,8 +381,8 @@ QMap RESTAPIRegistry::extractMethods(QHash= gOrderedMetaTypeInfo.size() || gOrderedMetaTypeInfo.at(_typeID) == nullptr)) + if (_typeID < TAPI_BASE_USER_DEFINED_TYPEID && (_typeID >= gOrderedMetaTypeInfo.size() || gOrderedMetaTypeInfo.at(_typeID) == nullptr)) return "is complex type and not supported"; - if(_typeID >= TAPI_BASE_USER_DEFINED_TYPEID){ + if (_typeID >= TAPI_BASE_USER_DEFINED_TYPEID) { if ((_typeID - TAPI_BASE_USER_DEFINED_TYPEID >= gUserDefinedTypesInfo.size() || gUserDefinedTypesInfo.at(_typeID - TAPI_BASE_USER_DEFINED_TYPEID) == nullptr)) return "is user defined but not registered"; - if(strcmp(gUserDefinedTypesInfo.at(_typeID - TAPI_BASE_USER_DEFINED_TYPEID)->RealTypeName, QMetaType::typeName(_typeID))) + if (strcmp(gUserDefinedTypesInfo.at(_typeID - TAPI_BASE_USER_DEFINED_TYPEID)->RealTypeName, QMetaType::typeName(_typeID))) return QString("Seems that registration table is corrupted: %1:%2 <-> %3:%4").arg( _typeID).arg( gUserDefinedTypesInfo.at(_typeID - TAPI_BASE_USER_DEFINED_TYPEID)->RealTypeName).arg( _typeID).arg( QMetaType::typeName(_typeID)); - if(_validate4Input){ + if (_validate4Input) { if (!gUserDefinedTypesInfo.at(_typeID - TAPI_BASE_USER_DEFINED_TYPEID)->hasFromVariantMethod()) return "has no fromVariant lambda so can not be used as input"; - }else{ + } else { if (!gUserDefinedTypesInfo.at(_typeID - TAPI_BASE_USER_DEFINED_TYPEID)->hasToVariantMethod()) return "has no toVariant lambda so can not be used as output"; } @@ -434,8 +428,8 @@ QString RESTAPIRegistry::isValidType(int _typeID, bool _validate4Input){ return ""; } -void RESTAPIRegistry::validateMethodInputAndOutput(const QMetaMethod& _method){ - if(_method.parameterCount() > 10) +void RESTAPIRegistry::validateMethodInputAndOutput(const QMetaMethod& _method) { + if (_method.parameterCount() > 10) throw exRESTRegistry("Unable to register methods with more than 10 input args <"+_method.name()+">"); QString ErrMessage; @@ -444,15 +438,15 @@ void RESTAPIRegistry::validateMethodInputAndOutput(const QMetaMethod& _method){ ErrMessage.clear(); - for(int i=0; i<_method.parameterCount(); ++i){ + for (int i=0; i<_method.parameterCount(); ++i) { if ((ErrMessage = RESTAPIRegistry::isValidType(_method.parameterType(i), true)).size()) throw exRESTRegistry(QString("Invalid parameter (%1 %2): %3").arg( _method.parameterTypes().at(i).constData()).arg( _method.parameterNames().at(i).constData()).arg( ErrMessage)); - for(int j=i+1; j<_method.parameterCount(); ++j){ - if(_method.parameterNames().at(j) == _method.parameterNames().at(i)) + for (int j=i+1; j<_method.parameterCount(); ++j) { + if (_method.parameterNames().at(j) == _method.parameterNames().at(i)) throw exRESTRegistry(QString("Invalid duplicate parameter name %1 at %2 and %3").arg( _method.parameterNames().at(i).constData()).arg( i).arg( @@ -470,15 +464,15 @@ void RESTAPIRegistry::addRegistryEntry(QHash& _registry intfPureModule* _module, const QMetaMethodExtended& _method, const QString& _httpMethod, - const QString& _methodName){ + const QString& _methodName) { QString MethodKey = RESTAPIRegistry::makeRESTAPIKey(_httpMethod, "/" + _module->moduleBaseName().replace(":", "/")+ '/' + _methodName); - if(_registry.contains(MethodKey)) { - if(RESTAPIRegistry::Registry.value(MethodKey)->isPolymorphic(_method)) + if (_registry.contains(MethodKey)) { + if (RESTAPIRegistry::Registry.value(MethodKey)->isPolymorphic(_method)) throw exRESTRegistry(QString("Polymorphism is not supported: %1").arg(_method.methodSignature().constData())); _registry.value(MethodKey)->updateDefaultValues(_method); } else { - if(RESTAPIRegistry::getTagSeconds(_method, CACHE_INTERNAL) > 0 + if (RESTAPIRegistry::getTagSeconds(_method, CACHE_INTERNAL) > 0 && RESTAPIRegistry::getTagSeconds(_method, CACHE_CENTRAL) >0) throw exRESTRegistry("Both internal and central cache can not be defined on an API"); @@ -495,17 +489,17 @@ void RESTAPIRegistry::addRegistryEntry(QHash& _registry } -int RESTAPIRegistry::getTagSeconds(const QMetaMethod& _method, const char* _type){ - if(_method.tag() == nullptr || _method.tag()[0] == '\0') +int RESTAPIRegistry::getTagSeconds(const QMetaMethod& _method, const char* _type) { + if (_method.tag() == nullptr || _method.tag()[0] == '\0') return 0; QString Tag = _method.tag(); - if(Tag.startsWith(_type) && Tag.size () > 12){ + if (Tag.startsWith(_type) && Tag.size () > 12) { Tag = Tag.mid(10); - if(_type == CACHE_INTERNAL && Tag == "INF") + if (_type == CACHE_INTERNAL && Tag == "INF") return -1; char Type = Tag.rbegin()->toLatin1(); int Number = Tag.mid(0,Tag.size() -1).toUShort(); - switch(Type){ + switch (Type) { case 'S': return Number; case 'M': return Number * 60; case 'H': return Number * 3600; @@ -528,11 +522,10 @@ QHash RESTAPIRegistry::WSRegistry; /****************************************************/ intfCacheConnector::~intfCacheConnector() -{} +{ ; } -void Targoman::API::Server::intfCacheConnector::setKeyVal(const QString& _key, const QVariant& _value, qint32 _ttl) -{ - if(_value.type() >= TAPI_BASE_USER_DEFINED_TYPEID) +void Targoman::API::Server::intfCacheConnector::setKeyVal(const QString& _key, const QVariant& _value, qint32 _ttl) { + if (_value.type() >= TAPI_BASE_USER_DEFINED_TYPEID) this->setKeyValImpl(_key, gUserDefinedTypesInfo.at(static_cast(_value.type() - TAPI_BASE_USER_DEFINED_TYPEID))->toString(_value), _ttl); diff --git a/App/Server/RESTAPIRegistry.h b/App/Server/RESTAPIRegistry.h index a8e38dd7..2beed81a 100644 --- a/App/Server/RESTAPIRegistry.h +++ b/App/Server/RESTAPIRegistry.h @@ -43,8 +43,7 @@ TARGOMAN_ADD_EXCEPTION_HANDLER(exRESTRegistry, Targoman::Common::exTargomanBase) /*****************************************************/ class OpenAPIGenerator; -class RESTAPIRegistry -{ +class RESTAPIRegistry { public: static inline QString makeRESTAPIKey(const QString& _httpMethod, const QString& _path) { return _httpMethod.toUpper() + " " + (_path.endsWith('/') ? _path.mid(0, _path.size() - 1) : _path); @@ -55,7 +54,7 @@ class RESTAPIRegistry } #ifdef TARGOMAN_API_ENABLE_WEBSOCKET - static inline clsAPIObject* getWSAPIObject(const QString& _path){ + static inline clsAPIObject* getWSAPIObject(const QString& _path) { return RESTAPIRegistry::WSRegistry.value(RESTAPIRegistry::makeRESTAPIKey("WS", _path)); } #endif diff --git a/App/Server/RESTServer.cpp b/App/Server/RESTServer.cpp index bb445e2a..3729fe81 100644 --- a/App/Server/RESTServer.cpp +++ b/App/Server/RESTServer.cpp @@ -50,8 +50,7 @@ static WebSocketServer gWSServer; #endif static clsUpdateAndPruneThread *gStatUpdateThread; -void RESTServer::start(fnIsInBlackList_t _fnIPInBlackList) -{ +void RESTServer::start(fnIsInBlackList_t _fnIPInBlackList) { if (this->IsStarted) throw exTargomanInitialization("RESTServer can be run single instance only"); @@ -82,26 +81,22 @@ void RESTServer::start(fnIsInBlackList_t _fnIPInBlackList) this->IsStarted = true; - if (ServerConfigs::StatisticsInterval.value()) - { + if (ServerConfigs::StatisticsInterval.value()) { gStatUpdateThread = new clsUpdateAndPruneThread(); connect(gStatUpdateThread, &clsUpdateAndPruneThread::finished, gStatUpdateThread, &QObject::deleteLater); gStatUpdateThread->start(); } - QObject::connect(&gHTTPServer, &QHttpServer::newConnection, [this](QHttpConnection* _con) - { + QObject::connect(&gHTTPServer, &QHttpServer::newConnection, [this](QHttpConnection* _con) { if (!this->validateConnection(_con->tcpSocket()->peerAddress(), _con->tcpSocket()->peerPort())) _con->killConnection(); }); QHostAddress ListenAddress = ServerConfigs::JustLocal.value() ? QHostAddress::LocalHost : QHostAddress::Any; - gHTTPServer.listen(ListenAddress, ServerConfigs::ListenPort.value(), [&, BasePath](QHttpRequest* _req, QHttpResponse* _res) - { + gHTTPServer.listen(ListenAddress, ServerConfigs::ListenPort.value(), [&, BasePath](QHttpRequest* _req, QHttpResponse* _res) { clsRequestHandler* RequestHandler = new clsRequestHandler(_req, _res); - try - { + try { QString Path = _req->url().adjusted(QUrl::NormalizePathSegments | QUrl::RemoveAuthority ).path(QUrl::PrettyDecoded); @@ -133,37 +128,31 @@ void RESTServer::start(fnIsInBlackList_t _fnIPInBlackList) _req->url().query()); //---------------------------------- - try - { + try { auto headers = _req->headers(); QStringList headersLog; for (auto Iter = headers.begin(); Iter != headers.end(); ++Iter) headersLog.append(QString(" %1: %2").arg(Iter.key().toStdString().c_str()).arg(Iter.value().toStdString().c_str())); TargomanLogInfo(7, "headers: " << "\n" << headersLog.join("\n")); - } catch (...) {} + } catch (...) { ; } //---------------------------------- RequestHandler->process(Path.mid(ServerConfigs::BasePathWithVersion.size() - 1)); - } - catch(exTargomanBase& ex) - { + } catch (exTargomanBase& ex) { RequestHandler->sendError(static_cast(ex.httpCode()), ex.what(), {}, ex.httpCode() >= 500); } }); - if (gHTTPServer.isListening()) - { + if (gHTTPServer.isListening()) { TargomanLogInfo(1, "REST Server is listening on "<peerAddress(), _con->peerPort())) _con->close(QWebSocketProtocol::CloseCodePolicyViolated,"IP banned"); }); @@ -173,8 +162,7 @@ void RESTServer::start(fnIsInBlackList_t _fnIPInBlackList) #endif } -void RESTServer::stop() -{ +void RESTServer::stop() { gHTTPServer.stopListening(); #ifdef TARGOMAN_API_ENABLE_WEBSOCKET gWSServer.stopListening(); @@ -185,18 +173,15 @@ void RESTServer::stop() gStatUpdateThread->quit(); } -TAPI::stuStatistics RESTServer::stats() -{ +TAPI::stuStatistics RESTServer::stats() { return gServerStats; } -QStringList RESTServer::registeredAPIs(bool _showParams, bool _showTypes, bool _prettifyTypes) -{ +QStringList RESTServer::registeredAPIs(bool _showParams, bool _showTypes, bool _prettifyTypes) { return RESTAPIRegistry::registeredAPIs("", _showParams, _showTypes, _prettifyTypes); } -void RESTServer::registerUserDefinedType(const char* _typeName, intfAPIArgManipulator* _argManipulator) -{ +void RESTServer::registerUserDefinedType(const char* _typeName, intfAPIArgManipulator* _argManipulator) { // TargomanInfo(9, "registering User Defined Type: (" << _typeName << ")"); Q_ASSERT_X(QMetaType::type(_typeName), QString("registerUserDefinedType typeName(%1)").arg(_typeName).toStdString().c_str(), "Seems that registering syntax is erroneous"); @@ -204,13 +189,11 @@ void RESTServer::registerUserDefinedType(const char* _typeName, intfAPIArgManipu gUserDefinedTypesInfo.insert(QMetaType::type(_typeName) - TAPI_BASE_USER_DEFINED_TYPEID, _argManipulator); } -bool RESTServer::validateConnection(const QHostAddress& _peerAddress, quint16 _peerPort) -{ +bool RESTServer::validateConnection(const QHostAddress& _peerAddress, quint16 _peerPort) { enuIPBlackListStatus::Type IPBlackListStatus = enuIPBlackListStatus::Unknown; if (this->fnIPInBlackList && - (IPBlackListStatus = this->fnIPInBlackList(_peerAddress)) != enuIPBlackListStatus::Ok) - { + (IPBlackListStatus = this->fnIPInBlackList(_peerAddress)) != enuIPBlackListStatus::Ok) { TargomanLogWarn(1,"Connection from " + _peerAddress.toString() + " was closed by security provider due to: "+enuIPBlackListStatus::toStr(IPBlackListStatus)); gServerStats.Blocked.inc(); return false; @@ -223,14 +206,13 @@ bool RESTServer::validateConnection(const QHostAddress& _peerAddress, quint16 _p } RESTServer::RESTServer() : - IsStarted(false) { -} + IsStarted(false) +{ ; } } //namespace Server /***********************************************************************************************/ -void registerUserDefinedType(const char* _typeName, intfAPIArgManipulator* _argManipulator) -{ +void registerUserDefinedType(const char* _typeName, intfAPIArgManipulator* _argManipulator) { Server::RESTServer::instance().registerUserDefinedType(_typeName, _argManipulator); } diff --git a/App/Server/ServerConfigs.cpp b/App/Server/ServerConfigs.cpp index 93486f28..35ee1578 100644 --- a/App/Server/ServerConfigs.cpp +++ b/App/Server/ServerConfigs.cpp @@ -280,7 +280,7 @@ tmplConfigurable ServerConfigs::MasterDB::Schema( /****************************************************************************/ /*static auto langValidator = [](const intfConfigurable& _item, QString& _errorMessage) -> bool{ - if(ISO639isValid(_item.toVariant().toString().toLatin1().constData())) + if (ISO639isValid(_item.toVariant().toString().toLatin1().constData())) return true; _errorMessage = QString("Invalid language code <%1> on <%2>").arg( _item.toVariant().toString()).arg( @@ -332,8 +332,7 @@ gConfigs::Server::Server(const QString& _basePath) : "","","", enuConfigSource::File ), - Statistics(gConfigs::Server::stuStatistics(_basePath)) -{} + Statistics(gConfigs::Server::stuStatistics(_basePath)) { ; } gConfigs::Server::stuStatistics::stuStatistics(const QString& _basePath) : OkResponses(_basePath + "Stats/OkResponses", @@ -349,8 +348,7 @@ gConfigs::Server::stuStatistics::stuStatistics(const QString& _basePath) : ReturnTrueCrossValidator(), "","","", enuConfigSource::ReadOnly - ) - {} + ) { ; } tmplConfigurableMultiMap gConfigs::TranslationServers( clsConfigPath("TranslationServers"), diff --git a/App/Server/ServerConfigs.h b/App/Server/ServerConfigs.h index 8da448c1..686c2f07 100644 --- a/App/Server/ServerConfigs.h +++ b/App/Server/ServerConfigs.h @@ -38,7 +38,7 @@ TARGOMAN_ADD_EXCEPTION_HANDLER(exTargomanAPI, Targoman::Common::exTargomanBase); struct ServerConfigs { - static inline QString makeConfig(const QString& _name){return "/Server/" + _name;} + static inline QString makeConfig(const QString& _name) {return "/Server/" + _name;} static Targoman::Common::Configuration::tmplConfigurable BasePath; static Targoman::Common::Configuration::tmplConfigurable Version; diff --git a/App/Server/WebSocketServer.cpp b/App/Server/WebSocketServer.cpp index aa162ec2..846c6e3a 100644 --- a/App/Server/WebSocketServer.cpp +++ b/App/Server/WebSocketServer.cpp @@ -74,8 +74,7 @@ tmplConfigurable WebSocketServer::Secure( -void WebSocketServer::start() -{ +void WebSocketServer::start() { this->WS.reset(new QWebSocketServer(this->Name.value(), this->Secure.value()? QWebSocketServer::SecureMode : @@ -91,14 +90,12 @@ void WebSocketServer::start() } } -void WebSocketServer::stopListening() -{ +void WebSocketServer::stopListening() { this->WS->close (); qDeleteAll(this->Clients.begin(), this->Clients.end()); } -void WebSocketServer::onNewConnection() -{ +void WebSocketServer::onNewConnection() { QWebSocket *pSocket = this->WS->nextPendingConnection(); @@ -111,14 +108,13 @@ void WebSocketServer::onNewConnection() emit sigNewConnection(pSocket); } -void WebSocketServer::processTextMessage(QString _message) -{ +void WebSocketServer::processTextMessage(QString _message) { QWebSocket *pSocket = qobject_cast(sender()); TargomanDebug(5, "Text Message Received:" << _message); if (pSocket) { - auto sendError = [pSocket](qhttp::TStatusCode _code, QString _message){ + auto sendError = [pSocket](qhttp::TStatusCode _code, QString _message) { QJsonObject ErrorInfo = QJsonObject({ {"code", _code}, {"message", _message} @@ -130,22 +126,22 @@ void WebSocketServer::processTextMessage(QString _message) QJsonDocument::Compact).data()); }; - try{ + try { QJsonParseError Error; QJsonDocument JSON = QJsonDocument::fromJson(_message.toUtf8(), &Error); - if(JSON.isNull()) + if (JSON.isNull()) throw exHTTPBadRequest(QString("Invalid JSON request: %1").arg(Error.errorString())); QString ExtraAPIPath; QJsonObject JSONReqObject = JSON.object(); QString API = JSONReqObject.begin().key(); - if(API.isEmpty()) + if (API.isEmpty()) return sendError(qhttp::ESTATUS_BAD_REQUEST, "No API path specified"); clsAPIObject* APIObject = RESTAPIRegistry::getWSAPIObject (API); if (!APIObject) { QString Path = API; - if(Path.endsWith('/')) + if (Path.endsWith('/')) Path.truncate(Path.size() - 1); ExtraAPIPath = Path.mid(Path.lastIndexOf('/')); Path = Path.mid(0, Path.lastIndexOf('/')); @@ -157,10 +153,10 @@ void WebSocketServer::processTextMessage(QString _message) QVariantMap APIArgs = JSONReqObject.begin().value().toObject().toVariantMap(); QStringList Queries; - for(auto Map = APIArgs.begin(); Map != APIArgs.end(); ++Map) + for (auto Map = APIArgs.begin(); Map != APIArgs.end(); ++Map) Queries.append(Map.key() + '=' + Map.value().toString()); - /*if(ExtraAPIPath) + /*if (ExtraAPIPath) Queries.append(REQUES)*/ @@ -170,20 +166,19 @@ void WebSocketServer::processTextMessage(QString _message) QJsonDocument::Indented : QJsonDocument::Compact); pSocket->sendTextMessage(Data.data()); - }catch(Targoman::Common::exTargomanBase& ex){ + } catch (Targoman::Common::exTargomanBase& ex) { sendError(static_cast(ex.code()), ex.what()); - }catch(exQFVRequiredParam &ex){ + } catch (exQFVRequiredParam &ex) { sendError(qhttp::ESTATUS_BAD_REQUEST, ex.what()); - }catch(exQFVInvalidValue &ex){ + } catch (exQFVInvalidValue &ex) { sendError(qhttp::ESTATUS_BAD_REQUEST, ex.what()); - }catch(std::exception &ex){ + } catch (std::exception &ex) { sendError(qhttp::ESTATUS_INTERNAL_SERVER_ERROR, ex.what()); } } } -void WebSocketServer::processBinaryMessage(QByteArray _message) -{ +void WebSocketServer::processBinaryMessage(QByteArray _message) { QWebSocket *pSocket = qobject_cast(sender()); TargomanDebug(5, "Binary Message Received:" << _message); if (pSocket) { @@ -191,8 +186,7 @@ void WebSocketServer::processBinaryMessage(QByteArray _message) } } -void WebSocketServer::socketDisconnected() -{ +void WebSocketServer::socketDisconnected() { QWebSocket *pClient = qobject_cast(sender()); if (pClient) { TargomanLogDebug(5, "Client Disconnected: "< Name; static Targoman::Common::Configuration::tmplRangedConfigurablePort; static Targoman::Common::Configuration::tmplConfigurable JustLocal; @@ -49,7 +49,7 @@ class WebSocketServer : public QObject{ public: void start(); void stopListening(); - inline bool isActive(){return Name.value().size() && Port.value() > 0;} + inline bool isActive() {return Name.value().size() && Port.value() > 0;} signals: void sigNewConnection(QWebSocket* _connection); void closed(); diff --git a/App/Server/appTargomanAPI.cpp b/App/Server/appTargomanAPI.cpp index bad4bd85..df3ec79b 100644 --- a/App/Server/appTargomanAPI.cpp +++ b/App/Server/appTargomanAPI.cpp @@ -50,12 +50,10 @@ TARGOMAN_ADD_EXCEPTION_HANDLER(exAPIModuleInitiailization, exModuleLoader); #pragma clang diagnostic pop appTargomanAPI::appTargomanAPI(QObject *parent) : QObject(parent) -{} +{ ; } -void appTargomanAPI::slotExecute() -{ - try - { +void appTargomanAPI::slotExecute() { + try { // Load modules QMap RequiredDBs; @@ -63,8 +61,7 @@ void appTargomanAPI::slotExecute() if (LoadedModules.isEmpty()) throw exTargomanAPI("No module was loaded. Maybe you forgot to specify --plugins"); - foreach (auto Plugin, LoadedModules) - { + foreach (auto Plugin, LoadedModules) { intfPureModule* Module = qobject_cast(Plugin.Instance); Module->setInstancePointer(); @@ -86,15 +83,13 @@ void appTargomanAPI::slotExecute() } //Prepare database connections - if (RequiredDBs.size()) - { + if (RequiredDBs.size()) { TargomanDebug(0, "Registering db connections"); QSet ConnectionStrings; if (ServerConfigs::MasterDB::Host.value().size() - && ServerConfigs::MasterDB::Schema.value().size()) - { + && ServerConfigs::MasterDB::Schema.value().size()) { intfPureModule::stuDBInfo MasterDBInfo = { ServerConfigs::MasterDB::Schema.value(), ServerConfigs::MasterDB::Port.value(), @@ -111,14 +106,12 @@ void appTargomanAPI::slotExecute() DBManager::clsDAC::setConnectionString(ConnStr); } - for (auto DBInfoIter = RequiredDBs.begin(); DBInfoIter != RequiredDBs.end(); ++DBInfoIter) - { + for (auto DBInfoIter = RequiredDBs.begin(); DBInfoIter != RequiredDBs.end(); ++DBInfoIter) { QString ConnStr = DBInfoIter->toConnStr(ServerCommonConfigs::DBPrefix.value()/*true*/); if (DBInfoIter->Host.size() && DBInfoIter->Schema.size() - && ConnectionStrings.contains(ConnStr) == false) - { + && ConnectionStrings.contains(ConnStr) == false) { ConnectionStrings.insert(ConnStr); TargomanDebug(0, "Registering <" << DBInfoIter.key() << "> " << ConnStr); @@ -137,9 +130,7 @@ void appTargomanAPI::slotExecute() OpenAPIGenerator::retrieveJson(); TargomanInfo(5, "\n" + RESTAPIRegistry::registeredAPIs("", true, true).join("\n")); - } - catch(Targoman::Common::exTargomanBase& e) - { + } catch (Targoman::Common::exTargomanBase& e) { TargomanLogError(e.what()); QCoreApplication::exit(-1); } diff --git a/App/Server/clsAPIObject.cpp b/App/Server/clsAPIObject.cpp index ddac0165..9d34dd04 100644 --- a/App/Server/clsAPIObject.cpp +++ b/App/Server/clsAPIObject.cpp @@ -51,10 +51,9 @@ clsAPIObject::clsAPIObject(intfPureModule* _module, TTL(_ttl ? _ttl : ServerConfigs::APICallTimeout.value()), RequiredParamsCount(static_cast(_method.parameterCount())), HasExtraMethodName(_hasExtraMethodName), - Parent(_module) -{ + Parent(_module) { quint8 i = 0; - foreach(const QByteArray& ParamName, _method.parameterNames()){ + foreach(const QByteArray& ParamName, _method.parameterNames()) { this->ParamNames.append(ParamName.startsWith('_') ? ParamName.mid(1) : ParamName); this->ParamTypes.append(QMetaType::typeName(_method.parameterType(i))); ++i; @@ -62,7 +61,7 @@ clsAPIObject::clsAPIObject(intfPureModule* _module, } clsAPIObject::~clsAPIObject() -{} +{ ; } intfAPIArgManipulator* clsAPIObject::argSpecs(quint8 _paramIndex) const { if (this->BaseMethod.parameterType(_paramIndex) < TAPI_BASE_USER_DEFINED_TYPEID) @@ -86,20 +85,20 @@ QVariant clsAPIObject::invoke( Q_ASSERT_X(this->parent(), "parent module", "Parent module not found to invoke method"); int ExtraArgCount = 0; - if(this->ParamTypes.contains(PARAM_COOKIES)) + if (this->ParamTypes.contains(PARAM_COOKIES)) ExtraArgCount++; - if(this->ParamTypes.contains(PARAM_HEADERS)) + if (this->ParamTypes.contains(PARAM_HEADERS)) ExtraArgCount++; - if(this->ParamTypes.contains(PARAM_JWT)) + if (this->ParamTypes.contains(PARAM_JWT)) ExtraArgCount++; - if(this->ParamTypes.contains(PARAM_REMOTE_IP)) + if (this->ParamTypes.contains(PARAM_REMOTE_IP)) ExtraArgCount++; - if(this->ParamTypes.contains(PARAM_PKSBYPATH)) + if (this->ParamTypes.contains(PARAM_PKSBYPATH)) ExtraArgCount++; - if(this->ParamTypes.contains(PARAM_ORMFIELDS)) + if (this->ParamTypes.contains(PARAM_ORMFIELDS)) ExtraArgCount++; - if(_args.size() + _bodyArgs.size() + ExtraArgCount < this->RequiredParamsCount) + if (_args.size() + _bodyArgs.size() + ExtraArgCount < this->RequiredParamsCount) throw exHTTPBadRequest("Not enough arguments"); QVariantList Arguments; @@ -107,50 +106,50 @@ QVariant clsAPIObject::invoke( qint8 FirstArgumentWithValue = -1; qint8 LastArgumentWithValue = -1; - for(quint8 i=0; i< this->ParamNames.count(); ++i ){ + for (quint8 i=0; i< this->ParamNames.count(); ++i) { bool ParamNotFound = true; QVariant ArgumentValue; static auto parseArgValue = [ArgumentValue](const QString& _paramName, QString _value) -> QVariant { _value = _value.trimmed(); if ((_value.startsWith('[') && _value.endsWith(']')) || - (_value.startsWith('{') && _value.endsWith('}'))){ + (_value.startsWith('{') && _value.endsWith('}'))) { QJsonParseError Error; QJsonDocument JSON = QJsonDocument::fromJson(_value.toUtf8(), &Error); - if(JSON.isNull()) + if (JSON.isNull()) throw exHTTPBadRequest(QString("Invalid value for %1: %2").arg(_paramName).arg(Error.errorString())); return JSON.toVariant(); - }else{ + } else { return _value; } }; - if(this->ParamTypes.at(i) == PARAM_COOKIES){ + if (this->ParamTypes.at(i) == PARAM_COOKIES) { ParamNotFound = false; ArgumentValue = _cookies.toVariant(); } - if(ParamNotFound && this->ParamTypes.at(i) == PARAM_HEADERS){ + if (ParamNotFound && this->ParamTypes.at(i) == PARAM_HEADERS) { ParamNotFound = false; ArgumentValue = _headers.toVariant(); } - if(ParamNotFound && this->ParamTypes.at(i) == PARAM_JWT){ + if (ParamNotFound && this->ParamTypes.at(i) == PARAM_JWT) { ParamNotFound = false; ArgumentValue = _jwt; } - if(ParamNotFound && this->ParamTypes.at(i) == PARAM_REMOTE_IP){ + if (ParamNotFound && this->ParamTypes.at(i) == PARAM_REMOTE_IP) { ParamNotFound = false; ArgumentValue = _remoteIP; } - if(ParamNotFound && this->ParamTypes.at(i) == PARAM_PKSBYPATH){ + if (ParamNotFound && this->ParamTypes.at(i) == PARAM_PKSBYPATH) { ParamNotFound = false; ArgumentValue = _extraAPIPath; } - if(ParamNotFound && this->ParamTypes.at(i) == PARAM_ORMFIELDS){ + if (ParamNotFound && this->ParamTypes.at(i) == PARAM_ORMFIELDS) { ParamNotFound = false; TAPI::ORMFields_t ORMFields; foreach (const QString& Arg, _args) @@ -161,9 +160,9 @@ QVariant clsAPIObject::invoke( ArgumentValue = ORMFields; } - if(ParamNotFound) - foreach (const QString& Arg, _args){ - if(Arg.startsWith(this->ParamNames.at(i)+ '=')){ + if (ParamNotFound) + foreach (const QString& Arg, _args) { + if (Arg.startsWith(this->ParamNames.at(i)+ '=')) { ParamNotFound = false; ArgumentValue = parseArgValue(this->ParamNames.at(i), QUrl::fromPercentEncoding(Arg.mid(Arg.indexOf('=') + 1).toUtf8())); break; @@ -181,15 +180,14 @@ QVariant clsAPIObject::invoke( } if (ParamNotFound) { - if(i < this->RequiredParamsCount) + if (i < this->RequiredParamsCount) throw exHTTPBadRequest(QString("Required parameter <%1> not specified").arg(this->ParamNames.at(i).constData())); else if (_isUpdateMethod) Arguments.append(QVariant()); else Arguments.append(this->defaultValue(i)); continue; - } - else if(ArgumentValue.isValid() == false) + } else if (ArgumentValue.isValid() == false) throw exHTTPBadRequest(QString("Invalid value for %1: no conversion to QVariant defined").arg(this->ParamNames.at(i).constData())); if (FirstArgumentWithValue < 0) @@ -201,8 +199,7 @@ QVariant clsAPIObject::invoke( Q_ASSERT(gUserDefinedTypesInfo.at(this->BaseMethod.parameterType(i) - TAPI_BASE_USER_DEFINED_TYPEID) != nullptr); Arguments.push_back(ArgumentValue); - } - else { + } else { Q_ASSERT(this->BaseMethod.parameterType(i) < gOrderedMetaTypeInfo.size()); Q_ASSERT(gOrderedMetaTypeInfo.at(this->BaseMethod.parameterType(i)) != nullptr); @@ -232,7 +229,7 @@ QVariant clsAPIObject::invoke( if (this->Cache4SecsCentral) { QVariant CachedValue = CentralCache::storedValue(CacheKey); - if(CachedValue.isValid()){ + if (CachedValue.isValid()) { gServerStats.APICentralCacheStats[this->BaseMethod.name()].inc(); QVariantMap Map = CachedValue.toMap(); @@ -248,8 +245,7 @@ QVariant clsAPIObject::invoke( Q_ASSERT(gUserDefinedTypesInfo.at(this->BaseMethod.returnType() - TAPI_BASE_USER_DEFINED_TYPEID) != nullptr); APIMethod = gUserDefinedTypesInfo.at(this->BaseMethod.returnType() - TAPI_BASE_USER_DEFINED_TYPEID); - } - else { + } else { Q_ASSERT(this->BaseMethod.returnType() < gOrderedMetaTypeInfo.size()); Q_ASSERT(gOrderedMetaTypeInfo.at(this->BaseMethod.returnType()) != nullptr); @@ -289,9 +285,8 @@ void clsAPIObject::invokeMethod( InvokableMethod = this->LessArgumentMethods.at(this->ParamNames.size() - _arguments.size() - 1); #ifdef QT_DEBUG - if (InvokableMethod.name().toStdString() == "apiPOSTfixtureCleanup") - { - int i = 0; + if (InvokableMethod.name().toStdString() == "apiPOSTfixtureCleanup") { + int i; i = 0; } #endif @@ -299,15 +294,13 @@ void clsAPIObject::invokeMethod( QMetaObject::Connection Conn_addResponseHeader; - try - { + try { if (_arguments.size() > 10) throw exHTTPInternalServerError(QString("At most 10 method params are supported")); QGenericArgument Arguments[10]; - for (int i=0; i<10; ++i) - { + for (int i=0; i<10; ++i) { if (i < _arguments.size()) Arguments[i] = USE_ARG_AT(i); else @@ -348,28 +341,27 @@ void clsAPIObject::invokeMethod( for (int i=0; i<_arguments.size(); ++i) CLEAN_ARG_AT(i); - } - catch(...) - { + } catch (...) { QObject::disconnect(Conn_addResponseHeader); for (int i=0; i<_arguments.size(); ++i) CLEAN_ARG_AT(i); + throw; } } bool clsAPIObject::isPolymorphic(const QMetaMethodExtended& _method) { - if(_method.parameterCount() == 0) + if (_method.parameterCount() == 0) return false; - for(int i=0; i< qMin(_method.parameterCount(), this->BaseMethod.parameterCount()); ++i) - if(this->BaseMethod.parameterType(i) != _method.parameterType(i)) + for (int i=0; i< qMin(_method.parameterCount(), this->BaseMethod.parameterCount()); ++i) + if (this->BaseMethod.parameterType(i) != _method.parameterType(i)) return true; return false; } void clsAPIObject::updateDefaultValues(const QMetaMethodExtended& _method) { - if(_method.parameterNames().size() < this->RequiredParamsCount){ + if (_method.parameterNames().size() < this->RequiredParamsCount) { this->RequiredParamsCount = static_cast(_method.parameterNames().size()); this->LessArgumentMethods.append(_method); } diff --git a/App/Server/clsAPIObject.h b/App/Server/clsAPIObject.h index 92ef5d5c..7a2684de 100644 --- a/App/Server/clsAPIObject.h +++ b/App/Server/clsAPIObject.h @@ -42,11 +42,11 @@ namespace Targoman::API::Server { class QMetaMethodExtended : public QMetaMethod { public: - QMetaMethodExtended(QMetaMethod _metaMethod, QVariantList _defaultValues, QString _doc): + QMetaMethodExtended(QMetaMethod _metaMethod, QVariantList _defaultValues, QString _doc) : QMetaMethod(_metaMethod), Doc(_doc), DefaultValues(_defaultValues) - {} + { ; } QString Doc; QVariantList DefaultValues; diff --git a/App/Server/clsRedisConnector.cpp b/App/Server/clsRedisConnector.cpp index 824b8cb2..82e48b9b 100644 --- a/App/Server/clsRedisConnector.cpp +++ b/App/Server/clsRedisConnector.cpp @@ -35,52 +35,47 @@ namespace Server { clsRedisConnector::clsRedisConnector(const QUrl& _connector) : intfCacheConnector(_connector) -{ -} +{ ; } -void clsRedisConnector::connect() -{ +void clsRedisConnector::connect() { struct timeval Timeout = { 1, 500000 }; // 1.5 seconds - if(this->ConnectorURL.port() == 1) + if (this->ConnectorURL.port() == 1) this->Connection.reset(redisConnectUnixWithTimeout(this->ConnectorURL.host().toLatin1().constData(), Timeout)); else this->Connection.reset(redisConnectWithTimeout(this->ConnectorURL.host().toLatin1().constData(), this->ConnectorURL.port(), Timeout)); - if(this->Connection.isNull() || this->Connection->err) + if (this->Connection.isNull() || this->Connection->err) throw exCacheConnector(this->Connection.isNull() ? "can't allocate Redis context" : this->Connection->errstr); redisSetTimeout(this->Connection.data(), Timeout); } -bool clsRedisConnector::reconnect() -{ - try{ - if(this->Connection.isNull()){ +bool clsRedisConnector::reconnect() { + try { + if (this->Connection.isNull()) { this->connect(); - }else + } else return redisReconnect(this->Connection.data()); - }catch(exCacheConnector& ex){ + } catch (exCacheConnector& ex) { TargomanLogWarn(1, ex.what()); return false; } return true; } -void clsRedisConnector::setKeyValImpl(const QString& _key, const QString& _value, qint32 _ttl) -{ - if(this->Connection.isNull() || this->Connection->err) +void clsRedisConnector::setKeyValImpl(const QString& _key, const QString& _value, qint32 _ttl) { + if (this->Connection.isNull() || this->Connection->err) this->reconnect(); if (!redisCommand(this->Connection.data(), "SETEX %s %d %s", qPrintable(_key), _ttl, _value.toUtf8().constData())) TargomanWarn(1, this->Connection->errstr); } -QString clsRedisConnector::getValueImpl(const QString& _key) -{ +QString clsRedisConnector::getValueImpl(const QString& _key) { void *Reply = nullptr; Reply = redisCommand(this->Connection.data(), "GET %s", qPrintable(_key)); // You must define "context" previously - if (!Reply){ + if (!Reply) { TargomanWarn(1, this->Connection->errstr); return ""; } diff --git a/App/Server/clsRequestHandler.cpp b/App/Server/clsRequestHandler.cpp index 049a1e3f..71c22e0b 100644 --- a/App/Server/clsRequestHandler.cpp +++ b/App/Server/clsRequestHandler.cpp @@ -50,17 +50,13 @@ using namespace Targoman::Common; clsRequestHandler::clsRequestHandler(QHttpRequest *_req, QHttpResponse *_res, QObject* _parent) : QObject(_parent), Request(_req), - Response(_res) -{ + Response(_res) { this->ElapsedTimer.start(); } -void clsRequestHandler::process(const QString& _api) -{ - this->Request->onData([this](QByteArray _data ) - { - try - { +void clsRequestHandler::process(const QString& _api) { + this->Request->onData([this](QByteArray _data ) { + try { TargomanLogInfo(7, "posted data: " << _data); QByteArray ContentType = this->Request->headers().value("content-type"); @@ -81,8 +77,7 @@ void clsRequestHandler::process(const QString& _api) if (ContentLength > ServerConfigs::MaxUploadSize.value()) throw exHTTPPayloadTooLarge(QString("Content-Size is too large: %d").arg(ContentLength)); - switch(this->Request->method()) - { + switch (this->Request->method()) { case qhttp::EHTTP_POST: case qhttp::EHTTP_PUT: case qhttp::EHTTP_PATCH: @@ -95,33 +90,26 @@ void clsRequestHandler::process(const QString& _api) static constexpr char APPLICATION_FORM_HEADER[] = "application/x-www-form-urlencoded"; static constexpr char MULTIPART_BOUNDARY_HEADER[] = "multipart/form-data; boundary="; - switch (ContentType.at(0)) - { + switch (ContentType.at(0)) { case 'a': { if (ContentType != APPLICATION_JSON_HEADER && ContentType != APPLICATION_FORM_HEADER) throw exHTTPBadRequest(("unsupported Content-Type: " + ContentType).constData()); if (_data.size() == ContentLength) - { this->RemainingData = _data; - } - else if (this->RemainingData.size()) - { + else if (this->RemainingData.size()) { this->RemainingData += _data; - if(this->RemainingData.size() < ContentLength) + if (this->RemainingData.size() < ContentLength) return; - } - else - { + } else { this->RemainingData = _data; return; } this->RemainingData = this->RemainingData.trimmed(); - if (this->RemainingData.startsWith('{') || this->RemainingData.startsWith('[')) - { + if (this->RemainingData.startsWith('{') || this->RemainingData.startsWith('[')) { if (this->RemainingData.startsWith('{') == false || this->RemainingData.endsWith('}') == false) throw exHTTPBadRequest("Invalid JSON Object"); @@ -135,8 +123,7 @@ void clsRequestHandler::process(const QString& _api) for (auto JSONObjectIter = JSONObject.begin(); JSONObjectIter != JSONObject.end(); - ++JSONObjectIter) - { + ++JSONObjectIter) { if (JSONObjectIter.value().isBool()) this->Request->addUserDefinedData(JSONObjectIter.key(), JSONObjectIter.value().toBool() ? "1" : "0"); else if (JSONObjectIter.value().isNull()) @@ -150,13 +137,10 @@ void clsRequestHandler::process(const QString& _api) else this->Request->addUserDefinedData(JSONObjectIter.key(), JSONObjectIter.value().toString()); } - } - else - { + } else { QList Params = this->RemainingData.split('&'); - static auto decodePercentEncoding = [](QByteArray& _value) - { + static auto decodePercentEncoding = [](QByteArray& _value) { _value = _value.replace("+"," "); QUrl URL = QUrl::fromPercentEncoding("http://127.0.0.1/?key=" + _value); _value=URL.query(QUrl::FullyDecoded).toUtf8(); @@ -164,10 +148,9 @@ void clsRequestHandler::process(const QString& _api) return _value; }; - foreach (auto Param, Params) - { + foreach (auto Param, Params) { QList ParamParts = Param.split('='); - if(ParamParts.size() != 2) + if (ParamParts.size() != 2) throw exHTTPBadRequest("Invalid Param: " + Param); this->Request->addUserDefinedData(ParamParts.first(), decodePercentEncoding(ParamParts.last())); } @@ -176,8 +159,7 @@ void clsRequestHandler::process(const QString& _api) } case 'm': { - if (this->MultipartFormDataHandler.isNull()) - { + if (this->MultipartFormDataHandler.isNull()) { if (ContentType.startsWith(MULTIPART_BOUNDARY_HEADER) == false) throw exHTTPBadRequest(("unsupported Content-Type: " + ContentType + " must be " + MULTIPART_BOUNDARY_HEADER).constData()); @@ -189,8 +171,7 @@ void clsRequestHandler::process(const QString& _api) } qlonglong Fed = 0; - while (!this->MultipartFormDataHandler->stopped() && _data.size() > Fed) - { + while (!this->MultipartFormDataHandler->stopped() && _data.size() > Fed) { do { qulonglong Ret = this->MultipartFormDataHandler->feed(_data.mid(static_cast(Fed)).constData(), _data.size() - Fed); @@ -206,56 +187,35 @@ void clsRequestHandler::process(const QString& _api) } TargomanLogInfo(7, "request user defined values: "); - foreach (auto val, this->Request->userDefinedValues()) - { + foreach (auto val, this->Request->userDefinedValues()) { TargomanLogInfo(7, val.first << " : " << val.second); } - } - catch(exTargomanBase& ex) - { + } catch (exTargomanBase& ex) { this->sendError(static_cast(ex.httpCode()), ex.what(), {}, ex.httpCode() >= 500); - } - catch(exQFVRequiredParam &ex) - { + } catch (exQFVRequiredParam &ex) { this->sendError(qhttp::ESTATUS_BAD_REQUEST, ex.what(), {}, false); - } - catch(exQFVInvalidValue &ex) - { + } catch (exQFVInvalidValue &ex) { this->sendError(qhttp::ESTATUS_BAD_REQUEST, ex.what(), {}, false); - } - catch(std::exception &ex) - { + } catch (std::exception &ex) { this->sendError(qhttp::ESTATUS_INTERNAL_SERVER_ERROR, ex.what(), {}, true); } }); - this->Request->onEnd([this, _api]() - { - try - { + this->Request->onEnd([this, _api]() { + try { if (this->Request->method() == qhttp::EHTTP_OPTIONS) this->sendCORSOptions(); else this->findAndCallAPI (_api); - } - catch(exTargomanBase& ex) - { + } catch (exTargomanBase& ex) { this->sendError(static_cast(ex.httpCode()), ex.what(), {}, ex.httpCode() >= 500); - } - catch(exQFVRequiredParam &ex) - { + } catch (exQFVRequiredParam &ex) { this->sendError(qhttp::ESTATUS_BAD_REQUEST, ex.what(), {}, false); - } - catch(exQFVInvalidValue &ex) - { + } catch (exQFVInvalidValue &ex) { this->sendError(qhttp::ESTATUS_BAD_REQUEST, ex.what(), {}, false); - } - catch(std::exception &ex) - { + } catch (std::exception &ex) { this->sendError(qhttp::ESTATUS_INTERNAL_SERVER_ERROR, ex.what(), {}, true); - } - catch(...) - { + } catch (...) { this->sendError(qhttp::ESTATUS_INTERNAL_SERVER_ERROR, "", {}, true); } }); @@ -304,12 +264,10 @@ const qhttp::TStatusCode StatusCodeOnMethod[] = { qhttp::ESTATUS_EXPECTATION_FAILED, ///< EHTTP_UNLINK = 32, }; -clsRequestHandler::stuResult clsRequestHandler::run(clsAPIObject* _apiObject, QStringList& _queries, const QString& _pksByPath) -{ +clsRequestHandler::stuResult clsRequestHandler::run(clsAPIObject* _apiObject, QStringList& _queries, const QString& _pksByPath) { QVariantMap ResponseHeaders; - try - { + try { for (auto QueryIter = _queries.begin(); QueryIter != _queries.end(); ++QueryIter) *QueryIter = QueryIter->replace('+', ' '); @@ -320,26 +278,21 @@ clsRequestHandler::stuResult clsRequestHandler::run(clsAPIObject* _apiObject, QS qhttp::THeaderHash Cookies; TAPI::JWT_t JWT; - if (_apiObject->requiresJWT()) - { + if (_apiObject->requiresJWT()) { QString Auth = Headers.value("authorization"); - if (Auth.startsWith("Bearer ")) - { + if (Auth.startsWith("Bearer ")) { QString BearerToken = Auth.mid(sizeof("Bearer")); Headers.remove("authorization"); QString RemoteIP = this->toIPv4(this->Request->remoteAddress()); - try - { + try { QJWT::verifyJWT( BearerToken, RemoteIP, JWT ); - } - catch (exJWTExpired &exp) - { + } catch (exJWTExpired &exp) { QString NewToken = Authentication::renewJWT( JWT, RemoteIP @@ -349,15 +302,12 @@ clsRequestHandler::stuResult clsRequestHandler::run(clsAPIObject* _apiObject, QS ResponseHeaders.insert("x-auth-new-token", BearerToken); } JWT["encodedJWT"] = BearerToken; - } - else + } else throw exHTTPForbidden("No valid authentication header is present"); } - if (_apiObject->requiresCookies() && Headers.value("cookie").size()) - { - foreach (auto Cookie, Headers.value("cookie").split(';')) - { + if (_apiObject->requiresCookies() && Headers.value("cookie").size()) { + foreach (auto Cookie, Headers.value("cookie").split(';')) { auto CookieParts = Cookie.split('='); Cookies.insert(CookieParts.first(), CookieParts.size() > 1 ? CookieParts.last() : QByteArray()); } @@ -378,25 +328,15 @@ clsRequestHandler::stuResult clsRequestHandler::run(clsAPIObject* _apiObject, QS ); return stuResult(Result, ResponseHeaders); - } - catch (exTargomanBase& ex) - { + } catch (exTargomanBase& ex) { return stuResult(ex.what(), ResponseHeaders, static_cast(ex.httpCode())); - } - catch (exQFVRequiredParam &ex) - { + } catch (exQFVRequiredParam &ex) { return stuResult(ex.what(), ResponseHeaders, qhttp::ESTATUS_BAD_REQUEST); - } - catch (exQFVInvalidValue &ex) - { + } catch (exQFVInvalidValue &ex) { return stuResult(ex.what(), ResponseHeaders, qhttp::ESTATUS_BAD_REQUEST); - } - catch (std::exception &ex) - { + } catch (std::exception &ex) { return stuResult(ex.what(), ResponseHeaders, qhttp::ESTATUS_INTERNAL_SERVER_ERROR); - } - catch (...) - { + } catch (...) { return stuResult("INTERNAL SERVER ERROR!!!", ResponseHeaders, qhttp::ESTATUS_INTERNAL_SERVER_ERROR); } } @@ -432,10 +372,8 @@ quint16 clsRequestHandler::port() const return Host.mid(idx+1).toUInt(); } -bool clsRequestHandler::callStaticAPI(QString _api) -{ - if (_api == "/openAPI.json") - { +bool clsRequestHandler::callStaticAPI(QString _api) { + if (_api == "/openAPI.json") { gServerStats.Success.inc(); this->sendResponseBase( qhttp::ESTATUS_OK, @@ -448,17 +386,14 @@ bool clsRequestHandler::callStaticAPI(QString _api) _api.replace(QRegularExpression("//+"), "/"); - if (_api.toLower().startsWith("/swaggerui")) - { - if (ServerConfigs::SwaggerUI.value().isEmpty()) - { + if (_api.toLower().startsWith("/swaggerui")) { + if (ServerConfigs::SwaggerUI.value().isEmpty()) { this->sendError(qhttp::ESTATUS_NOT_FOUND, "Swagger is not configured"); return true; } QString File = _api.mid(sizeof("/swaggerUI") - 1).replace(QRegularExpression("//+"), "/"); - if (File.isEmpty()) - { + if (File.isEmpty()) { this->redirect(_api + "/"); return true; } @@ -472,15 +407,13 @@ bool clsRequestHandler::callStaticAPI(QString _api) QStringList Queries = this->Request->url().query().split('&', QString::SkipEmptyParts); - if (_api == "/stats.json") - { + if (_api == "/stats.json") { gServerStats.Success.inc(); this->sendResponseBase(qhttp::ESTATUS_OK, gServerStats.toJson(Queries.contains("full=true"))); return true; } - if (_api == "/version") - { + if (_api == "/version") { gServerStats.Success.inc(); QJsonObject Version; Version.insert("version", TARGOMAN_M2STR(PROJ_VERSION)); @@ -491,8 +424,7 @@ bool clsRequestHandler::callStaticAPI(QString _api) return true; } - if (_api == "/ping") - { + if (_api == "/ping") { gServerStats.Success.inc(); this->sendResponseBase(qhttp::ESTATUS_OK, QJsonObject({ { "timestamp", QDateTime::currentDateTime().toMSecsSinceEpoch() }, @@ -503,8 +435,7 @@ bool clsRequestHandler::callStaticAPI(QString _api) return false; } -void clsRequestHandler::findAndCallAPI(QString _api) -{ +void clsRequestHandler::findAndCallAPI(QString _api) { if (this->callStaticAPI(_api)) return; @@ -550,8 +481,7 @@ void clsRequestHandler::findAndCallAPI(QString _api) if (ServerConfigs::APICallTimeout.value() > -1) this->FutureTimer.start(APIObject->ttl()); - } - else + } else run(APIObject, Queries, ExtraAPIPath); } @@ -575,8 +505,7 @@ void clsRequestHandler::sendError(qhttp::TStatusCode _code, _closeConnection); } -void clsRequestHandler::sendFile(const QString& _basePath, const QString _path) -{ +void clsRequestHandler::sendFile(const QString& _basePath, const QString _path) { if (QFile::exists(_basePath + _path) == false) throw exHTTPNotFound(_path); @@ -605,17 +534,14 @@ void clsRequestHandler::sendFile(const QString& _basePath, const QString _path) QTimer::singleShot(10, this, &clsRequestHandler::slotSendFileData); } -void clsRequestHandler::addHeaderValues(const QVariantMap &_responseHeaders) -{ - if (_responseHeaders.isEmpty() == false) - { +void clsRequestHandler::addHeaderValues(const QVariantMap &_responseHeaders) { + if (_responseHeaders.isEmpty() == false) { TargomanLogInfo(7, "Response Custom Header Values:"); for (QVariantMap::const_iterator it = _responseHeaders.constBegin(); it != _responseHeaders.constEnd(); ++it - ) - { + ) { TargomanLogInfo(7, " " << it.key().toLatin1() @@ -640,8 +566,7 @@ void clsRequestHandler::sendResponse(qhttp::TStatusCode _code, if (_response.isValid() == false) this->sendResponseBase(_code, QJsonObject({ { "result", QJsonValue(QJsonValue::Undefined) } }), _responseHeaders); - else if (strcmp(_response.typeName(), "TAPI::RawData_t") == 0) - { + else if (strcmp(_response.typeName(), "TAPI::RawData_t") == 0) { TAPI::RawData_t RawData = qvariant_cast(_response); TargomanLogInfo(7, @@ -686,13 +611,11 @@ void clsRequestHandler::sendResponse(qhttp::TStatusCode _code, this->Response->end(RawData.data()); this->deleteLater(); - } - else + } else this->sendResponseBase(_code, QJsonObject({{"result", QJsonValue::fromVariant(_response) }}), _responseHeaders); } -void clsRequestHandler::sendCORSOptions() -{ +void clsRequestHandler::sendCORSOptions() { this->Response->addHeaderValue("Access-Control-Allow-Origin", ServerConfigs::AccessControl.value()); this->Response->addHeaderValue("Access-Control-Allow-Credentials", QStringLiteral("true")); this->Response->addHeaderValue("Access-Control-Allow-Methods", @@ -725,8 +648,7 @@ void clsRequestHandler::sendCORSOptions() this->deleteLater(); } -void clsRequestHandler::redirect(const QString _path, bool _appendBase, bool _permananet) -{ +void clsRequestHandler::redirect(const QString _path, bool _appendBase, bool _permananet) { QString Path = _appendBase ? ServerConfigs::BasePathWithVersion + _path : _path; Path = Path.replace(QRegularExpression("//+"), "/"); @@ -795,9 +717,8 @@ void clsRequestHandler::sendResponseBase(qhttp::TStatusCode _code, this->deleteLater(); } -void clsRequestHandler::slotSendFileData() -{ - if(this->FileHandler.isNull() || this->FileHandler->atEnd()){ +void clsRequestHandler::slotSendFileData() { + if (this->FileHandler.isNull() || this->FileHandler->atEnd()) { // this->Response->end(); this->deleteLater(); return; @@ -810,9 +731,9 @@ void clsRequestHandler::slotSendFileData() /**************************************************************************/ void clsMultipartFormDataRequestHandler::onMultiPartBegin(const MultipartHeaders& _headers, void *_userData) { clsMultipartFormDataRequestHandler *Self = static_cast(_userData); - try{ + try { std::string ContentDisposition = _headers["Content-Disposition"]; - if(ContentDisposition.size()){ + if (ContentDisposition.size()) { const char* pContentDisposition = ContentDisposition.c_str(); const char* pBufferStart = pContentDisposition; enum enuLooking4{ @@ -826,66 +747,66 @@ void clsMultipartFormDataRequestHandler::onMultiPartBegin(const MultipartHeaders std::string* pLastFieldValue = nullptr; std::string Dummy; - while(pContentDisposition && *pContentDisposition != '\0'){ - if (*pContentDisposition == StopChar) - switch(Looking4){ - case L4Type: - if(strncmp(pBufferStart, "form-data", static_cast(pContentDisposition - pBufferStart))) - throw exHTTPBadRequest("Just form-data is allowed in multi-part request according to RFC7578"); - Looking4 = L4Field; - pBufferStart = pContentDisposition+1; - StopChar = '='; - break; - case L4Field: - if(strncmp(pBufferStart, " name", static_cast(pContentDisposition - pBufferStart)) == 0) - pLastFieldValue = &Self->LastItemName; - else if(strncmp(pBufferStart, " filename", static_cast(pContentDisposition - pBufferStart)) == 0) - pLastFieldValue = &Self->LastFileName; - else - pLastFieldValue = &Dummy; - Looking4 = L4DQuote; - StopChar = '"'; - break; - case L4NextField: - Looking4 = L4Field; - pBufferStart = pContentDisposition+1; - StopChar = '='; - break; - case L4DQuote: - Looking4 = L4Value; - StopChar = '"'; - pBufferStart = pContentDisposition+1; - break; - case L4Value: - *pLastFieldValue = pBufferStart; - pLastFieldValue->erase(static_cast(pContentDisposition - pBufferStart), std::string::npos); - StopChar=';'; - Looking4 = L4NextField; - pBufferStart = pContentDisposition+2; - break; + while (pContentDisposition && *pContentDisposition != '\0') { + if (*pContentDisposition == StopChar) { + switch (Looking4) { + case L4Type: + if (strncmp(pBufferStart, "form-data", static_cast(pContentDisposition - pBufferStart))) + throw exHTTPBadRequest("Just form-data is allowed in multi-part request according to RFC7578"); + Looking4 = L4Field; + pBufferStart = pContentDisposition+1; + StopChar = '='; + break; + case L4Field: + if (strncmp(pBufferStart, " name", static_cast(pContentDisposition - pBufferStart)) == 0) + pLastFieldValue = &Self->LastItemName; + else if (strncmp(pBufferStart, " filename", static_cast(pContentDisposition - pBufferStart)) == 0) + pLastFieldValue = &Self->LastFileName; + else + pLastFieldValue = &Dummy; + Looking4 = L4DQuote; + StopChar = '"'; + break; + case L4NextField: + Looking4 = L4Field; + pBufferStart = pContentDisposition+1; + StopChar = '='; + break; + case L4DQuote: + Looking4 = L4Value; + StopChar = '"'; + pBufferStart = pContentDisposition+1; + break; + case L4Value: + *pLastFieldValue = pBufferStart; + pLastFieldValue->erase(static_cast(pContentDisposition - pBufferStart), std::string::npos); + StopChar=';'; + Looking4 = L4NextField; + pBufferStart = pContentDisposition+2; + break; } - else if (*pContentDisposition == '\r') + } else if (*pContentDisposition == '\r') break; ++pContentDisposition; } - if(Self->LastItemName.empty()) + if (Self->LastItemName.empty()) throw exHTTPBadRequest(QString("No name provided for form field: ") + ContentDisposition.c_str()); - if(Self->ToBeStoredItemName.empty()) + if (Self->ToBeStoredItemName.empty()) Self->ToBeStoredItemName = Self->LastItemName; - if(Self->LastFileName.size()){ + if (Self->LastFileName.size()) { Self->LastTempFile.reset(new QTemporaryFile); - if(Self->LastTempFile.isNull() || Self->LastTempFile->open() == false) + if (Self->LastTempFile.isNull() || Self->LastTempFile->open() == false) throw exHTTPInternalServerError("unable to create temporary file"); Self->LastTempFile->setAutoRemove(false); Self->LastMime = _headers["Content-Type"]; } - }else + } else throw exHTTPBadRequest("No Content-Disposition header provided"); - }catch(exHTTPError& ex){ + } catch (exHTTPError& ex) { Self->pRequestHandler->sendError(static_cast(ex.code()), ex.what(), {}, ex.code() >= 500); - }catch(exTargomanBase& ex){ + } catch (exTargomanBase& ex) { Self->pRequestHandler->sendError(qhttp::ESTATUS_INTERNAL_SERVER_ERROR, ex.what(), {}, true); } @@ -893,22 +814,22 @@ void clsMultipartFormDataRequestHandler::onMultiPartBegin(const MultipartHeaders void clsMultipartFormDataRequestHandler::onMultiPartData(const char *_buffer, long long _size, void *_userData) { clsMultipartFormDataRequestHandler *Self = static_cast(_userData); - if(Self->LastTempFile.isNull() == false){ + if (Self->LastTempFile.isNull() == false) { Self->LastWrittenBytes += Self->LastTempFile->write(_buffer, _size); - if(Self->LastWrittenBytes > ServerConfigs::MaxUploadedFileSize.value()) + if (Self->LastWrittenBytes > ServerConfigs::MaxUploadedFileSize.value()) throw exHTTPPayloadTooLarge("Max file size limit reached"); - }else + } else Self->LastValue = QString::fromUtf8(_buffer, static_cast(_size)); } void clsMultipartFormDataRequestHandler::onMultiPartEnd(void *_userData) { clsMultipartFormDataRequestHandler *Self = static_cast(_userData); - if(Self->ToBeStoredItemName != Self->LastItemName){ + if (Self->ToBeStoredItemName != Self->LastItemName) { Self->storeDataInRequest(); Self->SameNameItems.clear(); Self->ToBeStoredItemName = Self->LastItemName; } - if(Self->LastTempFile.isNull() == false){ + if (Self->LastTempFile.isNull() == false) { Self->SameNameItems.append( QJsonDocument(QJsonObject::fromVariantMap(TAPI::stuFileInfo( Self->LastFileName.c_str(), @@ -916,7 +837,7 @@ void clsMultipartFormDataRequestHandler::onMultiPartEnd(void *_userData) { static_cast(Self->LastWrittenBytes), Self->LastMime.c_str()).toVariant().toMap())).toJson(QJsonDocument::Compact)); Self->LastTempFile.reset(); - }else + } else Self->SameNameItems.append(Self->LastValue); @@ -926,32 +847,29 @@ void clsMultipartFormDataRequestHandler::onMultiPartEnd(void *_userData) { Self->LastWrittenBytes = 0; } -void clsMultipartFormDataRequestHandler::onDataEnd(void *_userData){ +void clsMultipartFormDataRequestHandler::onDataEnd(void *_userData) { clsMultipartFormDataRequestHandler *Self = static_cast(_userData); - if(Self->SameNameItems.size()) + if (Self->SameNameItems.size()) Self->storeDataInRequest(); } -void clsMultipartFormDataRequestHandler::storeDataInRequest() -{ - if(this->SameNameItems.size() > 1) +void clsMultipartFormDataRequestHandler::storeDataInRequest() { + if (this->SameNameItems.size() > 1) this->pRequestHandler->Request->addUserDefinedData(this->ToBeStoredItemName.c_str(), QString("[%1]").arg(this->SameNameItems.join(','))); else this->pRequestHandler->Request->addUserDefinedData(this->ToBeStoredItemName.c_str(), this->SameNameItems.at(0)); } -QString clsRequestHandler::toIPv4(const QString _ip) -{ - if(_ip.startsWith("::")) +QString clsRequestHandler::toIPv4(const QString _ip) { + if (_ip.startsWith("::")) return _ip.mid(_ip.lastIndexOf(':') + 1); return _ip; } -void clsUpdateAndPruneThread::run() -{ +void clsUpdateAndPruneThread::run() { QTimer Timer; - QObject::connect(&Timer, &QTimer::timeout, [](){ + QObject::connect(&Timer, &QTimer::timeout, []() { gServerStats.Connections.snapshot(ServerConfigs::StatisticsInterval.value()); gServerStats.WSConnections.snapshot(ServerConfigs::StatisticsInterval.value()); gServerStats.Errors.snapshot(ServerConfigs::StatisticsInterval.value()); @@ -968,13 +886,13 @@ void clsUpdateAndPruneThread::run() ListIter->snapshot(ServerConfigs::StatisticsInterval.value()); QList ToDeleteIters; - for(auto CacheIter = InternalCache::Cache.begin(); + for (auto CacheIter = InternalCache::Cache.begin(); CacheIter != InternalCache::Cache.end(); ++CacheIter) - if(CacheIter->InsertionTime.secsTo(QTime::currentTime()) > CacheIter->TTL) + if (CacheIter->InsertionTime.secsTo(QTime::currentTime()) > CacheIter->TTL) ToDeleteIters.append(CacheIter); - if(ToDeleteIters.size()){ + if (ToDeleteIters.size()) { QMutexLocker Locker(&InternalCache::Lock); foreach(auto Iter, ToDeleteIters) InternalCache::Cache.erase(Iter); diff --git a/App/Server/clsRequestHandler.h b/App/Server/clsRequestHandler.h index 197e730a..620ded63 100644 --- a/App/Server/clsRequestHandler.h +++ b/App/Server/clsRequestHandler.h @@ -50,8 +50,7 @@ class clsMultipartFormDataRequestHandler : public MultipartReader clsMultipartFormDataRequestHandler(clsRequestHandler* _parent, const QByteArray& _marker) : MultipartReader(_marker.toStdString()), pRequestHandler(_parent), - LastWrittenBytes(0) - { + LastWrittenBytes(0) { this->onPartBegin = clsMultipartFormDataRequestHandler::onMultiPartBegin; this->onPartData = clsMultipartFormDataRequestHandler::onMultiPartData; this->onPartEnd = clsMultipartFormDataRequestHandler::onMultiPartEnd; @@ -59,8 +58,7 @@ class clsMultipartFormDataRequestHandler : public MultipartReader this->userData = reinterpret_cast(this); } - size_t feed(const char *_buffer, long long _len) - { + size_t feed(const char *_buffer, long long _len) { return static_cast(MultipartReader::feed(_buffer, _len)); } @@ -103,7 +101,7 @@ class clsRequestHandler : public QObject StatusCode(_code), Result(_result), ResponseHeader(_responseHeaders) - {} + { ; } }; public: diff --git a/App/Server/intfCacheConnector.hpp b/App/Server/intfCacheConnector.hpp index 09e62cf7..43a6221c 100644 --- a/App/Server/intfCacheConnector.hpp +++ b/App/Server/intfCacheConnector.hpp @@ -43,13 +43,13 @@ class intfCacheConnector{ public: intfCacheConnector(const QUrl& _connector) : ConnectorURL(_connector) - {} + { ; } virtual ~intfCacheConnector(); virtual void connect() = 0; void setKeyVal(const QString& _key, const QVariant& _value, qint32 _ttl); - QVariant getValue(const QString& _key){ + QVariant getValue(const QString& _key) { return this->getValueImpl (_key); } diff --git a/App/Server/main.cpp b/App/Server/main.cpp index c53e6e9d..55d36e1e 100644 --- a/App/Server/main.cpp +++ b/App/Server/main.cpp @@ -38,8 +38,7 @@ static const char* LicenseStr = using namespace Targoman::Common; using namespace Targoman::API::Server; -int main(int _argc, char *_argv[]) -{ +int main(int _argc, char *_argv[]) { /* static const QVariant QNull = QVariant(QVariant::Line); static const QVariant QInvalid = QVariant(QVariant::Invalid); @@ -61,8 +60,7 @@ int main(int _argc, char *_argv[]) exit(0);*/ - try - { + try { QCoreApplication App(_argc, _argv); #pragma GCC diagnostic push @@ -74,20 +72,14 @@ int main(int _argc, char *_argv[]) #pragma GCC diagnostic pop QTimer::singleShot(10, new appTargomanAPI, SLOT(slotExecute())); - return App.exec(); - } - catch(exTargomanBase& ex) - { + } catch (exTargomanBase& ex) { TargomanError(ex.what()); - } - catch (std::exception& ex) - { + } catch (std::exception& ex) { TargomanError(ex.what()); - } - catch(...) - { + } catch (...) { TargomanError("FATAL Unrecognized exception"); } + return -1; } diff --git a/Interfaces/AAA/Accounting_Defs.hpp b/Interfaces/AAA/Accounting_Defs.hpp index 9ef8c38d..5477a0cf 100644 --- a/Interfaces/AAA/Accounting_Defs.hpp +++ b/Interfaces/AAA/Accounting_Defs.hpp @@ -131,7 +131,7 @@ struct stuUsageColDefinition { stuUsageColDefinition(const QString& _perDay, const QString& _perWeek, const QString& _perMonth, const QString& _total) : PerDay(_perDay), PerWeek(_perWeek), PerMonth(_perMonth), Total(_total) - {} + { ; } }; typedef QMap AssetUsageLimitsCols_t; @@ -222,8 +222,8 @@ TAPI_DEFINE_VARIANT_ENABLED_STRUCT(stuPreVoucher, /* name */ Items, /* def */ InvItems_t(), /* validator */ v.size(), - /* fromVariant */ [](auto v){QJsonArray A; foreach(auto a, v) A.append(a.toJson()); return A;}(v), - /* toVariant */ [](auto v){InvItems_t L; foreach(auto I, v.toArray()) L.append(Targoman::API::AAA::stuVoucherItem().fromJson(I.toObject())); return L;}(v) + /* fromVariant */ [](auto v) {QJsonArray A; foreach(auto a, v) A.append(a.toJson()); return A;}(v), + /* toVariant */ [](auto v) {InvItems_t L; foreach(auto I, v.toArray()) L.append(Targoman::API::AAA::stuVoucherItem().fromJson(I.toObject())); return L;}(v) ), SF_Struct(stuPrize, Prize, v.Desc.size()), SF_QString(Summary), diff --git a/Interfaces/AAA/Accounting_Interfaces.cpp b/Interfaces/AAA/Accounting_Interfaces.cpp index 778fc090..bbf96457 100644 --- a/Interfaces/AAA/Accounting_Interfaces.cpp +++ b/Interfaces/AAA/Accounting_Interfaces.cpp @@ -44,8 +44,7 @@ TAPI_REGISTER_METATYPE( }, /* fromVariantLambda */ [](const QVariant& _value, const QByteArray& _paramName) -> stuVoucherItem { // qDebug() << "stuVoucherItem(2) =================================" << _paramName << ":" << _value; - if (_value.isValid() == false) - { + if (_value.isValid() == false) { // qDebug() << "stuVoucherItem(2.1) =================================" << _paramName << ":" << _value; return stuVoucherItem(); } @@ -53,15 +52,13 @@ TAPI_REGISTER_METATYPE( if (_value.canConvert() // || _value.canConvert() // || _value.canConvert() - ) - { + ) { auto ret = QJsonDocument::fromVariant(_value); // qDebug() << "stuVoucherItem(2.2) =================================" << _paramName << ":" << _value << "=" << ret.object(); return stuVoucherItem().fromJson(ret.object()); } - if (_value.toString().isEmpty()) - { + if (_value.toString().isEmpty()) { // qDebug() << "stuVoucherItem(2.3) =================================" << _paramName << ":" << _value; return stuVoucherItem(); } @@ -89,8 +86,7 @@ TAPI_REGISTER_METATYPE( }, /* fromVariantLambda */ [](const QVariant& _value, const QByteArray& _paramName) -> stuPreVoucher { // qDebug() << "stuPreVoucher(2) =================================" << _paramName << ":" << _value; - if (_value.isValid() == false) - { + if (_value.isValid() == false) { // qDebug() << "stuPreVoucher(2.1) =================================" << _paramName << ":" << _value; return stuPreVoucher(); } @@ -98,15 +94,13 @@ TAPI_REGISTER_METATYPE( if (_value.canConvert() // || _value.canConvert() // || _value.canConvert() - ) - { + ) { auto ret = QJsonDocument::fromVariant(_value); // qDebug() << "stuPreVoucher(2.2) =================================" << _paramName << ":" << _value << "=" << ret.object(); return stuPreVoucher().fromJson(ret.object()); } - if (_value.toString().isEmpty()) - { + if (_value.toString().isEmpty()) { // qDebug() << "stuPreVoucher(2.3) =================================" << _paramName << ":" << _value; return stuPreVoucher(); } @@ -139,7 +133,7 @@ TAPI_REGISTER_METATYPE( [](const QVariant& _value, const QByteArray&) -> OrderAdditives_t { auto Map = _value.toMap(); OrderAdditives_t Additives; - for(auto Iter = Map.begin(); Iter != Map.end(); ++Iter) + for (auto Iter = Map.begin(); Iter != Map.end(); ++Iter) Additives.insert(Iter.key(), Iter.value().toString()); return Additives; } @@ -218,32 +212,28 @@ intfAccountProducts::intfAccountProducts( { tblAccountProductsBase::prdUpdatedBy_usrID }, }) + _exclusiveIndexes ) -{} +{ ; } -QVariant intfAccountProducts::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant intfAccountProducts::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); constexpr quint16 CACHE_TIME = 15 * 60; return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL, {}, CACHE_TIME); } -quint32 intfAccountProducts::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) -{ +quint32 intfAccountProducts::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PUT, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Create(*this, CREATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool intfAccountProducts::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool intfAccountProducts::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PATCH, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool intfAccountProducts::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool intfAccountProducts::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())); return /*Targoman::API::Query::*/this->DeleteByPks(*this, DELETE_METHOD_CALL_ARGS_INTERNAL_CALL); @@ -305,10 +295,9 @@ intfAccountSaleables::intfAccountSaleables( { tblAccountSaleablesBase::slbUpdatedBy_usrID }, }) + _exclusiveIndexes ) -{} +{ ; } -QVariant intfAccountSaleables::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant intfAccountSaleables::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { // QString ExtraFilters; // if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())) == false) // ExtraFilters = QString ("%1<=NOW() + ( %2=NULL | %2>=DATE_ADD(NOW(),INTERVAL$SPACE$15$SPACEMIN) )") @@ -328,22 +317,19 @@ QVariant intfAccountSaleables::apiGET(GET_METHOD_ARGS_IMPL_APICALL) return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL, ExtraFilters, CACHE_TIME); } -quint32 intfAccountSaleables::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) -{ +quint32 intfAccountSaleables::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PUT, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Create(*this, CREATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool intfAccountSaleables::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool intfAccountSaleables::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PATCH, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool intfAccountSaleables::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool intfAccountSaleables::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())); return /*Targoman::API::Query::*/this->DeleteByPks(*this, DELETE_METHOD_CALL_ARGS_INTERNAL_CALL); @@ -399,17 +385,16 @@ intfAccountUserAssets::intfAccountUserAssets( { tblAccountUserAssetsBase::uasUpdatedBy_usrID }, }) + _exclusiveIndexes ) -{} +{ ; } -QVariant intfAccountUserAssets::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant intfAccountUserAssets::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())) == false) this->setSelfFilters({{tblAccountUserAssetsBase::uas_usrID, clsJWT(_JWT).usrID()}}, _filters); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool intfAccountUserAssets::apiUPDATEsetAsPrefered(TAPI::JWT_t _JWT, TAPI::PKsByPath_t _pksByPath){ +bool intfAccountUserAssets::apiUPDATEsetAsPrefered(TAPI::JWT_t _JWT, TAPI::PKsByPath_t _pksByPath) { bool Ok; quint64 UserPackageID = _pksByPath.toUInt(&Ok); if (!Ok || !UserPackageID ) @@ -422,7 +407,7 @@ bool intfAccountUserAssets::apiUPDATEsetAsPrefered(TAPI::JWT_t _JWT, TAPI::PKsBy return false; } -bool intfAccountUserAssets::apiUPDATEdisablePackage(TAPI::JWT_t _JWT, TAPI::PKsByPath_t _pksByPath){ +bool intfAccountUserAssets::apiUPDATEdisablePackage(TAPI::JWT_t _JWT, TAPI::PKsByPath_t _pksByPath) { bool Ok; quint64 UserPackageID = _pksByPath.toUInt(&Ok); if (!Ok || !UserPackageID ) @@ -458,10 +443,9 @@ intfAccountAssetUsage::intfAccountAssetUsage( }) + _exclusiveRelations, _exclusiveIndexes ) -{} +{ ; } -QVariant intfAccountAssetUsage::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant intfAccountAssetUsage::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())) == false) this->setSelfFilters({{tblAccountUserAssetsBase::uas_usrID, clsJWT(_JWT).usrID()}}, _filters); @@ -516,10 +500,9 @@ intfAccountCoupons::intfAccountCoupons( { tblAccountCouponsBase::cpnUpdatedBy_usrID }, } ) -{} +{ ; } -QVariant intfAccountCoupons::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant intfAccountCoupons::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); @@ -529,22 +512,19 @@ QVariant intfAccountCoupons::apiGET(GET_METHOD_ARGS_IMPL_APICALL) // return this->selectFromTable({}, {}, GET_METHOD_CALL_ARGS_APICALL); } -quint32 intfAccountCoupons::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) -{ +quint32 intfAccountCoupons::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PUT, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Create(*this, CREATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool intfAccountCoupons::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool intfAccountCoupons::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PATCH, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool intfAccountCoupons::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool intfAccountCoupons::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())); return /*Targoman::API::Query::*/this->DeleteByPks(*this, DELETE_METHOD_CALL_ARGS_INTERNAL_CALL); @@ -563,10 +543,9 @@ intfAccountPrizes::intfAccountPrizes( _cols, _relations ) -{} +{ ; } -QVariant intfAccountPrizes::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant intfAccountPrizes::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); @@ -576,22 +555,19 @@ QVariant intfAccountPrizes::apiGET(GET_METHOD_ARGS_IMPL_APICALL) // return this->selectFromTable({}, {}, GET_METHOD_CALL_ARGS_APICALL); } -quint32 intfAccountPrizes::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) -{ +quint32 intfAccountPrizes::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PUT, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Create(*this, CREATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool intfAccountPrizes::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool intfAccountPrizes::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PATCH, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool intfAccountPrizes::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool intfAccountPrizes::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())); return /*Targoman::API::Query::*/this->DeleteByPks(*this, DELETE_METHOD_CALL_ARGS_INTERNAL_CALL); @@ -609,30 +585,28 @@ stuActiveCredit::stuActiveCredit(const stuAssetItem& _credit, bool _isFromParent IsFromParent(_isFromParent), MyLimitsOnParent(_myLimitsOnParent), TTL(_ttl) -{} +{ ; } -QJsonObject stuActiveCredit::toJson(bool _full) -{ +QJsonObject stuActiveCredit::toJson(bool _full) { QJsonObject Account = { { ASA_PACKAGE, this->Credit.toJson(_full) }, { ASA_TTL, static_cast(this->TTL) }, }; - if(this->IsFromParent) + if (this->IsFromParent) Account.insert(ASA_ISFROMPARENT, true); - for(auto LimitIter = this->MyLimitsOnParent.begin(); + for (auto LimitIter = this->MyLimitsOnParent.begin(); LimitIter != this->MyLimitsOnParent.end(); LimitIter++) Account.insert(LimitIter.key(), LimitIter->toJson()); return Account; } -stuActiveCredit& stuActiveCredit::fromJson(const QJsonObject _obj) -{ +stuActiveCredit& stuActiveCredit::fromJson(const QJsonObject _obj) { this->Credit = stuAssetItem().fromJson(_obj.value(ASA_PACKAGE).toObject()); this->IsFromParent = _obj.value(ASA_ISFROMPARENT).toBool(); this->TTL = static_cast(_obj.value(ASA_TTL).toDouble()); QJsonObject Limits = _obj.value(ASA_LIMITSONPARENT).toObject(); - for(auto LimitIter = Limits.begin(); + for (auto LimitIter = Limits.begin(); LimitIter != Limits.end(); LimitIter++) this->MyLimitsOnParent.insert(LimitIter.key(), stuUsage().fromJson(LimitIter->toObject())); @@ -652,25 +626,24 @@ stuServiceCreditsInfo::stuServiceCreditsInfo( ParentID(_parentID), MyLimitsOnParent(_myLimitsOnParent), DBCurrentDateTime(_dbCurrentDateTime) -{} +{ ; } -QJsonObject stuAssetItem::toJson(bool _full) -{ +QJsonObject stuAssetItem::toJson(bool _full) { ///TODO: very important: Complete this QJsonObject Info; /* - if(this->PackageID > 0) Info[PKG_ID] = static_cast(this->PackageID); - if(this->PackageCode > -1) Info[PKG_CODE] = this->PackageCode; - if(this->RemainingDays > -1) Info[PKG_REMAININGDAYS] = this->RemainingDays; - if(this->RemainingHours > -1) Info[PKG_REMAININGHOURS] = this->RemainingHours; - if(this->StartDate.isValid()) Info[PKG_STARTDATE] = this->StartDate.toString(); - if(this->EndDate.isValid()) Info[PKG_ENDDATE] = this->EndDate.toString(); - if(this->StartTime.isValid()) Info[PKG_STARTTIME] = this->StartTime.toString(); - if(this->EndTime.isValid()) Info[PKG_ENDTIME] = this->EndTime.toString(); - if(this->Properties.size()) Info[PKG_PROPS] = this->Properties; - if(_full){ + if (this->PackageID > 0) Info[PKG_ID] = static_cast(this->PackageID); + if (this->PackageCode > -1) Info[PKG_CODE] = this->PackageCode; + if (this->RemainingDays > -1) Info[PKG_REMAININGDAYS] = this->RemainingDays; + if (this->RemainingHours > -1) Info[PKG_REMAININGHOURS] = this->RemainingHours; + if (this->StartDate.isValid()) Info[PKG_STARTDATE] = this->StartDate.toString(); + if (this->EndDate.isValid()) Info[PKG_ENDDATE] = this->EndDate.toString(); + if (this->StartTime.isValid()) Info[PKG_STARTTIME] = this->StartTime.toString(); + if (this->EndTime.isValid()) Info[PKG_ENDTIME] = this->EndTime.toString(); + if (this->Properties.size()) Info[PKG_PROPS] = this->Properties; + if (_full) { QJsonObject Limits; - for(auto LimitIter = this->Remaining.begin(); + for (auto LimitIter = this->Remaining.begin(); LimitIter != this->Remaining.end(); LimitIter++) Limits.insert(LimitIter.key(), LimitIter->toJson()); @@ -679,8 +652,7 @@ QJsonObject stuAssetItem::toJson(bool _full) return Info; } -stuAssetItem &stuAssetItem::fromJson(const QJsonObject& _obj) -{ +stuAssetItem &stuAssetItem::fromJson(const QJsonObject& _obj) { ///TODO: very important: Complete this /* this->PackageID = static_cast(_obj.contains(PKG_ID) ? _obj.value(PKG_ID).toDouble() : 0); @@ -693,7 +665,7 @@ stuAssetItem &stuAssetItem::fromJson(const QJsonObject& _obj) this->EndTime = _obj.contains(PKG_ENDTIME) ? QTime::fromString(_obj.value(PKG_ENDTIME).toString()) : QTime(); this->Properties = _obj.value(PKG_PROPS).toObject(); QJsonObject Limits = _obj.value(PKG_LIMITS).toObject(); - for(auto LimitIter = Limits.begin(); + for (auto LimitIter = Limits.begin(); LimitIter != Limits.end(); LimitIter++) this->Remaining.insert(LimitIter.key(), stuUsage().fromJson(LimitIter->toObject())); @@ -701,8 +673,7 @@ stuAssetItem &stuAssetItem::fromJson(const QJsonObject& _obj) return *this; } -void stuAssetItem::fromVariantMap(const QVariantMap& _info) -{ +void stuAssetItem::fromVariantMap(const QVariantMap& _info) { SET_FIELD_FROM_VARIANT_MAP(this->prdID, _info, tblAccountProductsBase, prdID); SET_FIELD_FROM_VARIANT_MAP(this->prdCode, _info, tblAccountProductsBase, prdCode); SET_FIELD_FROM_VARIANT_MAP(this->prdName, _info, tblAccountProductsBase, prdName); @@ -732,8 +703,7 @@ void stuAssetItem::fromVariantMap(const QVariantMap& _info) SET_FIELD_FROM_VARIANT_MAP(this->slbStatus, _info, tblAccountSaleablesBase, slbStatus); } -void stuFullDiscount::fromVariantMap(const QVariantMap& _info) -{ +void stuFullDiscount::fromVariantMap(const QVariantMap& _info) { SET_FIELD_FROM_VARIANT_MAP(this->cpnID, _info, tblAccountCouponsBase, cpnID); SET_FIELD_FROM_VARIANT_MAP(this->cpnCode, _info, tblAccountCouponsBase, cpnCode); SET_FIELD_FROM_VARIANT_MAP(this->cpnPrimaryCount, _info, tblAccountCouponsBase, cpnPrimaryCount); @@ -754,18 +724,18 @@ void stuFullDiscount::fromVariantMap(const QVariantMap& _info) /******************************************************************/ /*QVariant stuAssetItemReq_t::toVariant() const{ QVariantMap Value; - for(auto Iter = this->begin(); Iter != this->end(); ++Iter) + for (auto Iter = this->begin(); Iter != this->end(); ++Iter) Value.insert(Iter.key(), Iter.value()); return Value; } -stuAssetItemReq_t& stuAssetItemReq_t::fromVariant(const QVariant& _value, const QByteArray& _paramName){ - if(_value.canConvert>() == false) +stuAssetItemReq_t& stuAssetItemReq_t::fromVariant(const QVariant& _value, const QByteArray& _paramName) { + if (_value.canConvert>() == false) throw exHTTPBadRequest("Invalid value specified for parameter:" + _paramName); this->clear(); const QMap& Map = _value.toMap(); - for(auto Iter = Map.begin (); Iter != Map.end (); ++Iter) + for (auto Iter = Map.begin (); Iter != Map.end (); ++Iter) this->insert(Iter.key(), static_cast(Iter.value().toInt())); return *this; }*/ diff --git a/Interfaces/AAA/Authentication.cpp b/Interfaces/AAA/Authentication.cpp index 17060aed..a74331f3 100644 --- a/Interfaces/AAA/Authentication.cpp +++ b/Interfaces/AAA/Authentication.cpp @@ -59,8 +59,7 @@ stuActiveAccount login( } /* -stuActiveAccount updatePrivs(const QString& _ip, const QString& _ssid, const QString& _requiredServices) -{ +stuActiveAccount updatePrivs(const QString& _ip, const QString& _ssid, const QString& _requiredServices) { makeAAADAC(DAC); QJsonObject UserInfo = DAC.callSP({}, @@ -120,10 +119,8 @@ QString renewJWT( ); } -QString retrievePhoto(const QString _url) -{ - try - { +QString retrievePhoto(const QString _url) { + try { QByteArray Photo = PrivHelpers::getURL(_url); if (_url.endsWith(".jpg") || _url.endsWith(".jpeg")) @@ -131,15 +128,12 @@ QString retrievePhoto(const QString _url) if (_url.endsWith(".png")) return "data:image/png;base64," + Photo.toBase64(); - } - catch(...) - {} + } catch (...) { ; } return QByteArray(); } -stuOAuthInfo retrieveGoogleUserInfo(const QString& _authToken) -{ +stuOAuthInfo retrieveGoogleUserInfo(const QString& _authToken) { stuOAuthInfo Info; QByteArray Json = PrivHelpers::getURL("https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" + _authToken); QJsonParseError JsonError; @@ -164,8 +158,7 @@ stuOAuthInfo retrieveGoogleUserInfo(const QString& _authToken) return Info; } -stuOAuthInfo retrieveLinkedinUserInfo(const QString& _authToken) -{ +stuOAuthInfo retrieveLinkedinUserInfo(const QString& _authToken) { stuOAuthInfo Info; QByteArray Json = PrivHelpers::getURL("https://api.linkedin.com/v1/people/~?format=json&oauth_token=" + _authToken); QJsonParseError JsonError; @@ -188,14 +181,12 @@ stuOAuthInfo retrieveLinkedinUserInfo(const QString& _authToken) return Info; } -stuOAuthInfo retrieveYahooUserInfo(const QString& _authToken) -{ +stuOAuthInfo retrieveYahooUserInfo(const QString& _authToken) { throw exAuthentication("Authentication by Yahoo is not implemented yet"); Q_UNUSED(_authToken); } -stuOAuthInfo retrieveGitHubUserInfo(const QString& _authToken) -{ +stuOAuthInfo retrieveGitHubUserInfo(const QString& _authToken) { Q_UNUSED(_authToken); throw exAuthentication("Authentication by Github is not implemented yet"); } diff --git a/Interfaces/AAA/Authorization.cpp b/Interfaces/AAA/Authorization.cpp index 97627fde..ff16c320 100644 --- a/Interfaces/AAA/Authorization.cpp +++ b/Interfaces/AAA/Authorization.cpp @@ -30,16 +30,14 @@ namespace API { namespace AAA { namespace Authorization{ -void validateIPAddress(const QString& _ip) -{ +void validateIPAddress(const QString& _ip) { makeAAADAC(DAC); DAC.callSP({}, "spIP_ValidateAccess", { {"iIP", inet_addr(_ip.toLatin1().constData())}, }); } -QJsonObject retrieveTokenInfo(const QString& _token, const QString& _ip, const QStringList& _requiredPrivs) -{ +QJsonObject retrieveTokenInfo(const QString& _token, const QString& _ip, const QStringList& _requiredPrivs) { PrivHelpers::validateToken(_token); makeAAADAC(DAC); @@ -51,9 +49,8 @@ QJsonObject retrieveTokenInfo(const QString& _token, const QString& _ip, const Q return PrivHelpers::processUserObject(TokenInfo, _requiredPrivs).Privs; } -bool hasPriv(const TAPI::JWT_t& _jwt, const QStringList& _requiredAccess, bool _isSelf) -{ - if(_requiredAccess.isEmpty()) +bool hasPriv(const TAPI::JWT_t& _jwt, const QStringList& _requiredAccess, bool _isSelf) { + if (_requiredAccess.isEmpty()) return true; QJsonObject Privs = privObjectFromInfo(_jwt); @@ -61,25 +58,23 @@ bool hasPriv(const TAPI::JWT_t& _jwt, const QStringList& _requiredAccess, bool _ return false; foreach(auto AccessItem, _requiredAccess) - if(PrivHelpers::hasPrivBase(Privs, AccessItem, _isSelf) == false) + if (PrivHelpers::hasPrivBase(Privs, AccessItem, _isSelf) == false) return false; return true; } -void checkPriv(const TAPI::JWT_t &_jwt, const QStringList &_requiredAccess, bool _isSelf) -{ +void checkPriv(const TAPI::JWT_t &_jwt, const QStringList &_requiredAccess, bool _isSelf) { if (!hasPriv(_jwt, _requiredAccess, _isSelf)) throw exAuthorization("Not enought privileges: required are <" + _requiredAccess.join("|") + ">"); } -QVariant getPrivValue(const TAPI::JWT_t &_jwt, QString _accessItem){ +QVariant getPrivValue(const TAPI::JWT_t &_jwt, QString _accessItem) { QJsonObject Privs = privObjectFromInfo(_jwt); if ( Privs.isEmpty()) return QVariant(); return PrivHelpers::getPrivValue(Privs, _accessItem); } -QJsonObject privObjectFromInfo(const QJsonObject& _info) -{ +QJsonObject privObjectFromInfo(const QJsonObject& _info) { return _info.contains(AAACommonItems::privs) ? _info[AAACommonItems::privs].toObject() : _info; } diff --git a/Interfaces/AAA/PrivHelpers.cpp b/Interfaces/AAA/PrivHelpers.cpp index 53bd138b..aa0aa2c3 100644 --- a/Interfaces/AAA/PrivHelpers.cpp +++ b/Interfaces/AAA/PrivHelpers.cpp @@ -40,7 +40,7 @@ stuActiveAccount PrivHelpers::digestPrivileges(const QJsonArray& _privs, quint64 throw exHTTPBadRequest("Service " + Service + " was not registered."); qint64 MinTTL = LLONG_MAX; - foreach(auto Priv, _privs){ + foreach(auto Priv, _privs) { QJsonObject PrivObj = Priv.toObject(); for (auto PrivIter = PrivObj.begin(); PrivIter != PrivObj.end(); ++PrivIter) if (PrivIter.key() == "ALL" || _services.contains("ALL") || _services.contains(PrivIter.key())) { @@ -58,27 +58,27 @@ stuActiveAccount PrivHelpers::digestPrivileges(const QJsonArray& _privs, quint64 if (Privs.contains("ALL") == false) foreach (auto Service, _services) - if(Privs.contains(Service) == false) + if (Privs.contains(Service) == false) throw exAuthorization("Not enough priviledges to access <"+Service+">"); return { MinTTL, Privs }; } -bool PrivHelpers::hasPrivBase(const QJsonObject& _privs, const QString& _requiredAccess, bool _isSelf){ +bool PrivHelpers::hasPrivBase(const QJsonObject& _privs, const QString& _requiredAccess, bool _isSelf) { QStringList AccessItemParts = _requiredAccess.split(":"); QJsonObject CurrCheckingPriv = _privs; - foreach(auto Part, AccessItemParts){ - if(Part.startsWith("CRUD~")){ + foreach(auto Part, AccessItemParts) { + if (Part.startsWith("CRUD~")) { QString RequiredAccess = Part.split('~').last(); - if(RequiredAccess.size() != 4) + if (RequiredAccess.size() != 4) throw exAAA("Invalid access format for CRUD must be of CRUD~ACCESS"); QString CheckingPriv = CurrCheckingPriv.value(PRIVItems::CRUD).toString(); - for(quint8 i=0; i<4; ++i) + for (quint8 i=0; i<4; ++i) if (RequiredAccess[i] == '1' || RequiredAccess[i].toUpper() == 'T' - ){ - if(CheckingPriv[i] == '0' || CheckingPriv[i].toUpper() == 'F') + ) { + if (CheckingPriv[i] == '0' || CheckingPriv[i].toUpper() == 'F') return false; else return (CheckingPriv[i].toUpper() == 'T' || _isSelf); @@ -88,16 +88,16 @@ bool PrivHelpers::hasPrivBase(const QJsonObject& _privs, const QString& _require return true; } bool Found = false; - for (auto PrivIter = CurrCheckingPriv.begin(); PrivIter != CurrCheckingPriv.end(); ++PrivIter){ - if(PrivIter.key() == "ALL" && PrivIter.value().toInt() != 0) + for (auto PrivIter = CurrCheckingPriv.begin(); PrivIter != CurrCheckingPriv.end(); ++PrivIter) { + if (PrivIter.key() == "ALL" && PrivIter.value().toInt() != 0) return true; - if(PrivIter.key().toLower() == Part.toLower()){ + if (PrivIter.key().toLower() == Part.toLower()) { CurrCheckingPriv = PrivIter.value().toObject(); Found = true; break; } - if(Found == false) + if (Found == false) return false; } } @@ -105,32 +105,32 @@ bool PrivHelpers::hasPrivBase(const QJsonObject& _privs, const QString& _require return true; } -QJsonObject PrivHelpers::confirmPriviledgeBase(const QJsonObject& _privs, const QStringList& _requiredAccess){ +QJsonObject PrivHelpers::confirmPriviledgeBase(const QJsonObject& _privs, const QStringList& _requiredAccess) { if (_requiredAccess.isEmpty()) return _privs; - if(_privs.isEmpty()) + if (_privs.isEmpty()) throw exAAA("Seems that Privs has not been set"); foreach(auto AccessItem, _requiredAccess) - if(AccessItem.size() && PrivHelpers::hasPrivBase(_privs, AccessItem) == false) + if (AccessItem.size() && PrivHelpers::hasPrivBase(_privs, AccessItem) == false) throw exAuthorization("Not enough priviledges on <"+AccessItem+">"); return _privs; } -void PrivHelpers::validateToken(const QString& _token){ +void PrivHelpers::validateToken(const QString& _token) { static QRegularExpression rxTokenValidator = QRegularExpression("^[a-zA-Z0-9\\-_ ]{8,32}$"); - if(_token.isEmpty()) + if (_token.isEmpty()) throw exNoTokenProvided("No token provided"); - if(rxTokenValidator.match(_token).hasMatch() == false) + if (rxTokenValidator.match(_token).hasMatch() == false) throw exInvalidToken("Invalid token provided"); } -QVariant PrivHelpers::getPrivValue(const QJsonObject& _privs, const QString& _selector){ +QVariant PrivHelpers::getPrivValue(const QJsonObject& _privs, const QString& _selector) { QStringList AccessItemParts = _selector.split(":"); QJsonObject CurrCheckingPriv = _privs; - foreach(auto Part, AccessItemParts){ - if(CurrCheckingPriv.contains(Part) == false) + foreach(auto Part, AccessItemParts) { + if (CurrCheckingPriv.contains(Part) == false) return QVariant(); CurrCheckingPriv = CurrCheckingPriv.value(Part).toObject(); } @@ -141,7 +141,7 @@ stuActiveAccount PrivHelpers::processUserObject(QJsonObject& _userObj, const QSt if (_userObj.contains(DBM_SPRESULT_ROWS)) _userObj = _userObj[DBM_SPRESULT_ROWS].toArray().at(0).toObject(); - if(_userObj.size()){ + if (_userObj.size()) { stuActiveAccount ActiveAccount = PrivHelpers::digestPrivileges( _userObj[AAACommonItems::privs].toArray(), @@ -149,11 +149,11 @@ stuActiveAccount PrivHelpers::processUserObject(QJsonObject& _userObj, const QSt _services); _userObj[AAACommonItems::privs] = PrivHelpers::confirmPriviledgeBase(ActiveAccount.Privs, _requiredAccess); return { ActiveAccount.TTL, _userObj }; - }else + } else return { -1, _userObj }; } -QByteArray PrivHelpers::getURL(const QString& _url){ +QByteArray PrivHelpers::getURL(const QString& _url) { QtCUrl CUrl; CUrl.setTextCodec("UTF-8"); @@ -165,17 +165,16 @@ QByteArray PrivHelpers::getURL(const QString& _url){ if (CUrl.lastError().code() == CURLE_OPERATION_TIMEDOUT) throw exAccounting("Connection to <" + _url +"> timed out."); - else if(CUrl.lastError().code() == CURLE_COULDNT_CONNECT) + else if (CUrl.lastError().code() == CURLE_COULDNT_CONNECT) throw exAccounting("Connection to <" + _url +"> failed."); - else if(CUrl.lastError().isOk() == false) + else if (CUrl.lastError().isOk() == false) throw exAccounting("Connection to <" + _url + "> error: " + CUrl.lastError().text()); else return CUrlResult.toUtf8(); } /******************************************************************************/ -TAPI::EncodedJWT_t clsJWT::createSigned(QJsonObject _payload, QJsonObject _privatePayload, const qint64 _expiry, const QString& _sessionID) -{ +TAPI::EncodedJWT_t clsJWT::createSigned(QJsonObject _payload, QJsonObject _privatePayload, const qint64 _expiry, const QString& _sessionID) { return Server::QJWT::createSigned(_payload, _privatePayload, _expiry < 0 || _expiry == LLONG_MAX ? Server::QJWT::TTL.value() : static_cast(_expiry), diff --git a/Interfaces/AAA/PrivHelpers.h b/Interfaces/AAA/PrivHelpers.h index 34f2ce12..1beb1649 100644 --- a/Interfaces/AAA/PrivHelpers.h +++ b/Interfaces/AAA/PrivHelpers.h @@ -39,7 +39,7 @@ struct stuActiveAccount{ stuActiveAccount(qint64 _ttl, const QJsonObject& _privs) : TTL(_ttl), Privs(_privs) - {} + { ; } }; class PrivHelpers{ diff --git a/Interfaces/AAA/clsJWT.hpp b/Interfaces/AAA/clsJWT.hpp index ec686896..65c10fe8 100644 --- a/Interfaces/AAA/clsJWT.hpp +++ b/Interfaces/AAA/clsJWT.hpp @@ -49,7 +49,7 @@ TARGOMAN_CREATE_CONSTEXPR(rolName); class clsJWT{ public: - clsJWT(const QJsonObject& _token) : Token(_token){} + clsJWT(const QJsonObject& _token) : Token(_token) { ; } inline QString login() const {return this->Token.value(JWTItems::usrLogin).toString();} inline QString name() const {return this->Token.value(JWTItems::usrName).toString();} inline QString family() const {return this->Token.value(JWTItems::usrFamily).toString();} diff --git a/Interfaces/AAA/intfAccountingBasedModule.cpp b/Interfaces/AAA/intfAccountingBasedModule.cpp index 7c0d56f6..8e37bea0 100644 --- a/Interfaces/AAA/intfAccountingBasedModule.cpp +++ b/Interfaces/AAA/intfAccountingBasedModule.cpp @@ -44,13 +44,11 @@ Targoman::Common::Configuration::tmplConfigurable Secret( "Secret to be used for signing voucher and prevoucher", "fcy^E?a*4<;auY?>^6s@"); -QByteArray hash(const QByteArray& _data) -{ +QByteArray hash(const QByteArray& _data) { return QMessageAuthenticationCode::hash(_data, Secret.value().toUtf8(), QCryptographicHash::Sha256); } -void checkPreVoucherSanity(stuPreVoucher _preVoucher) -{ +void checkPreVoucherSanity(stuPreVoucher _preVoucher) { if (_preVoucher.Items.isEmpty()) return; @@ -59,8 +57,7 @@ void checkPreVoucherSanity(stuPreVoucher _preVoucher) if (Sign != QString(hash(QJsonDocument(_preVoucher.toJson()).toJson()).toBase64())) throw exHTTPBadRequest("Invalid sign found on pre-Voucher items"); - foreach (auto VoucherItem, _preVoucher.Items) - { + foreach (auto VoucherItem, _preVoucher.Items) { QString Sign = VoucherItem.Sign; VoucherItem.Sign.clear(); @@ -69,8 +66,7 @@ void checkPreVoucherSanity(stuPreVoucher _preVoucher) } } -intfAccountingBasedModule* serviceAccounting(const QString& _serviceName) -{ +intfAccountingBasedModule* serviceAccounting(const QString& _serviceName) { // Q_UNUSED(serviceAccounting); return ServiceRegistry.value(_serviceName); } @@ -97,10 +93,8 @@ intfAccountingBasedModule::intfAccountingBasedModule( AccountAssetUsages(_assetUsages), AccountCoupons(_discounts), AccountPrizes(_prizes), - AssetUsageLimitsCols(_AssetUsageLimitsCols) -{ - foreach(auto Col, this->AssetUsageLimitsCols) - { + AssetUsageLimitsCols(_AssetUsageLimitsCols) { + foreach(auto Col, this->AssetUsageLimitsCols) { if (Col.PerDay.size()) this->AssetUsageLimitsColsName.append(Col.PerDay); @@ -117,15 +111,13 @@ intfAccountingBasedModule::intfAccountingBasedModule( ServiceRegistry.insert(this->ServiceName, this); } -//intfAccountingBasedModule::~intfAccountingBasedModule() {} +//intfAccountingBasedModule::~intfAccountingBasedModule() { ; } -stuActiveCredit intfAccountingBasedModule::activeAccountObject(quint64 _usrID) -{ +stuActiveCredit intfAccountingBasedModule::activeAccountObject(quint64 _usrID) { return this->findBestMatchedCredit(_usrID); } -void intfAccountingBasedModule::checkUsageIsAllowed(const clsJWT& _jwt, const ServiceUsage_t& _requestedUsage) -{ +void intfAccountingBasedModule::checkUsageIsAllowed(const clsJWT& _jwt, const ServiceUsage_t& _requestedUsage) { QJsonObject Privs = _jwt.privsObject(); if (Privs.contains(this->ServiceName) == false) @@ -152,12 +144,10 @@ void intfAccountingBasedModule::checkUsageIsAllowed(const clsJWT& _jwt, const Se const stuAssetItem& ActiveCredit = BestMatchedCredit.Credit; - if (BestMatchedCredit.IsFromParent) - { - for(auto UsageIter = _requestedUsage.begin(); + if (BestMatchedCredit.IsFromParent) { + for (auto UsageIter = _requestedUsage.begin(); UsageIter != _requestedUsage.end(); - UsageIter++) - { + UsageIter++) { if (ActiveCredit.Digested.Limits.contains(UsageIter.key()) == false) continue; @@ -175,8 +165,7 @@ void intfAccountingBasedModule::checkUsageIsAllowed(const clsJWT& _jwt, const Se for (auto UsageIter = _requestedUsage.begin(); UsageIter != _requestedUsage.end(); - UsageIter++) - { + UsageIter++) { if (ActiveCredit.Digested.Limits.contains(UsageIter.key()) == false) continue; @@ -184,8 +173,7 @@ void intfAccountingBasedModule::checkUsageIsAllowed(const clsJWT& _jwt, const Se } } -stuActiveCredit intfAccountingBasedModule::findBestMatchedCredit(quint64 _usrID, const ServiceUsage_t& _requestedUsage) -{ +stuActiveCredit intfAccountingBasedModule::findBestMatchedCredit(quint64 _usrID, const ServiceUsage_t& _requestedUsage) { stuServiceCreditsInfo ServiceCreditsInfo = this->retrieveServiceCreditsInfo(_usrID); if (ServiceCreditsInfo.ActiveCredits.isEmpty()) return stuActiveCredit(); @@ -218,16 +206,14 @@ stuActiveCredit intfAccountingBasedModule::findBestMatchedCredit(quint64 _usrID, ) return false; - if (_requestedUsage.size()) - { + if (_requestedUsage.size()) { for (auto UsageIter = _requestedUsage.begin(); UsageIter != _requestedUsage.end(); - UsageIter++) - { + UsageIter++) { if (_assetItem.Digested.Limits.contains(UsageIter.key()) == false) continue; - if (this->isUnlimited(_assetItem.Digested.Limits) == false){ + if (this->isUnlimited(_assetItem.Digested.Limits) == false) { stuUsage Remaining = _assetItem.Digested.Limits.value(UsageIter.key()); if ((NULLABLE_HAS_VALUE(Remaining.PerDay) && *Remaining.PerDay - UsageIter.value() <= 0) || (NULLABLE_HAS_VALUE(Remaining.PerWeek) && *Remaining.PerWeek - UsageIter.value() <= 0) @@ -255,8 +241,8 @@ stuActiveCredit intfAccountingBasedModule::findBestMatchedCredit(quint64 _usrID, if (NULLABLE_HAS_VALUE(a.prdValidToHour) && NULLABLE_IS_NULL(b.prdValidToHour)) return -1; if (NULLABLE_IS_NULL(a.prdValidToHour) && NULLABLE_HAS_VALUE(b.prdValidToHour)) return 1; if (NULLABLE_HAS_VALUE(a.prdValidToHour) && NULLABLE_HAS_VALUE(b.prdValidToHour)) { - if(effectiveEndDateTime(a) < effectiveEndDateTime(b)) return -1; - if(effectiveEndDateTime(a) > effectiveEndDateTime(b)) return 1; + if (effectiveEndDateTime(a) < effectiveEndDateTime(b)) return -1; + if (effectiveEndDateTime(a) > effectiveEndDateTime(b)) return 1; } if (a.prdValidToDate.isValid() && b.prdValidToDate.isValid() && a.prdValidToDate != b.prdValidToDate) return b.prdValidToDate > a.prdValidToDate ? -1 : 1; @@ -267,15 +253,13 @@ stuActiveCredit intfAccountingBasedModule::findBestMatchedCredit(quint64 _usrID, for (auto AccountIter = ServiceCreditsInfo.ActiveCredits.begin(); AccountIter != ServiceCreditsInfo.ActiveCredits.end(); - AccountIter++) - { + AccountIter++) { const stuAssetItem& Item = AccountIter.value(); if (isInvalidPackage(Item)) continue; - if (CandidateCredit.isEmpty()) - { + if (CandidateCredit.isEmpty()) { CandidateCredit.append(Item); continue; } @@ -283,10 +267,8 @@ stuActiveCredit intfAccountingBasedModule::findBestMatchedCredit(quint64 _usrID, bool Inserted = false; for (auto CandidateIter = CandidateCredit.begin(); CandidateIter != CandidateCredit.end(); - CandidateIter++) - { - if (comparePackages(Item, *CandidateIter) <0) - { + CandidateIter++) { + if (comparePackages(Item, *CandidateIter) <0) { this->breakCredit(CandidateIter->slbID); CandidateCredit.insert(CandidateIter, Item); Inserted = true; @@ -297,8 +279,7 @@ stuActiveCredit intfAccountingBasedModule::findBestMatchedCredit(quint64 _usrID, CandidateCredit.append(Item); } - if (CandidateCredit.isEmpty()) - { + if (CandidateCredit.isEmpty()) { if (_requestedUsage.size()) throw exPaymentRequired("You don't have any active account"); @@ -307,14 +288,12 @@ stuActiveCredit intfAccountingBasedModule::findBestMatchedCredit(quint64 _usrID, const stuAssetItem& ActivePackage = CandidateCredit.first(); QDateTime NextDigestTime; - if (ActivePackage.prdValidToDate.isNull() == false) - { + if (ActivePackage.prdValidToDate.isNull() == false) { if (NULLABLE_HAS_VALUE(ActivePackage.prdValidToHour)) NextDigestTime = effectiveEndDateTime(ActivePackage); else NextDigestTime = QDateTime(ActivePackage.prdValidToDate.addDays(1)); - } - else if (NULLABLE_HAS_VALUE(ActivePackage.prdValidToHour)) + } else if (NULLABLE_HAS_VALUE(ActivePackage.prdValidToHour)) NextDigestTime = effectiveEndDateTime(ActivePackage); return stuActiveCredit(ActivePackage, @@ -324,10 +303,8 @@ stuActiveCredit intfAccountingBasedModule::findBestMatchedCredit(quint64 _usrID, } bool intfAccountingBasedModule::increaseDiscountUsage( - const Targoman::API::AAA::stuVoucherItem &_voucherItem) -{ - if (_voucherItem.DisAmount > 0) - { + const Targoman::API::AAA::stuVoucherItem &_voucherItem) { + if (_voucherItem.DisAmount > 0) { clsDACResult Result = this->AccountCoupons->callSP("spCoupon_IncreaseStats", { { "iDiscountID", _voucherItem.Discount.ID }, { "iTotalUsedCount", 1 }, @@ -341,8 +318,7 @@ bool intfAccountingBasedModule::decreaseDiscountUsage( const Targoman::API::AAA::stuVoucherItem &_voucherItem ) { - if (_voucherItem.DisAmount > 0) - { + if (_voucherItem.DisAmount > 0) { clsDACResult Result = this->AccountCoupons->callSP("spCoupon_DecreaseStats", { { "iDiscountID", _voucherItem.Discount.ID }, { "iTotalUsedCount", 1 }, @@ -557,8 +533,7 @@ Targoman::API::AAA::stuPreVoucher intfAccountingBasedModule::apiPOSTaddToBasket( UsageLimits_t SaleableUsageLimits; for (auto Iter = this->AssetUsageLimitsCols.begin(); Iter != this->AssetUsageLimitsCols.end(); - Iter++) - { + Iter++) { SaleableUsageLimits.insert( Iter.key(), { @@ -720,15 +695,13 @@ Targoman::API::AAA::stuPreVoucher intfAccountingBasedModule::apiPOSTaddToBasket( QJsonArray arr = FullDiscount.cpnSaleableBasedMultiplier.array(); // qDebug() << "arr" << arr; - if (arr.size()) - { + if (arr.size()) { // qDebug() << "AAAAAAAAAAAAAAA 2" << arr; stuDiscountSaleableBasedMultiplier multiplier; for (QJsonArray::const_iterator itr = arr.constBegin(); itr != arr.constEnd(); - itr++) - { + itr++) { auto elm = *itr; // qDebug() << "elm" << elm << "elm.toObject()=" << elm.toObject(); @@ -741,8 +714,7 @@ Targoman::API::AAA::stuPreVoucher intfAccountingBasedModule::apiPOSTaddToBasket( if ((cur.SaleableCode == _saleableCode) && (NULLABLE_GET_OR_DEFAULT(cur.MinQty, 0) <= _qty) - ) - { + ) { if ((multiplier.Multiplier == 0) || (NULLABLE_GET_OR_DEFAULT(multiplier.MinQty, 0) < MinQty)) multiplier = cur; @@ -770,13 +742,11 @@ Targoman::API::AAA::stuPreVoucher intfAccountingBasedModule::apiPOSTaddToBasket( qDebug() << "2 Discount:" << "ID(" << Discount3.ID << ")" << "Code(" << Discount3.Code << ")" << "Amount(" << Discount3.Amount << ")"; //check cpnMaxAmount - if (NULLABLE_HAS_VALUE(FullDiscount.cpnMaxAmount)) - { + if (NULLABLE_HAS_VALUE(FullDiscount.cpnMaxAmount)) { //note: cpnMaxAmount type is opposite to cpnAmountType if (FullDiscount.cpnAmountType == enuDiscountType::Percent) Discount3.Amount = fmin(Discount3.Amount, NULLABLE_GET_OR_DEFAULT(FullDiscount.cpnMaxAmount, 0)); - else - { + else { quint32 _max = ceil(AssetItem.SubTotal * NULLABLE_GET_OR_DEFAULT(FullDiscount.cpnMaxAmount, 0) / 100.0); Discount3.Amount = fmin(Discount3.Amount, _max); } @@ -785,15 +755,13 @@ Targoman::API::AAA::stuPreVoucher intfAccountingBasedModule::apiPOSTaddToBasket( //check total - used amount qint32 remainDiscountAmount = FullDiscount.cpnTotalMaxAmount - FullDiscount.cpnTotalUsedAmount; - if (remainDiscountAmount < Discount3.Amount) - { + if (remainDiscountAmount < Discount3.Amount) { Discount3.Amount = remainDiscountAmount; qDebug() << "4 Discount:" << "ID(" << Discount3.ID << ")" << "Code(" << Discount3.Code << ")" << "Amount(" << Discount3.Amount << ")"; } //check per user - used amount - if (NULLABLE_GET_OR_DEFAULT(FullDiscount.cpnPerUserMaxAmount, 0) > 0) - { + if (NULLABLE_GET_OR_DEFAULT(FullDiscount.cpnPerUserMaxAmount, 0) > 0) { remainDiscountAmount = NULLABLE_GET_OR_DEFAULT(FullDiscount.cpnPerUserMaxAmount, 0) - NULLABLE_GET_OR_DEFAULT(_discountUsedAmount, 0); if (remainDiscountAmount <= 0) Discount3.Amount = 0; @@ -806,8 +774,7 @@ Targoman::API::AAA::stuPreVoucher intfAccountingBasedModule::apiPOSTaddToBasket( Discount3.Amount = ceil(Discount3.Amount); qDebug() << "Discount:" << "ID(" << Discount3.ID << ")" << "Code(" << Discount3.Code << ")" << "Amount(" << Discount3.Amount << ")"; - if (Discount3.Amount > 0) - { + if (Discount3.Amount > 0) { AssetItem.Discount = Discount3; AssetItem.TotalPrice = AssetItem.SubTotal - Discount3.Amount; @@ -876,8 +843,7 @@ Targoman::API::AAA::stuPreVoucher intfAccountingBasedModule::apiPOSTaddToBasket( // { tblAccountUserAssetsBase::uasStatus, }, }; - if (Discount3.ID > 0) - { + if (Discount3.ID > 0) { qry .addCol(tblAccountUserAssetsBase::uas_cpnID) .addCol(tblAccountUserAssetsBase::uasDiscountAmount) @@ -934,12 +900,10 @@ Targoman::API::AAA::stuPreVoucher intfAccountingBasedModule::apiPOSTremoveBasket qint64 FinalPrice = 0; auto iter = _lastPreVoucher.Items.begin(); - while (iter != _lastPreVoucher.Items.end()) - { + while (iter != _lastPreVoucher.Items.end()) { stuVoucherItem PreVoucherItem = *iter; - if (PreVoucherItem.UUID == _itemUUID) - { + if (PreVoucherItem.UUID == _itemUUID) { Found = true; //delete voucher item @@ -963,21 +927,18 @@ Targoman::API::AAA::stuPreVoucher intfAccountingBasedModule::apiPOSTremoveBasket //preventing ++iter continue; - } - else + } else FinalPrice += (PreVoucherItem.SubTotal - PreVoucherItem.DisAmount + PreVoucherItem.VATAmount); ++iter; } - if (Found) - { + if (Found) { if (_lastPreVoucher.Items.isEmpty()) _lastPreVoucher.Summary = ""; else if (_lastPreVoucher.Items.size() > 1) _lastPreVoucher.Summary = QString("%1 items").arg(_lastPreVoucher.Items.size()); - else - { + else { auto item = _lastPreVoucher.Items.first(); _lastPreVoucher.Summary = QString("%1 of %2").arg(item.Qty).arg(item.Desc); } @@ -1015,12 +976,10 @@ Targoman::API::AAA::stuPreVoucher intfAccountingBasedModule::apiPOSTupdateBasket qint64 FinalPrice = 0; auto iter = _lastPreVoucher.Items.begin(); - while (iter != _lastPreVoucher.Items.end()) - { + while (iter != _lastPreVoucher.Items.end()) { stuVoucherItem &PreVoucherItem = *iter; - if (PreVoucherItem.UUID == _itemUUID) - { + if (PreVoucherItem.UUID == _itemUUID) { Found = true; if (_new_qty == PreVoucherItem.Qty) @@ -1040,12 +999,9 @@ Targoman::API::AAA::stuPreVoucher intfAccountingBasedModule::apiPOSTupdateBasket throw exHTTPInternalServerError("only Pending items of pre-voucher can be modify."); // - if (_new_qty < PreVoucherItem.Qty) - { + if (_new_qty < PreVoucherItem.Qty) { - } - else //_new_qty > PreVoucherItem.Qty - { + } else { //_new_qty > PreVoucherItem.Qty } @@ -1092,12 +1048,10 @@ Targoman::API::AAA::stuPreVoucher intfAccountingBasedModule::apiPOSTupdateBasket ++iter; } - if (Found) - { + if (Found) { if (_lastPreVoucher.Items.size() > 1) _lastPreVoucher.Summary = QString("%1 items").arg(_lastPreVoucher.Items.size()); - else - { + else { auto item = _lastPreVoucher.Items.first(); _lastPreVoucher.Summary = QString("%1 of %2").arg(item.Qty).arg(item.Desc); } diff --git a/Interfaces/AAA/intfAccountingBasedModule.h b/Interfaces/AAA/intfAccountingBasedModule.h index e0138c67..eba3ef9c 100644 --- a/Interfaces/AAA/intfAccountingBasedModule.h +++ b/Interfaces/AAA/intfAccountingBasedModule.h @@ -159,15 +159,13 @@ protected slots: protected: virtual void digestPrivs(TAPI::JWT_t _JWT, - INOUT stuAssetItem& _assetItem) - { + INOUT stuAssetItem& _assetItem) { Q_UNUSED(_JWT); Q_UNUSED(_assetItem) }; virtual void applyAssetAdditives(TAPI::JWT_t _JWT, INOUT stuAssetItem& _assetItem, - const OrderAdditives_t& _orderAdditives) - { + const OrderAdditives_t& _orderAdditives) { Q_UNUSED(_JWT); Q_UNUSED(_assetItem) Q_UNUSED(_orderAdditives) @@ -175,8 +173,7 @@ protected slots: virtual void applyReferrer(TAPI::JWT_t _JWT, INOUT stuAssetItem& AssetItem, QString _referrer, - TAPI::JSON_t _extraReferrerParams) - { + TAPI::JSON_t _extraReferrerParams) { Q_UNUSED(_JWT); Q_UNUSED(AssetItem); Q_UNUSED(_referrer); diff --git a/Interfaces/API/APIQueryBuilders.cpp b/Interfaces/API/APIQueryBuilders.cpp index cbe5247f..77a1420f 100644 --- a/Interfaces/API/APIQueryBuilders.cpp +++ b/Interfaces/API/APIQueryBuilders.cpp @@ -30,8 +30,7 @@ using namespace Targoman::API::AAA; namespace Targoman::API::Query { -QVariantMap SelectOne(clsTable& _table, GET_METHOD_ARGS_IMPL_INTERNAL_CALL, const clsCondition& _extraFilters, quint16 _cacheTime, std::function _lambda_TouchQuery) -{ +QVariantMap SelectOne(clsTable& _table, GET_METHOD_ARGS_IMPL_INTERNAL_CALL, const clsCondition& _extraFilters, quint16 _cacheTime, std::function _lambda_TouchQuery) {/*KZ*/ Q_UNUSED(_userID) Q_UNUSED(_reportCount) @@ -57,8 +56,7 @@ QVariantMap SelectOne(clsTable& _table, GET_METHOD_ARGS_IMPL_INTERNAL_CALL, cons return Query.one(); } -QVariantList SelectAll(clsTable& _table, GET_METHOD_ARGS_IMPL_INTERNAL_CALL, const clsCondition& _extraFilters, quint16 _cacheTime, std::function _lambda_TouchQuery) -{ +QVariantList SelectAll(clsTable& _table, GET_METHOD_ARGS_IMPL_INTERNAL_CALL, const clsCondition& _extraFilters, quint16 _cacheTime, std::function _lambda_TouchQuery) {/*KZ*/ Q_UNUSED(_userID) Q_UNUSED(_reportCount) @@ -82,8 +80,7 @@ QVariantList SelectAll(clsTable& _table, GET_METHOD_ARGS_IMPL_INTERNAL_CALL, con return Query.all(); } -TAPI::stuTable SelectAllWithCount(clsTable& _table, GET_METHOD_ARGS_IMPL_INTERNAL_CALL, const clsCondition& _extraFilters, quint16 _cacheTime, std::function _lambda_TouchQuery) -{ +TAPI::stuTable SelectAllWithCount(clsTable& _table, GET_METHOD_ARGS_IMPL_INTERNAL_CALL, const clsCondition& _extraFilters, quint16 _cacheTime, std::function _lambda_TouchQuery) {/*KZ*/ Q_UNUSED(_userID) Q_UNUSED(_reportCount) @@ -107,8 +104,7 @@ TAPI::stuTable SelectAllWithCount(clsTable& _table, GET_METHOD_ARGS_IMPL_INTERNA return Query.allWithCount(); } -QVariant Select(clsTable& _table, GET_METHOD_ARGS_IMPL_INTERNAL_CALL, const clsCondition& _extraFilters, quint16 _cacheTime, std::function _lambda_TouchQuery) -{ +QVariant Select(clsTable& _table, GET_METHOD_ARGS_IMPL_INTERNAL_CALL, const clsCondition& _extraFilters, quint16 _cacheTime, std::function _lambda_TouchQuery) {/*KZ*/ if (_pksByPath.isEmpty()) { if (_reportCount) return SelectAllWithCount(_table, GET_METHOD_CALL_ARGS_INTERNAL_CALL_RAW, _extraFilters, _cacheTime, _lambda_TouchQuery).toVariant(); @@ -119,8 +115,7 @@ QVariant Select(clsTable& _table, GET_METHOD_ARGS_IMPL_INTERNAL_CALL, const clsC return SelectOne(_table, GET_METHOD_CALL_ARGS_INTERNAL_CALL_RAW, _extraFilters, _cacheTime, _lambda_TouchQuery); } -quint64 Create(clsTable& _table, CREATE_METHOD_ARGS_IMPL_INTERNAL_CALL) -{ +quint64 Create(clsTable& _table, CREATE_METHOD_ARGS_IMPL_INTERNAL_CALL) {/*KZ*/ _table.prepareFiltersList(); CreateQuery query = CreateQuery(_table); @@ -133,8 +128,7 @@ quint64 Create(clsTable& _table, CREATE_METHOD_ARGS_IMPL_INTERNAL_CALL) return query.execute(_userID); } -bool Update(clsTable& _table, UPDATE_METHOD_ARGS_IMPL_INTERNAL_CALL, const QVariantMap& _extraFilters) -{ +bool Update(clsTable& _table, UPDATE_METHOD_ARGS_IMPL_INTERNAL_CALL, const QVariantMap& _extraFilters) {/*KZ*/ _table.prepareFiltersList(); if (_pksByPath.isEmpty() && _extraFilters.isEmpty()) @@ -166,8 +160,7 @@ bool Update(clsTable& _table, UPDATE_METHOD_ARGS_IMPL_INTERNAL_CALL, const QVari return query.execute(_userID) > 0; } -bool DeleteByPks(clsTable& _table, DELETE_METHOD_ARGS_IMPL_INTERNAL_CALL, const QVariantMap& _extraFilters, bool _realDelete) -{ +bool DeleteByPks(clsTable& _table, DELETE_METHOD_ARGS_IMPL_INTERNAL_CALL, const QVariantMap& _extraFilters, bool _realDelete) {/*KZ*/ _table.prepareFiltersList(); if (_pksByPath.isEmpty() && _extraFilters.isEmpty()) diff --git a/Interfaces/API/clsRESTAPI.cpp b/Interfaces/API/clsRESTAPI.cpp index 481d79ea..c76056ee 100644 --- a/Interfaces/API/clsRESTAPI.cpp +++ b/Interfaces/API/clsRESTAPI.cpp @@ -43,6 +43,6 @@ clsRESTAPI::clsRESTAPI( _dbProperties ), Module(_module) -{} +{/*KZ*/;/*KZ*/} } // namespace Targoman::API::ORM diff --git a/Interfaces/API/intfPureModule.cpp b/Interfaces/API/intfPureModule.cpp index 3556068a..ff1a41e8 100644 --- a/Interfaces/API/intfPureModule.cpp +++ b/Interfaces/API/intfPureModule.cpp @@ -37,7 +37,7 @@ TAPI_VALIDATION_REQUIRED_TYPE_IMPL( [](const QList& _fields) { QStringList Cols; foreach(auto Col, _fields) - if(Col.isVirtual() == false) + if (Col.isVirtual() == false) Cols.append(clsTable::finalColName(Col)); return QString("Nothing for all or comma separated columns: (ex. %1,%2) \n" "you can also use aggregation functions: (ex. COUNT(%3))\n" @@ -53,7 +53,7 @@ TAPI_VALIDATION_REQUIRED_TYPE_IMPL( TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, Filter_t, QFieldValidator::allwaysValid(), _value, - [](const QList& _fields){ + [](const QList& _fields) { return "Filtering rules where '+'=AND, '|'=OR, '*'=XOR. All parenthesis and logical operators must be bounded by space.\n" "Equality/Inequality operators are\n" "* =: equal\n" @@ -66,20 +66,20 @@ TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, Filter_t, }); TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, OrderBy_t, QFieldValidator::allwaysValid(), _value, - [](const QList& _fields){ + [](const QList& _fields) { QStringList Cols; foreach(auto Col, _fields) - if(Col.isSortable() && Col.isVirtual() == false) + if (Col.isSortable() && Col.isVirtual() == false) Cols.append(clsTable::finalColName(Col)); return "Comma separated list of columns with +/- for ASC/DESC order prefix: (ex. +"+Cols.first()+",-"+Cols.last()+")\n* " + Cols.join("\n* "); // return "Comma separated list of columns with +/- for ASC/DESC order prefix: (ex. +"+Cols.first()+",-"+Cols.last()+")"; }); TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, GroupBy_t, QFieldValidator::allwaysValid(), _value, - [](const QList& _fields){ + [](const QList& _fields) { QStringList Cols; foreach(auto Col, _fields) - if(Col.isFilterable()) + if (Col.isFilterable()) Cols.append(clsTable::finalColName(Col)); return "Comma separated columns: \n* " + Cols.join(",\n* "); // return "Comma separated columns" ; @@ -93,13 +93,11 @@ intfPureModule::intfPureModule( ) : intfModule(_parent), ModuleName(_moduleName) -{ -} +{ ; } -//intfPureModule::~intfPureModule(){} +//intfPureModule::~intfPureModule() { ; } -void intfPureModule::addResponseHeaderNameToExpose(const QString &_header) -{ +void intfPureModule::addResponseHeaderNameToExpose(const QString &_header) { addResponseHeader("Access-Control-Expose-Headers", _header, true); } @@ -110,7 +108,7 @@ intfPureModule::stuDBInfo::stuDBInfo(QString _schema, quint16 _port, QString _ho User(_user), Pass(_pass), Schema(_schema) -{} +{ ; } QString intfPureModule::stuDBInfo::toConnStr(const QString &_dbPrefix, bool _noSchema) { return QString("HOST=%1;PORT=%2;USER=%3;PASSWORD=%4;SCHEMA=%5") diff --git a/Interfaces/API/intfPureModule.h b/Interfaces/API/intfPureModule.h index 96b0d7d0..ebccb6f7 100644 --- a/Interfaces/API/intfPureModule.h +++ b/Interfaces/API/intfPureModule.h @@ -72,22 +72,22 @@ #define ORMGET(_doc) \ apiGET(GET_METHOD_ARGS_HEADER_APICALL); \ - QString signOfGET(){ return TARGOMAN_M2STR((GET_METHOD_ARGS_HEADER_APICALL)); } \ + QString signOfGET() { return TARGOMAN_M2STR((GET_METHOD_ARGS_HEADER_APICALL)); } \ QString docOfGET() { return _doc; } #define ORMGETPureVirtual(_doc) \ apiGET(GET_METHOD_ARGS_HEADER_APICALL)=0; \ - virtual QString signOfGET(){ return TARGOMAN_M2STR((GET_METHOD_ARGS_HEADER_APICALL)); } \ + virtual QString signOfGET() { return TARGOMAN_M2STR((GET_METHOD_ARGS_HEADER_APICALL)); } \ virtual QString docOfGET() { return _doc; } #define ORMGETWithBody(_doc, _body) \ apiGET(GET_METHOD_ARGS_HEADER_APICALL) _body \ - virtual QString signOfGET(){ return TARGOMAN_M2STR((GET_METHOD_ARGS_HEADER_APICALL)); } \ + virtual QString signOfGET() { return TARGOMAN_M2STR((GET_METHOD_ARGS_HEADER_APICALL)); } \ virtual QString docOfGET() { return _doc; } #define ORMGETByName(_name, _doc) \ apiGET##_name(GET_METHOD_ARGS_HEADER_APICALL); \ - QString signOfGET##_name(){ return TARGOMAN_M2STR((GET_METHOD_ARGS_HEADER_APICALL)); } \ + QString signOfGET##_name() { return TARGOMAN_M2STR((GET_METHOD_ARGS_HEADER_APICALL)); } \ QString docOfGET##_name() { return _doc; } //used by ApiQuery @@ -143,7 +143,7 @@ #define CREATE_METHOD_ARGS_IMPL_APICALL TAPI::JWT_t _JWT, TAPI::ORMFields_t _createInfo //#define CREATE_METHOD_CALL_ARGS_APICALL _JWT, _createInfo #define ORMCREATE(_doc) apiCREATE(CREATE_METHOD_ARGS_HEADER_APICALL); \ - QString signOfCREATE(){ return TARGOMAN_M2STR((CREATE_METHOD_ARGS_HEADER_APICALL)); } \ + QString signOfCREATE() { return TARGOMAN_M2STR((CREATE_METHOD_ARGS_HEADER_APICALL)); } \ QString docOfCREATE() { return _doc; } //used by ApiQuery #define CREATE_METHOD_ARGS_HEADER_INTERNAL_CALL quint64 _userID, TAPI::ORMFields_t _createInfo = {} @@ -158,7 +158,7 @@ #define UPDATE_METHOD_ARGS_IMPL_APICALL TAPI::JWT_t _JWT, TAPI::PKsByPath_t _pksByPath, const TAPI::ORMFields_t& _updateInfo //#define UPDATE_METHOD_CALL_ARGS_APICALL clsJWT(_JWT).usrID(), _pksByPath, _updateInfo #define ORMUPDATE(_doc) apiUPDATE(UPDATE_METHOD_ARGS_HEADER_APICALL); \ - QString signOfUPDATE(){ return TARGOMAN_M2STR((UPDATE_METHOD_ARGS_HEADER_APICALL)); } \ + QString signOfUPDATE() { return TARGOMAN_M2STR((UPDATE_METHOD_ARGS_HEADER_APICALL)); } \ QString docOfUPDATE() { return _doc; } //used by ApiQuery #define UPDATE_METHOD_ARGS_HEADER_INTERNAL_CALL quint64 _userID, TAPI::PKsByPath_t _pksByPath = {}, const TAPI::ORMFields_t& _updateInfo = {} @@ -173,7 +173,7 @@ #define DELETE_METHOD_ARGS_IMPL_APICALL TAPI::JWT_t _JWT, TAPI::PKsByPath_t _pksByPath //#define DELETE_METHOD_CALL_ARGS_APICALL clsJWT(_JWT).usrID(), _pksByPath #define ORMDELETE(_doc) apiDELETE(DELETE_METHOD_ARGS_HEADER_APICALL); \ - QString signOfDELETE(){ return TARGOMAN_M2STR((DELETE_METHOD_ARGS_HEADER_APICALL)); } \ + QString signOfDELETE() { return TARGOMAN_M2STR((DELETE_METHOD_ARGS_HEADER_APICALL)); } \ QString docOfDELETE() { return _doc; } //used by ApiQuery #define DELETE_METHOD_ARGS_HEADER_INTERNAL_CALL quint64 _userID, TAPI::PKsByPath_t _pksByPath = {} @@ -250,8 +250,8 @@ namespace Targoman::API::API { # define APITIMEOUT_30S #endif -#define REST(_method, _name, _sig, _doc) api##_method##_name _sig; QString signOf##_method##_name(){ return #_sig; } QString docOf##_method##_name(){ return #_doc; } -#define ASYNC_REST(_method, _name, _sig, _doc) asyncApi##_method##_name _sig;QString signOf##_method##_name(){ return #_sig; } QString docOf##_method##_name(){ return #_doc; } +#define REST(_method, _name, _sig, _doc) api##_method##_name _sig; QString signOf##_method##_name() { return #_sig; } QString docOf##_method##_name() { return #_doc; } +#define ASYNC_REST(_method, _name, _sig, _doc) asyncApi##_method##_name _sig;QString signOf##_method##_name() { return #_sig; } QString docOf##_method##_name() { return #_doc; } #define REST_GET_OR_POST(_name, _sig, _doc) REST(, _name, _sig, _doc) #define ASYNC_REST_GET_OR_POST(_name, _sig, _doc) ASYNC_REST(, _name, _sig, _doc) @@ -301,7 +301,7 @@ class intfPureModule : public Targoman::Common::Configuration::intfModule stuModuleMethod(intfPureModule* _module, const QMetaMethod& _method) : Module(_module), Method(_method) - {} + { ; } }; typedef QList ModuleMethods_t; @@ -317,10 +317,9 @@ class intfPureModule : public Targoman::Common::Configuration::intfModule virtual stuDBInfo requiredDB() const { return {}; } virtual bool init() { return true; } - virtual void setInstancePointer() { }; + virtual void setInstancePointer() { ; }; - virtual QList filterItems(qhttp::THttpMethod _method = qhttp::EHTTP_ACL) - { + virtual QList filterItems(qhttp::THttpMethod _method = qhttp::EHTTP_ACL) { Targoman::API::DBM::clsTable* PTHIS = dynamic_cast(this); if (PTHIS == nullptr) return {}; @@ -328,8 +327,7 @@ class intfPureModule : public Targoman::Common::Configuration::intfModule PTHIS->prepareFiltersList(); return PTHIS->filterItems(_method); } - virtual void updateFilterParamType(const QString& _fieldTypeName, QMetaType::Type _typeID) - { + virtual void updateFilterParamType(const QString& _fieldTypeName, QMetaType::Type _typeID) { Targoman::API::DBM::clsTable* PTHIS = dynamic_cast(this); if (PTHIS == nullptr) return; diff --git a/Interfaces/API/intfSQLBasedModule.cpp b/Interfaces/API/intfSQLBasedModule.cpp index 92bd8469..5e2a9a75 100644 --- a/Interfaces/API/intfSQLBasedModule.cpp +++ b/Interfaces/API/intfSQLBasedModule.cpp @@ -53,7 +53,7 @@ intfSQLBasedModule::intfSQLBasedModule( _indexes, _dbProperties ) -{} +{ ; } intfSQLBasedModule::intfSQLBasedModule( const QString& _schema, @@ -72,7 +72,7 @@ intfSQLBasedModule::intfSQLBasedModule( _indexes, _dbProperties ) -{} +{ ; } QVariantMap intfSQLBasedModule::SelectOne( clsTable& _table, @@ -167,8 +167,7 @@ TAPI::stuTable intfSQLBasedModule::SelectAllWithCount( GET_METHOD_ARGS_IMPL_INTERNAL_CALL, const clsCondition& _extraFilters, quint16 _cacheTime, - std::function _lambda_TouchQuery) -{ + std::function _lambda_TouchQuery) { Q_UNUSED(_userID) Q_UNUSED(_reportCount) @@ -204,10 +203,8 @@ TAPI::stuTable intfSQLBasedModule::SelectAllWithCount( return Result; } -QVariant intfSQLBasedModule::Select(clsTable& _table, GET_METHOD_ARGS_IMPL_INTERNAL_CALL, const clsCondition& _extraFilters, quint16 _cacheTime, std::function _lambda_TouchQuery) -{ - if (_pksByPath.isEmpty()) - { +QVariant intfSQLBasedModule::Select(clsTable& _table, GET_METHOD_ARGS_IMPL_INTERNAL_CALL, const clsCondition& _extraFilters, quint16 _cacheTime, std::function _lambda_TouchQuery) { + if (_pksByPath.isEmpty()) { if (_reportCount) return this->SelectAllWithCount(_table, GET_METHOD_CALL_ARGS_INTERNAL_CALL_RAW, _extraFilters, _cacheTime, _lambda_TouchQuery) .toVariant() @@ -219,8 +216,7 @@ QVariant intfSQLBasedModule::Select(clsTable& _table, GET_METHOD_ARGS_IMPL_INTER return this->SelectOne(_table, GET_METHOD_CALL_ARGS_INTERNAL_CALL_RAW, _extraFilters, _cacheTime, _lambda_TouchQuery); } -quint64 intfSQLBasedModule::Create(clsTable& _table, CREATE_METHOD_ARGS_IMPL_INTERNAL_CALL) -{ +quint64 intfSQLBasedModule::Create(clsTable& _table, CREATE_METHOD_ARGS_IMPL_INTERNAL_CALL) { _table.prepareFiltersList(); CreateQuery query = CreateQuery(_table); @@ -233,8 +229,7 @@ quint64 intfSQLBasedModule::Create(clsTable& _table, CREATE_METHOD_ARGS_IMPL_INT return query.execute(_userID); } -bool intfSQLBasedModule::Update(clsTable& _table, UPDATE_METHOD_ARGS_IMPL_INTERNAL_CALL, const QVariantMap& _extraFilters) -{ +bool intfSQLBasedModule::Update(clsTable& _table, UPDATE_METHOD_ARGS_IMPL_INTERNAL_CALL, const QVariantMap& _extraFilters) { _table.prepareFiltersList(); if (_pksByPath.isEmpty() && _extraFilters.isEmpty()) @@ -266,8 +261,7 @@ bool intfSQLBasedModule::Update(clsTable& _table, UPDATE_METHOD_ARGS_IMPL_INTERN return query.execute(_userID) > 0; } -bool intfSQLBasedModule::DeleteByPks(clsTable& _table, DELETE_METHOD_ARGS_IMPL_INTERNAL_CALL, const QVariantMap& _extraFilters, bool _realDelete) -{ +bool intfSQLBasedModule::DeleteByPks(clsTable& _table, DELETE_METHOD_ARGS_IMPL_INTERNAL_CALL, const QVariantMap& _extraFilters, bool _realDelete) { _table.prepareFiltersList(); if (_pksByPath.isEmpty() && _extraFilters.isEmpty()) diff --git a/Interfaces/API/intfSQLBasedWithActionLogsModule.cpp b/Interfaces/API/intfSQLBasedWithActionLogsModule.cpp index 668d98af..a2412b39 100644 --- a/Interfaces/API/intfSQLBasedWithActionLogsModule.cpp +++ b/Interfaces/API/intfSQLBasedWithActionLogsModule.cpp @@ -36,6 +36,6 @@ intfSQLBasedWithActionLogsModule::intfSQLBasedWithActionLogsModule( _schema, "" ) -{} +{ ; } } // namespace Targoman::API::API diff --git a/Interfaces/Common/APIArgHelperMacrosPrivate.h b/Interfaces/Common/APIArgHelperMacrosPrivate.h index d0993894..c2ea869f 100644 --- a/Interfaces/Common/APIArgHelperMacrosPrivate.h +++ b/Interfaces/Common/APIArgHelperMacrosPrivate.h @@ -138,8 +138,7 @@ #define TAPI_HELEPER_VARIANTSTRUCT_CONS_INIT20(t,n,d,i,to,fr, ...) n(_##n), TAPI_HELEPER_VARIANTSTRUCT_CONS_INIT19(__VA_ARGS__) //extern QString toCammel(const QString& _name); -inline QString toCammel(const QString& _name) -{ +inline QString toCammel(const QString& _name) { return _name.mid(0,1).toLower() + _name.mid(1); } @@ -216,7 +215,7 @@ inline QString toCammel(const QString& _name) template<> std::function tmplAPIArg<_namespace::_type, _complexity, false>::fromORMValueLambda = _fromORMValueLambda; \ template<> std::function tmplAPIArg<_namespace::_type, _complexity, false>::optionsLambda = _lambdaOptions; \ template<> std::function tmplAPIArg::toVariantLambda = \ - [](NULLABLE_TYPE(_namespace::_type) _value){return NULLABLE_IS_NULL(_value) ? QVariant() : tmplAPIArg<_namespace::_type, _complexity, false>::toVariant(*_value);}; \ + [](NULLABLE_TYPE(_namespace::_type) _value) {return NULLABLE_IS_NULL(_value) ? QVariant() : tmplAPIArg<_namespace::_type, _complexity, false>::toVariant(*_value);}; \ template<> std::function tmplAPIArg::fromVariantLambda = \ [](const QVariant& _value, const QByteArray& _paramName) -> NULLABLE_TYPE(_namespace::_type) { \ if (!_value.isValid() || _value.isNull()) \ @@ -266,7 +265,7 @@ inline QString toCammel(const QString& _name) template<> std::function tmplAPIArg<_namespace::_enum::Type, COMPLEXITY_Enum, false>::optionsLambda = _lambdaOptions; \ template<> std::function& _allFields)> tmplAPIArg<_namespace::_enum::Type, COMPLEXITY_Enum, false>::descriptionLambda = _descriptionLambda; \ template<> std::function tmplAPIArg::toVariantLambda = \ - [](NULLABLE_TYPE(_namespace::_enum::Type) _value){return NULLABLE_IS_NULL(_value) ? QVariant() : tmplAPIArg<_namespace::_enum::Type, COMPLEXITY_Enum, false>::toVariant(*_value);}; \ + [](NULLABLE_TYPE(_namespace::_enum::Type) _value) {return NULLABLE_IS_NULL(_value) ? QVariant() : tmplAPIArg<_namespace::_enum::Type, COMPLEXITY_Enum, false>::toVariant(*_value);}; \ template<> std::function tmplAPIArg::fromVariantLambda = \ [](const QVariant& _value, const QByteArray& _paramName) -> NULLABLE_TYPE(_namespace::_enum::Type) { \ if (!_value.isValid() || _value.isNull()) return NULLABLE_TYPE(_namespace::_enum::Type)(); \ @@ -290,8 +289,8 @@ inline QString toCammel(const QString& _name) #define INTERNAL_TAPI_ADD_TYPE_SPECIALFROMVARIANT(_baseType, _typeName, _setFromVariantLambda) \ class _typeName : public _baseType { \ public: \ - _typeName() {} \ - _typeName(const _baseType& _other):_baseType(_other) {} \ + _typeName() { ; } \ + _typeName(const _baseType& _other) :_baseType(_other) { ; } \ void customFromVariant(const QVariant& _value) { _setFromVariantLambda(_value); } \ static _typeName fromVariant(const QVariant& _value) { \ _typeName _var; \ diff --git a/Interfaces/Common/GenericTypes.cpp b/Interfaces/Common/GenericTypes.cpp index 5b6e6d52..ea65af0d 100644 --- a/Interfaces/Common/GenericTypes.cpp +++ b/Interfaces/Common/GenericTypes.cpp @@ -97,10 +97,10 @@ TAPI_REGISTER_METATYPE( /* toVariantLambda */ nullptr, /* fromVariantLambda */ [](const QVariant& _value, const QByteArray& _paramName) -> JWT_t { QJsonObject Obj; - if(_value.canConvert()) + if (_value.canConvert()) Obj = Obj.fromVariantMap(_value.value()); - if(Obj.isEmpty()) + if (Obj.isEmpty()) throw exHTTPBadRequest(_paramName + " is not a valid JWT object"); return *reinterpret_cast(&Obj); } @@ -128,50 +128,50 @@ TAPI_REGISTER_JSON_DERIVED_METATYPE( /* [](const PrivObject_t& _value) -> QVariant {return _value;} [](const QVariant& _value, const QByteArray& _paramName) -> PrivObject_t { - if(_value.isValid() == false) + if (_value.isValid() == false) return QJsonDocument(); QJsonDocument Doc; - if(_value.canConvert() || + if (_value.canConvert() || _value.canConvert() || _value.canConvert()) Doc = QJsonDocument::fromVariant(_value); - else if(_value.toString().isEmpty()) + else if (_value.toString().isEmpty()) return QJsonDocument(); else { QJsonParseError Error; QJsonDocument Doc; Doc = Doc.fromJson(_value.toString().toUtf8(), &Error); - if(Error.error != QJsonParseError::NoError) + if (Error.error != QJsonParseError::NoError) throw exHTTPBadRequest(_paramName + " is not a valid Json: <"+_value.toString()+">" + Error.errorString()); } - if(Doc.isNull() || Doc.isEmpty()) + if (Doc.isNull() || Doc.isEmpty()) return Doc; - if(Doc.isArray()) + if (Doc.isArray()) throw exHTTPBadRequest(_paramName + " is not a valid PrivObject: <"+_value.toString()+"> must be object not array"); QJsonObject PrivObj = Doc.object(); - if(PrivObj.contains("ALL")) + if (PrivObj.contains("ALL")) throw exHTTPUnauthorized(_paramName + " is not a valid PrivObject: <"+_value.toString()+"> top level allowance is not valid"); return Doc; }, - [](const QList&){ return "A valid Privilege JSON object"; }, + [](const QList&) { return "A valid Privilege JSON object"; }, [](const QVariant& _value) { - if(_value.isNull() || _value.toString().isEmpty()) //OJO why?!!! + if (_value.isNull() || _value.toString().isEmpty()) //OJO why?!!! return QJsonDocument(); QJsonParseError Error; QJsonDocument Doc; - if(_value.canConvert() || + if (_value.canConvert() || _value.canConvert() || _value.canConvert()) Doc = QJsonDocument::fromVariant(_value); else Doc = Doc.fromJson(_value.toString().toUtf8(), &Error); - if(Error.error != QJsonParseError::NoError) + if (Error.error != QJsonParseError::NoError) throw exHTTPBadRequest("is not a valid Privilege: <"+_value.toString()+">" + Error.errorString()); return Doc; }, @@ -189,28 +189,28 @@ TAPI_REGISTER_JSON_DERIVED_METATYPE( /* [](const SaleableAdditive_t& _value) -> QVariant {return _value;} [](const QVariant& _value, const QByteArray& _paramName) -> SaleableAdditive_t { - if(_value.isValid() == false) + if (_value.isValid() == false) return QJsonDocument(); QJsonDocument Doc; - if(_value.canConvert() || + if (_value.canConvert() || _value.canConvert() || _value.canConvert()) Doc = QJsonDocument::fromVariant(_value); - else if(_value.toString().isEmpty()) + else if (_value.toString().isEmpty()) return QJsonDocument(); else { QJsonParseError Error; QJsonDocument Doc; Doc = Doc.fromJson(_value.toString().toUtf8(), &Error); - if(Error.error != QJsonParseError::NoError) + if (Error.error != QJsonParseError::NoError) throw exHTTPBadRequest(_paramName + " is not a valid Json: <"+_value.toString()+">" + Error.errorString()); } - if(Doc.isNull() || Doc.isEmpty()) + if (Doc.isNull() || Doc.isEmpty()) return Doc; - if(Doc.isArray()) + if (Doc.isArray()) throw exHTTPBadRequest(_paramName + " is not a valid PrivObject: <"+_value.toString()+"> must be object not array"); QJsonObject PrivObj = Doc.object(); @@ -229,7 +229,7 @@ throw Targoman::Common::exTargomanMustBeImplemented("SaleableAdditive_t not impl return Doc; }, - [](const QList&){ return "A valid Saleable Additive JSON object"; }, + [](const QList&) { return "A valid Saleable Additive JSON object"; }, [](const QVariant& _value) { @@ -242,18 +242,18 @@ throw Targoman::Common::exTargomanMustBeImplemented("SaleableAdditive_t not impl - if(_value.isNull() || _value.toString().isEmpty()) //OJO why?!!! + if (_value.isNull() || _value.toString().isEmpty()) //OJO why?!!! return QJsonDocument(); QJsonParseError Error; QJsonDocument Doc; - if(_value.canConvert() || + if (_value.canConvert() || _value.canConvert() || _value.canConvert()) Doc = QJsonDocument::fromVariant(_value); else Doc = Doc.fromJson(_value.toString().toUtf8(), &Error); - if(Error.error != QJsonParseError::NoError) + if (Error.error != QJsonParseError::NoError) throw exHTTPBadRequest("is not a valid Saleable Additive: <"+_value.toString()+">" + Error.errorString()); return Doc; }, @@ -269,7 +269,7 @@ TAPI_REGISTER_METATYPE( /* type */ EncodedJWT_t, /* toVariantLambda */ [](const EncodedJWT_t& _value) -> QVariant {return _value;}, /* fromVariantLambda */ nullptr, - [](const QList&){ return "A signed JsonWebToken string"; } + [](const QList&) { return "A signed JsonWebToken string"; } ); TAPI_REGISTER_METATYPE( @@ -310,7 +310,7 @@ TAPI_REGISTER_METATYPE( /* type */ Date_t, /* toVariantLambda */ [](const Date_t& _value) -> QVariant {return _value;}, /* fromVariantLambda */ [](const QVariant& _value, const QByteArray& _paramName) -> Date_t { - if(_value.canConvert() == false) + if (_value.canConvert() == false) throw exHTTPBadRequest(_paramName + " is not a valid Date: <"+_value.toString()+">"); return _value.toDate(); } @@ -322,7 +322,7 @@ TAPI_REGISTER_METATYPE( /* type */ Time_t, /* toVariantLambda */ [](const Time_t& _value) -> QVariant {return _value;}, /* fromVariantLambda */ [](const QVariant& _value, const QByteArray& _paramName) -> Time_t { - if(_value.canConvert() == false) + if (_value.canConvert() == false) throw exHTTPBadRequest(_paramName + " is not a valid Time: <"+_value.toString()+">"); return _value.toTime(); } @@ -334,8 +334,7 @@ TAPI_REGISTER_METATYPE( /* type */ DateTime_t, /* toVariantLambda */ [](const DateTime_t& _value) -> QVariant { return _value; }, /* fromVariantLambda */ [](const QVariant& _value, const QByteArray& _paramName) -> DateTime_t { - if (_value.canConvert() == false) - { + if (_value.canConvert() == false) { print_stacktrace(); throw exHTTPBadRequest(_paramName + " is not a valid DateTime: <" + _value.toString() + ">"); } @@ -343,31 +342,30 @@ TAPI_REGISTER_METATYPE( } ) -TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, MD5_t, optional(QFV.md5()), _value, [](const QList&){ return "A valid MD5 string"; }); -TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, CommaSeparatedStringList_t, optional(QFV.asciiAlNum(false, ",")), _value, [](const QList&){ return "A valid comma separated string list"; }); -TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, Email_t, optional(QFV.email()), _value, [](const QList&){ return "A valid email"; }); -TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, Mobile_t, optional(QFV.mobile()), _value, [](const QList&){ return "A valid mobile number with/without country code"; }); -TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, IPv4_t, optional(QFV.ipv4()), _value, [](const QList&){ return "A valid IP version 4"; }); -TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, ISO639_2_t, optional(QFV.maxLenght(2).languageCode()), _value, [](const QList&){ return "A valid ISO639 two-letter language code"; }); -TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, Base64Image_t, optional(QFV.base64Image()), _value, [](const QList&){ return "A valid base64 encoded png/jpg image"; }); -TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, Sheba_t, optional(QFV.iban("IR")), _value, [](const QList&){ return "A valid Iranian sheba code"; }); +TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, MD5_t, optional(QFV.md5()), _value, [](const QList&) { return "A valid MD5 string"; }); +TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, CommaSeparatedStringList_t, optional(QFV.asciiAlNum(false, ",")), _value, [](const QList&) { return "A valid comma separated string list"; }); +TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, Email_t, optional(QFV.email()), _value, [](const QList&) { return "A valid email"; }); +TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, Mobile_t, optional(QFV.mobile()), _value, [](const QList&) { return "A valid mobile number with/without country code"; }); +TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, IPv4_t, optional(QFV.ipv4()), _value, [](const QList&) { return "A valid IP version 4"; }); +TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, ISO639_2_t, optional(QFV.maxLenght(2).languageCode()), _value, [](const QList&) { return "A valid ISO639 two-letter language code"; }); +TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, Base64Image_t, optional(QFV.base64Image()), _value, [](const QList&) { return "A valid base64 encoded png/jpg image"; }); +TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, Sheba_t, optional(QFV.iban("IR")), _value, [](const QList&) { return "A valid Iranian sheba code"; }); ///TODO: Ether/Bitcoin validator -TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, Ether_t, optional(QFV.allwaysValid()), _value, [](const QList&){ return "A valid ethercoin address"; }); -TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, URL_t, optional(QFV.url()), _value, [](const QList&){ return "A valid URL"; }); -TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, ProductCode_t, optional(QFV.matches(QRegularExpression("[a-zA-Z\\-_0-9]{3,10}"))), _value, [](const QList&){ return "A valid ProductCode"; }); -TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, SaleableCode_t, optional(QFV.matches(QRegularExpression("[a-zA-Z\\-_0-9]{3,10}"))), _value, [](const QList&){ return "A valid SaleableCode"; }); -TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, DBTinyText_t, optional(QFV.matches(QRegularExpression("(?s).*")).maxLenght(255)), _value, [](const QList&){ return "A valid tiny text"; }); -TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, DBText_t, optional(QFV.matches(QRegularExpression("(?s).*")).maxLenght(65535)), _value, [](const QList&){ return "A valid text"; }); -TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, DBMediumText_t, optional(QFV.matches(QRegularExpression("(?s).*")).maxLenght(16777215)), _value, [](const QList&){ return "A valid medium text"; }); -TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, DBLongText_t, optional(QFV.matches(QRegularExpression("(?s).*")).maxLenght(4294967295)), _value, [](const QList&){ return "A valid long text"; }); -TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, String_t, optional(QFV.matches(QRegularExpression("(?s).*"))), _value, [](const QList&){ return "A valid String"; }); +TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, Ether_t, optional(QFV.allwaysValid()), _value, [](const QList&) { return "A valid ethercoin address"; }); +TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, URL_t, optional(QFV.url()), _value, [](const QList&) { return "A valid URL"; }); +TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, ProductCode_t, optional(QFV.matches(QRegularExpression("[a-zA-Z\\-_0-9]{3,10}"))), _value, [](const QList&) { return "A valid ProductCode"; }); +TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, SaleableCode_t, optional(QFV.matches(QRegularExpression("[a-zA-Z\\-_0-9]{3,10}"))), _value, [](const QList&) { return "A valid SaleableCode"; }); +TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, DBTinyText_t, optional(QFV.matches(QRegularExpression("(?s).*")).maxLenght(255)), _value, [](const QList&) { return "A valid tiny text"; }); +TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, DBText_t, optional(QFV.matches(QRegularExpression("(?s).*")).maxLenght(65535)), _value, [](const QList&) { return "A valid text"; }); +TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, DBMediumText_t, optional(QFV.matches(QRegularExpression("(?s).*")).maxLenght(16777215)), _value, [](const QList&) { return "A valid medium text"; }); +TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, DBLongText_t, optional(QFV.matches(QRegularExpression("(?s).*")).maxLenght(4294967295)), _value, [](const QList&) { return "A valid long text"; }); +TAPI_VALIDATION_REQUIRED_TYPE_IMPL(COMPLEXITY_String, TAPI, String_t, optional(QFV.matches(QRegularExpression("(?s).*"))), _value, [](const QList&) { return "A valid String"; }); TAPI_REGISTER_TARGOMAN_ENUM(TAPI, enuGenericStatus); -stuFileInfo stuFileInfo::fromVariant(const QVariant& _value, const QByteArray& _paramName) -{ +stuFileInfo stuFileInfo::fromVariant(const QVariant& _value, const QByteArray& _paramName) { QVariantMap Value = _value.toMap(); - if(Value.isEmpty() || !Value.contains("name") || !Value.contains("tmpname") || !Value.contains("size") || !Value.contains("mime")) + if (Value.isEmpty() || !Value.contains("name") || !Value.contains("tmpname") || !Value.contains("size") || !Value.contains("mime")) throw exHTTPBadRequest(_paramName + " is not valid File information"); return stuFileInfo( @@ -395,8 +393,7 @@ QVariant Files_t::toVariant() const return Files; } -Files_t& Files_t::fromVariant(const QVariant& _value, const QByteArray& _paramName) -{ +Files_t& Files_t::fromVariant(const QVariant& _value, const QByteArray& _paramName) { foreach(auto ListItem, _value.toList()) this->append(TAPI::stuFileInfo::fromVariant(ListItem, _paramName)); return *this; @@ -405,8 +402,7 @@ Files_t& Files_t::fromVariant(const QVariant& _value, const QByteArray& _paramNa RawData_t::RawData_t(const QByteArray& _data, const QString& _mime) : Mime(_mime), Data(_data) -{ -} +{ ; } QVariant RawData_t::toVariant() const { diff --git a/Interfaces/Common/GenericTypes.h b/Interfaces/Common/GenericTypes.h index d74a4463..2ee8fec4 100644 --- a/Interfaces/Common/GenericTypes.h +++ b/Interfaces/Common/GenericTypes.h @@ -58,14 +58,14 @@ struct stuStatistics { QHash APIInternalCacheStats; QHash APICentralCacheStats; - QJsonObject toJson(bool _full = false){ - auto count2Json = [](const Targoman::Common::clsCountAndSpeed& _value){ + QJsonObject toJson(bool _full = false) { + auto count2Json = [](const Targoman::Common::clsCountAndSpeed& _value) { return QJsonObject({ {"count", static_cast(_value.count())}, {"cps", _value.countPerSecond()} }); }; - auto hashToJson = [count2Json](const QHash& _hash){ + auto hashToJson = [count2Json](const QHash& _hash) { QJsonObject RetObj; for (auto Iter=_hash.begin(); Iter != _hash.end(); ++Iter) RetObj.insert(Iter.key(), count2Json(Iter.value())); @@ -79,7 +79,7 @@ struct stuStatistics { {"Success", count2Json(this->Success)}, }; - if(_full){ + if (_full) { Stats.insert("APICallsStats", hashToJson(APICallsStats)); Stats.insert("APIInternalCacheStats", hashToJson(APIInternalCacheStats)); Stats.insert("APICentralCacheStats", hashToJson(APICentralCacheStats)); @@ -95,10 +95,10 @@ struct stuStatistics { struct stuTable { qint64 TotalRows; QVariantList Rows; - stuTable(qint64 _totalRows = -1, const QVariantList& _rows = QVariantList()): + stuTable(qint64 _totalRows = -1, const QVariantList& _rows = QVariantList()) : TotalRows(_totalRows), Rows(_rows) - {} + { ; } QVariant toVariant() const{ return QVariantMap({ {"rows", this->Rows}, @@ -118,14 +118,14 @@ struct stuFileInfo { TempName(_tmpName), Size(_size), Mime(_mime) - {} + { ; } stuFileInfo(const stuFileInfo& _other) : Name(_other.Name), TempName(_other.TempName), Size(_other.Size), Mime(_other.Mime) - {} + { ; } QVariant toVariant() const; diff --git a/Interfaces/Common/HTTPExceptions.hpp b/Interfaces/Common/HTTPExceptions.hpp index 2b0ac471..120afb0c 100644 --- a/Interfaces/Common/HTTPExceptions.hpp +++ b/Interfaces/Common/HTTPExceptions.hpp @@ -35,15 +35,15 @@ namespace API { class exHTTPError : public Targoman::Common::exTargomanBase { public: - exHTTPError(const QString& _definition, quint16 _errorCode, const QString& _message): + exHTTPError(const QString& _definition, quint16 _errorCode, const QString& _message) : Targoman::Common::exTargomanBase(_message, _errorCode), Definition(_definition) - {} + { ; } virtual void toEnsureAvoidanceOfUsingBaseClass()=0; inline const QString definition() const{return this->Definition;} - inline const QString fullError(){ + inline const QString fullError() { return QString("%1(%2): %3").arg( this->definition()).arg( this->code()).arg( @@ -59,7 +59,7 @@ class exHTTPError : public Targoman::Common::exTargomanBase { public: _name (const QString& _message = "") : \ exHTTPError (QString(TARGOMAN_M2STR(_name)).mid(2), _code, _message) \ {} \ - void toEnsureAvoidanceOfUsingBaseClass(){} \ + void toEnsureAvoidanceOfUsingBaseClass() { ; } \ } /*******************************************************************************/ diff --git a/Interfaces/Common/QtTypes.hpp b/Interfaces/Common/QtTypes.hpp index e85baedd..59a57385 100644 --- a/Interfaces/Common/QtTypes.hpp +++ b/Interfaces/Common/QtTypes.hpp @@ -63,15 +63,14 @@ #define DEFINE_SETFROMVARIANT_METHOD_ON_COMPLEXITY_Complex(_baseType) \ namespace TAPI { \ - inline void setFromVariant(_baseType& _storage, const QVariant& _val){ _storage = _val.value<_baseType>(); } \ - inline void setFromVariant(NULLABLE_TYPE(_baseType)& _storage, const QVariant& _val){ \ + inline void setFromVariant(_baseType& _storage, const QVariant& _val) { _storage = _val.value<_baseType>(); } \ + inline void setFromVariant(NULLABLE_TYPE(_baseType)& _storage, const QVariant& _val) { \ if (_val.isValid() && _val.isNull() == false) _storage = _val.value<_baseType>(); \ } \ } //https://cpp.hotexamples.com/examples/-/QString/toLongLong/cpp-qstring-tolonglong-method-examples.html -inline QVariant readNumber(const QString& _str, bool *ok) -{ +inline QVariant readNumber(const QString& _str, bool *ok) { //m_settings->locale() QString negativeSign = "-"; QString decimalSymbol = "."; @@ -158,7 +157,7 @@ inline QVariant readNumber(const QString& _str, bool *ok) #define TAPI_SPECIAL_MAKE_GENERIC_ON_NUMERIC_TYPE(_numericType, _convertor) \ namespace Targoman::API::Common { \ -template<> inline QGenericArgument tmplAPIArg<_numericType, COMPLEXITY_Integral, false, true>::makeGenericArgument(const QVariant& _val, const QByteArray& _paramName, void** _argStorage){ \ +template<> inline QGenericArgument tmplAPIArg<_numericType, COMPLEXITY_Integral, false, true>::makeGenericArgument(const QVariant& _val, const QByteArray& _paramName, void** _argStorage) { \ bool Result; \ *_argStorage = new _numericType; \ _numericType ConvertedVal; \ @@ -174,7 +173,7 @@ template<> inline QGenericArgument tmplAPIArg<_numericType, COMPLEXITY_Integral, throw exHTTPBadRequest("Invalid value specified for parameter: " + _paramName); \ return QGenericArgument(this->RealTypeName, *_argStorage); \ } \ -template<> inline QGenericArgument tmplAPIArg::makeGenericArgument(const QVariant& _val, const QByteArray& _paramName, void** _argStorage){ \ +template<> inline QGenericArgument tmplAPIArg::makeGenericArgument(const QVariant& _val, const QByteArray& _paramName, void** _argStorage) { \ bool Result = true; \ *_argStorage = new NULLABLE_TYPE(_numericType); \ if (_val.isValid() && _val.isNull() == false) \ @@ -195,15 +194,15 @@ template<> inline QGenericArgument tmplAPIArg(_val._convertor(&Result)); \ if (!Result) throw Targoman::API::exHTTPBadRequest(QString("Invalid value (%1) specified for base type: %2").arg(_val.toString()).arg(#_numericType)); \ } \ -inline void setFromVariant(NULLABLE_TYPE(_numericType)& _storage, const QVariant& _val){ \ - bool Result = true; if(_val.isValid() && _val.isNull() == false) _storage = static_cast<_numericType>(_val._convertor(&Result)); \ +inline void setFromVariant(NULLABLE_TYPE(_numericType)& _storage, const QVariant& _val) { \ + bool Result = true; if (_val.isValid() && _val.isNull() == false) _storage = static_cast<_numericType>(_val._convertor(&Result)); \ if (!Result) throw Targoman::API::exHTTPBadRequest(QString("Invalid value (%1) specified for base type: NULLABLE<%1>").arg(_val.toString()).arg(#_numericType)); \ } \ -inline QJsonValue toJsonValue(const NULLABLE_TYPE(_numericType)& _val){ \ +inline QJsonValue toJsonValue(const NULLABLE_TYPE(_numericType)& _val) { \ qDebug() << "toJsonValue(?)" << NULLABLE_GET_OR_DEFAULT(_val, 99999999); \ QJsonValue JsonVal; JsonVal = NULLABLE_IS_NULL(_val) ? QJsonValue() : static_cast(*_val); return JsonVal; } \ } diff --git a/Interfaces/Common/ServerCommon.cpp b/Interfaces/Common/ServerCommon.cpp index ee72ebca..64beda9d 100644 --- a/Interfaces/Common/ServerCommon.cpp +++ b/Interfaces/Common/ServerCommon.cpp @@ -39,8 +39,7 @@ tmplConfigurable ServerCommonConfigs::DBPrefix( enuConfigSource::Arg | enuConfigSource::File ); -const QString PrependSchema(const QString &_schema) -{ +const QString PrependSchema(const QString &_schema) { return ServerCommonConfigs::DBPrefix.value() + _schema; } diff --git a/Interfaces/Common/ServerCommon.h b/Interfaces/Common/ServerCommon.h index 4941ad24..711a9cd1 100644 --- a/Interfaces/Common/ServerCommon.h +++ b/Interfaces/Common/ServerCommon.h @@ -30,7 +30,7 @@ namespace Targoman::API::Common { struct ServerCommonConfigs { - static inline QString makeConfig(const QString& _name){return "/Server/" + _name;} + static inline QString makeConfig(const QString& _name) {return "/Server/" + _name;} static Targoman::Common::Configuration::tmplConfigurable DBPrefix; }; diff --git a/Interfaces/Common/base.cpp b/Interfaces/Common/base.cpp index cd4d46b4..6b209f6b 100644 --- a/Interfaces/Common/base.cpp +++ b/Interfaces/Common/base.cpp @@ -23,8 +23,7 @@ #include "base.h" #include -extern void print_stacktrace(FILE *out, unsigned int max_frames) -{ +extern void print_stacktrace(FILE *out, unsigned int max_frames) { #ifdef QT_DEBUG fprintf(out, "stack trace:\n"); @@ -35,8 +34,8 @@ extern void print_stacktrace(FILE *out, unsigned int max_frames) int addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void*)); if (addrlen == 0) { - fprintf(out, " \n"); - return; + fprintf(out, " \n"); + return; } // resolve addresses into strings containing "filename(function+address)", @@ -49,56 +48,50 @@ extern void print_stacktrace(FILE *out, unsigned int max_frames) // iterate over the returned symbol lines. skip the first, it is the // address of this function. - for (int i = 1; i < addrlen; i++) - { - char *begin_name = 0, *begin_offset = 0, *end_offset = 0; + for (int i = 1; i < addrlen; i++) { + char *begin_name = 0, *begin_offset = 0, *end_offset = 0; - // find parentheses and +address offset surrounding the mangled name: - // ./module(function+0x15c) [0x8048a6d] - for (char *p = symbollist[i]; *p; ++p) - { - if (*p == '(') - begin_name = p; - else if (*p == '+') - begin_offset = p; - else if (*p == ')' && begin_offset) { - end_offset = p; - break; + // find parentheses and +address offset surrounding the mangled name: + // ./module(function+0x15c) [0x8048a6d] + for (char *p = symbollist[i]; *p; ++p) { + if (*p == '(') + begin_name = p; + else if (*p == '+') + begin_offset = p; + else if (*p == ')' && begin_offset) { + end_offset = p; + break; + } } - } - if (begin_name && begin_offset && end_offset - && begin_name < begin_offset) - { - *begin_name++ = '\0'; - *begin_offset++ = '\0'; - *end_offset = '\0'; + if (begin_name && begin_offset && end_offset + && begin_name < begin_offset) { + *begin_name++ = '\0'; + *begin_offset++ = '\0'; + *end_offset = '\0'; - // mangled name is now in [begin_name, begin_offset) and caller - // offset in [begin_offset, end_offset). now apply - // __cxa_demangle(): + // mangled name is now in [begin_name, begin_offset) and caller + // offset in [begin_offset, end_offset). now apply + // __cxa_demangle(): - int status; - char* ret = abi::__cxa_demangle(begin_name, - funcname, &funcnamesize, &status); - if (status == 0) { - funcname = ret; // use possibly realloc()-ed string - fprintf(out, " %s : %s+%s\n", - symbollist[i], funcname, begin_offset); - } - else { - // demangling failed. Output function name as a C function with - // no arguments. - fprintf(out, " %s : %s()+%s\n", - symbollist[i], begin_name, begin_offset); + int status; + char* ret = abi::__cxa_demangle(begin_name, + funcname, &funcnamesize, &status); + if (status == 0) { + funcname = ret; // use possibly realloc()-ed string + fprintf(out, " %s : %s+%s\n", + symbollist[i], funcname, begin_offset); + } else { + // demangling failed. Output function name as a C function with + // no arguments. + fprintf(out, " %s : %s()+%s\n", + symbollist[i], begin_name, begin_offset); + } + } else { + // couldn't parse the line? print the whole line. + fprintf(out, " %s\n", symbollist[i]); } } - else - { - // couldn't parse the line? print the whole line. - fprintf(out, " %s\n", symbollist[i]); - } - } free(funcname); free(symbollist); diff --git a/Interfaces/Common/intfAPIArgManipulator.cpp b/Interfaces/Common/intfAPIArgManipulator.cpp index a0cb2e07..24a15e6a 100644 --- a/Interfaces/Common/intfAPIArgManipulator.cpp +++ b/Interfaces/Common/intfAPIArgManipulator.cpp @@ -25,7 +25,7 @@ namespace Targoman::API::Common { -intfAPIObject::~intfAPIObject() {} +intfAPIObject::~intfAPIObject() { ; } intfAPIArgManipulator::intfAPIArgManipulator(const QString& _realTypeName) { Q_ASSERT_X(_realTypeName.startsWith("QSharedPointer") == false, "intfAPIArgManipulator::ctor()", "aah!! ooh!!"); @@ -39,6 +39,6 @@ intfAPIArgManipulator::intfAPIArgManipulator(const QString& _realTypeName) { this->RealTypeName[RealTypeByteArray.size()] = 0; } -intfAPIArgManipulator::~intfAPIArgManipulator() {} +intfAPIArgManipulator::~intfAPIArgManipulator() { ; } } //namespace Targoman::API::Common diff --git a/Interfaces/Common/tmplAPIArg.h b/Interfaces/Common/tmplAPIArg.h index 906dd8f7..510eb5ab 100644 --- a/Interfaces/Common/tmplAPIArg.h +++ b/Interfaces/Common/tmplAPIArg.h @@ -41,7 +41,7 @@ templatetoVariantLambda == nullptr ? QVariant::fromValue(Default) : this->toVariantLambda(Default); } - inline void cleanup (void* _argStorage) final {if(_argStorage) delete (reinterpret_cast<_itmplType*>(_argStorage));} + inline void cleanup (void* _argStorage) final {if (_argStorage) delete (reinterpret_cast<_itmplType*>(_argStorage));} inline bool hasFromVariantMethod() const final {return this->fromVariantLambda != nullptr;} inline bool hasToVariantMethod() const final {return this->toVariantLambda != nullptr;} inline bool isPrimitiveType() const final { return _itmplVarType == COMPLEXITY_Integral;} @@ -119,7 +119,7 @@ class tmplAPIArg : public intfAPIArgManipulator return this->descriptionLambda ? this->descriptionLambda(_allFields) : QString("A value of type: %1").arg(this->PrettyTypeName); } inline QString toString(const QVariant _val) const final { - if(this->hasFromVariantMethod() && this->hasToVariantMethod()) + if (this->hasFromVariantMethod() && this->hasToVariantMethod()) return this->toVariantLambda(this->fromVariantLambda(_val, {})).toString(); return QString(); } @@ -133,19 +133,19 @@ class tmplAPIArg : public intfAPIArgManipulator inline std::function fromORMValueConverter() const final {return this->fromORMValueLambda;} inline std::function toORMValueConverter() const final {return this->toORMValueLambda;} - static _itmplType fromVariant(QVariant _value, const QByteArray& _paramName = {}){ - if(tmplAPIArg<_itmplType, _itmplVarType, _itmplNullable, _isQtType>::fromVariantLambda) + static _itmplType fromVariant(QVariant _value, const QByteArray& _paramName = {}) { + if (tmplAPIArg<_itmplType, _itmplVarType, _itmplNullable, _isQtType>::fromVariantLambda) return tmplAPIArg<_itmplType, _itmplVarType, _itmplNullable, _isQtType>::fromVariantLambda(_value, _paramName); return _value.value<_itmplType>(); } - static QVariant toVariant(_itmplType _value){ - if(tmplAPIArg<_itmplType, _itmplVarType, _itmplNullable, _isQtType>::toVariantLambda) + static QVariant toVariant(_itmplType _value) { + if (tmplAPIArg<_itmplType, _itmplVarType, _itmplNullable, _isQtType>::toVariantLambda) return tmplAPIArg<_itmplType, _itmplVarType, _itmplNullable, _isQtType>::toVariantLambda(_value); return QVariant::fromValue(_value); } - static tmplAPIArg* instance(const char* _typeStr){ + static tmplAPIArg* instance(const char* _typeStr) { static tmplAPIArg* Instance = nullptr; return Q_LIKELY(Instance) ? Instance : (Instance = new tmplAPIArg(_typeStr)); } private: diff --git a/Interfaces/Common/tmplNullable.hpp b/Interfaces/Common/tmplNullable.hpp index d2554c4d..cbdafbef 100644 --- a/Interfaces/Common/tmplNullable.hpp +++ b/Interfaces/Common/tmplNullable.hpp @@ -36,11 +36,11 @@ namespace TAPI { //template //class tmplNullable : public QSharedPointer { //public: -// tmplNullable() : QSharedPointer(nullptr) {} -// tmplNullable(std::nullptr_t) : QSharedPointer(nullptr) {} +// tmplNullable() : QSharedPointer(nullptr) { ; } +// tmplNullable(std::nullptr_t) : QSharedPointer(nullptr) { ; } // tmplNullable(itmplType _val) : QSharedPointer(new itmplType) { *this = _val; } // tmplNullable(itmplType* _ptr) : QSharedPointer(new itmplType) { *this = _ptr; }; -// tmplNullable(const tmplNullable& _val) : QSharedPointer(_val) {} +// tmplNullable(const tmplNullable& _val) : QSharedPointer(_val) { ; } // tmplNullable(const QVariant& _val) : QSharedPointer(nullptr) { // if (_val.isNull() == false) // tmplNullable(_val.value()); @@ -50,12 +50,12 @@ namespace TAPI { //template //class tmplNullable : public optional { //public: -// tmplNullable() : optional() {} -// tmplNullable(std::nullopt_t) : optional() {} -// tmplNullable(std::nullptr_t) : optional() {} +// tmplNullable() : optional() { ; } +// tmplNullable(std::nullopt_t) : optional() { ; } +// tmplNullable(std::nullptr_t) : optional() { ; } // tmplNullable(itmplType _val) : optional() { *this = _val; } // tmplNullable(itmplType* _ptr) : optional() { *this = _ptr; }; -// tmplNullable(const tmplNullable& _val) : optional(_val) {} +// tmplNullable(const tmplNullable& _val) : optional(_val) { ; } // tmplNullable(const QVariant& _val) : optional() { // if (_val.isNull() == false) // tmplNullable(_val.value()); diff --git a/Interfaces/DBM/Defs.hpp b/Interfaces/DBM/Defs.hpp index 8059ab12..4ee3f8bb 100644 --- a/Interfaces/DBM/Defs.hpp +++ b/Interfaces/DBM/Defs.hpp @@ -54,7 +54,7 @@ struct stuRelation ForeignColumn(_foreignColumn), RenamingPrefix(_renamingPrefix), IsLeftJoin(_isLeftJoin) - {} + { ; } stuRelation(QString _relationName, const stuRelation& _relation) : RelationName(_relationName), @@ -63,7 +63,7 @@ struct stuRelation ForeignColumn(_relation.ForeignColumn), RenamingPrefix(_relation.RenamingPrefix), IsLeftJoin(_relation.IsLeftJoin) - {} + { ; } }; TARGOMAN_DEFINE_ENUM(enuDBIndex, @@ -81,11 +81,11 @@ struct stuDBIndex { stuDBIndex(QStringList _cols, enuDBIndex::Type _type = enuDBIndex::Key, QString _name = {}) : Type(_type), Columns(_cols), Name(_name) - {} + { ; } stuDBIndex(QString _col, enuDBIndex::Type _type = enuDBIndex::Key, QString _name = {}) : stuDBIndex(QStringList()<<_col, _type, _name) - {} + { ; } }; extern stuRelation InvalidRelation; @@ -98,12 +98,12 @@ struct stuRelatedORMField stuRelatedORMField(clsORMField _col, const stuRelation& _relation = InvalidRelation) : Col(_col), Relation(_relation) - {} + { ; } stuRelatedORMField() : Relation(InvalidRelation) - {} + { ; } - inline bool isValid(){ return this->Col.name().size();} + inline bool isValid() { return this->Col.name().size();} }; extern QString finalColName(const clsORMField& _col, const QString& _prefix = {}); diff --git a/Interfaces/DBM/QueryBuilders.cpp b/Interfaces/DBM/QueryBuilders.cpp index 40347384..fe66e4ce 100644 --- a/Interfaces/DBM/QueryBuilders.cpp +++ b/Interfaces/DBM/QueryBuilders.cpp @@ -35,13 +35,11 @@ namespace Targoman::API::DBM { stuRelation InvalidRelation("", "", ""); -QString finalColName(const clsORMField& _col, const QString& _prefix) -{ +QString finalColName(const clsORMField& _col, const QString& _prefix) { return _prefix + (_col.renameAs().isEmpty() ? _col.name() : _col.renameAs()); } -QString makeColRenamedAs(const clsORMField& _col, const QString& _prefix = {}) -{ +QString makeColRenamedAs(const clsORMField& _col, const QString& _prefix = {}) { return (_col.renameAs().isEmpty() && _prefix.isEmpty() ? "" : " AS `"+ finalColName(_col, _prefix) + "`"); }; @@ -63,8 +61,7 @@ QString makeColName( // 3:table //check names e.g. CURRENT_TIMESTAMP() - if (_col.isVirtual() == false) - { + if (_col.isVirtual() == false) { if (_tableAlias.length()) ret.append(_tableAlias + "."); else if (_relation.ReferenceTable.isEmpty() == false) @@ -73,11 +70,9 @@ QString makeColName( ret.append(_tableName + "."); } - if (_col.masterName().length()) - { + if (_col.masterName().length()) { ret.append(_col.masterName()); - if (_appendAs) - { + if (_appendAs) { ret.append(" AS `"); if (_col.renameAs().length()) ret.append(_col.renameAs()); @@ -85,9 +80,7 @@ QString makeColName( ret.append(_col.name()); ret.append("`"); } - } - else - { + } else { QString ColName = _col.name(); if (_relation.Column.size() && _relation.RenamingPrefix.size()) @@ -102,8 +95,7 @@ QString makeColName( return ret.join(""); }; -QString makeValueAsSQL(const QVariant& _value, bool _qouteIfIsString = true, clsORMField* baseCol = nullptr) -{ +QString makeValueAsSQL(const QVariant& _value, bool _qouteIfIsString = true, clsORMField* baseCol = nullptr) { if (_value.isValid() == false) return QString(""); ///TODO: ? throw ? @@ -138,8 +130,7 @@ QString makeValueAsSQL(const QVariant& _value, bool _qouteIfIsString = true, cls return v; }; -QVariant makeValueAsVariant(const QVariant& _value) -{ +QVariant makeValueAsVariant(const QVariant& _value) { if (_value.isValid() == false) return QVariant(); ///TODO: ? throw ? @@ -163,10 +154,14 @@ class DBExpressionData : public QSharedData public: DBExpressionData(const DBExpressionData& _other) : QSharedData(_other), Name(_other.Name), ExprType(_other.ExprType), Values(_other.Values) - {} + { ; } + DBExpressionData(const QString& _name, enuDBExpressionType::Type _exprType, const QStringList& _values) : Name(_name), ExprType(_exprType), Values(_values) - {} + { ; } + + virtual ~DBExpressionData() + { ; } public: QString Name; @@ -177,15 +172,15 @@ class DBExpressionData : public QSharedData /***************************************************************************************/ DBExpression::DBExpression() : Data(nullptr) -{} +{ ; } DBExpression::DBExpression(const DBExpression& _other) : Data(_other.Data) -{} +{ ; } DBExpression::DBExpression(const QString& _name, enuDBExpressionType::Type _exprType, const QStringList& _values) : Data(new DBExpressionData(_name, _exprType, _values)) -{} +{ ; } DBExpression::~DBExpression() -{} +{ ; } DBExpression::operator QVariant() const { return QVariant::fromValue(*this); @@ -289,7 +284,7 @@ DBExpression DBExpression::DATE_SUB(const DBExpression& _date, const QVariant _i class clsColSpecsData : public QSharedData { public: - clsColSpecsData() : QSharedData() {} + clsColSpecsData() : QSharedData() { ; } clsColSpecsData(const clsColSpecsData &_other) : QSharedData(_other), @@ -301,7 +296,10 @@ class clsColSpecsData : public QSharedData TrueValue(_other.TrueValue), FalseValue(_other.FalseValue), Expression(_other.Expression) - {} + { ; } + + virtual ~clsColSpecsData() + { ; } public: QString Name; @@ -321,15 +319,14 @@ class clsColSpecsData : public QSharedData }; /***************************************************************************************/ -clsColSpecs::clsColSpecs() : Data(new clsColSpecsData) {} -clsColSpecs::clsColSpecs(const clsColSpecs& _other) : Data(_other.Data) {} -clsColSpecs::~clsColSpecs() {} +clsColSpecs::clsColSpecs() : Data(new clsColSpecsData) { ; } +clsColSpecs::clsColSpecs(const clsColSpecs& _other) : Data(_other.Data) { ; } +clsColSpecs::~clsColSpecs() { ; } clsColSpecs::clsColSpecs( const QString& _name, const QString& _renameAs - ) : Data(new clsColSpecsData) -{ + ) : Data(new clsColSpecsData) { this->Data->Name = _name; this->Data->RenameAs = _renameAs; } @@ -337,8 +334,7 @@ clsColSpecs::clsColSpecs( clsColSpecs::clsColSpecs( const DBExpression& _expression, const QString& _renameAs - ) : Data(new clsColSpecsData) -{ + ) : Data(new clsColSpecsData) { this->Data->RenameAs = _renameAs; this->Data->Expression = _expression; } @@ -347,8 +343,7 @@ clsColSpecs::clsColSpecs( const enuAggregation::Type _aggregation_Simple, const QString& _name, const QString& _renameAs - ) : Data(new clsColSpecsData) -{ + ) : Data(new clsColSpecsData) { this->Data->Name = _name; this->Data->RenameAs = _renameAs; this->Data->SimpleAggregation = _aggregation_Simple; @@ -360,8 +355,7 @@ clsColSpecs::clsColSpecs( const QString& _renameAs, const QVariant& _trueValue, const QVariant& _falseValue - ) : Data(new clsColSpecsData) -{ + ) : Data(new clsColSpecsData) { this->Data->RenameAs = _renameAs; this->Data->ConditionalAggregation = _ConditionalAggregation; this->Data->Condition = _condition; @@ -387,8 +381,7 @@ QString clsColSpecs::buildColNameString( /*OUT*/ bool *_isStatusColumn ) { - auto applyRenameAs = [this, &_appendAs](QString _fieldString) - { + auto applyRenameAs = [this, &_appendAs](QString _fieldString) { if ((_appendAs == false) || this->Data->RenameAs.isEmpty()) return _fieldString; @@ -399,16 +392,14 @@ QString clsColSpecs::buildColNameString( }; //Expression - if (this->Data->Expression.isValid()) - { + if (this->Data->Expression.isValid()) { // DBExpression exp = this->Data->Expression.value(); // return applyRenameAs(exp.name()); return applyRenameAs(this->Data->Expression.name()); } //ConditionalAggregation - if (NULLABLE_HAS_VALUE(this->Data->ConditionalAggregation)) - { + if (NULLABLE_HAS_VALUE(this->Data->ConditionalAggregation)) { if (this->Data->Condition.isEmpty()) throw exQueryBuilder("Condition is not provided for conditional aggregation"); @@ -421,8 +412,7 @@ QString clsColSpecs::buildColNameString( if (this->Data->ConditionalAggregation != enuConditionalAggregation::IF) AggFunction.chop(2); AggFunction += "("; - if (this->Data->TrueValue.isValid()) - { + if (this->Data->TrueValue.isValid()) { if (this->Data->ConditionalAggregation != enuConditionalAggregation::IF) AggFunction += "IF ("; } @@ -439,8 +429,7 @@ QString clsColSpecs::buildColNameString( _renamedColumns, _isStatusColumn)); - if (this->Data->TrueValue.isValid()) - { + if (this->Data->TrueValue.isValid()) { if (SQLPrettyLen && this->Data->Condition.hasMany()) parts.append("\n" + QString(SQLPrettyLen, ' ') + " "); parts.append(","); @@ -449,8 +438,7 @@ QString clsColSpecs::buildColNameString( parts.append(makeValueAsSQL(this->Data->FalseValue)); } - if (this->Data->TrueValue.isValid() != false) - { + if (this->Data->TrueValue.isValid() != false) { if (this->Data->ConditionalAggregation != enuConditionalAggregation::IF) parts.append(")"); } @@ -468,13 +456,11 @@ QString clsColSpecs::buildColNameString( QString AggFunction; - if (NULLABLE_IS_NULL(this->Data->SimpleAggregation)) - { + if (NULLABLE_IS_NULL(this->Data->SimpleAggregation)) { ///TODO: why using ANY_VALUE? // if (this->Data->GroupByCols.size()) // AggFunction = "ANY_VALUE("; - } - else if (*this->Data->SimpleAggregation == enuAggregation::DISTINCT_COUNT) + } else if (*this->Data->SimpleAggregation == enuAggregation::DISTINCT_COUNT) AggFunction = "COUNT(DISTINCT "; else AggFunction = enuAggregation::toStr(*this->Data->SimpleAggregation) @@ -483,8 +469,7 @@ QString clsColSpecs::buildColNameString( QString ColumnPrefix = (_otherTableAlias.length() ? _otherTableAlias : _tableAlias); QString NameToSearch = this->Data->Name; - if (this->Data->Name.indexOf('.') >= 0) - { + if (this->Data->Name.indexOf('.') >= 0) { ColumnPrefix = this->Data->Name.split('.').first(); if (_allowUseColumnAlias && _renamedColumns.contains(ColumnPrefix)) @@ -493,12 +478,10 @@ QString clsColSpecs::buildColNameString( QString ColFinalName; const stuRelatedORMField& relatedORMField = _selectableColsMap[NameToSearch]; - if (relatedORMField.Col.name().isNull()) - { + if (relatedORMField.Col.name().isNull()) { if (_allowUseColumnAlias && _renamedColumns.contains(this->Data->Name)) ColFinalName = this->Data->Name; - else - { + else { // qDebug() << "tableName" << _tableName; // qDebug() << "otherTableAlias" << _otherTableAlias; // qDebug() << "NameToSearch" << NameToSearch; @@ -510,9 +493,7 @@ QString clsColSpecs::buildColNameString( throw exQueryBuilder("Invalid column for filtering: " + this->Data->Name); // return false; } - } - else - { + } else { if (_isStatusColumn && (relatedORMField.Col.updatableBy() == enuUpdatableBy::__STATUS__)) *_isStatusColumn = true; @@ -576,14 +557,13 @@ struct stuConditionData bool _isAggregator, QString _col) : IsAggregator(true), - ColSpecs(_col, {}) - { + ColSpecs(_col, {}) { Q_UNUSED(_isAggregator); } stuConditionData(const clsCondition& _condition) : Condition(_condition), IsAggregator(false) - {} + { ; } stuConditionData( QString _tableNameOrAlias, @@ -595,7 +575,7 @@ struct stuConditionData ColSpecs(_colSpecs), Operator(_operator), Value(_value) - {} + { ; } stuConditionData( QString _tableNameOrAlias, @@ -609,7 +589,7 @@ struct stuConditionData Operator(_operator), OtherTableNameOrAlias(_otherTableNameOrAlias), OtherColSpecs(_otherColSpecs) - {} + { ; } /* stuConditionData( @@ -619,8 +599,7 @@ struct stuConditionData IsAggregator(false), ColSpecs(_col), Operator(_operator), - Value(_value) - {} + Value(_value) { ; } stuConditionData( const clsColSpecs& _colSpecs, enuConditionOperator::Type _operator, @@ -628,8 +607,7 @@ struct stuConditionData IsAggregator(false), ColSpecs(_colSpecs), Operator(_operator), - Value(_value) - {} + Value(_value) { ; } stuConditionData( QString _tableNameOrAlias, @@ -640,8 +618,7 @@ struct stuConditionData TableNameOrAlias(_tableNameOrAlias), ColSpecs(_col), Operator(_operator), - Value(_value) - {} + Value(_value) { ; } stuConditionData( QString _tableNameOrAlias, const clsColSpecs& _colSpecs, @@ -651,8 +628,7 @@ struct stuConditionData TableNameOrAlias(_tableNameOrAlias), ColSpecs(_colSpecs), Operator(_operator), - Value(_value) - {} + Value(_value) { ; } @@ -665,8 +641,7 @@ struct stuConditionData TableNameOrAlias(_tableNameOrAlias), ColSpecs(_col), Operator(_operator), - OtherColSpecs(_otherColSpecs) - {} + OtherColSpecs(_otherColSpecs) { ; } stuConditionData( QString _tableNameOrAlias, const clsColSpecs& _colSpecs, @@ -676,8 +651,7 @@ struct stuConditionData TableNameOrAlias(_tableNameOrAlias), ColSpecs(_colSpecs), Operator(_operator), - OtherColSpecs(_otherColSpecs) - {} + OtherColSpecs(_otherColSpecs) { ; } stuConditionData( QString _col, @@ -686,8 +660,7 @@ struct stuConditionData IsAggregator(false), ColSpecs(_col), Operator(_operator), - OtherColSpecs(_otherColSpecs) - {} + OtherColSpecs(_otherColSpecs) { ; } stuConditionData( const clsColSpecs& _colSpecs, enuConditionOperator::Type _operator, @@ -695,8 +668,7 @@ struct stuConditionData IsAggregator(false), ColSpecs(_colSpecs), Operator(_operator), - OtherColSpecs(_otherColSpecs) - {} + OtherColSpecs(_otherColSpecs) { ; } stuConditionData( @@ -710,8 +682,7 @@ struct stuConditionData ColSpecs(_col), Operator(_operator), OtherTableNameOrAlias(_otherTableNameOrAlias), - OtherColSpecs(_otherCol) - {} + OtherColSpecs(_otherCol) { ; } stuConditionData( QString _tableNameOrAlias, const clsColSpecs& _colSpecs, @@ -723,8 +694,7 @@ struct stuConditionData ColSpecs(_colSpecs), Operator(_operator), OtherTableNameOrAlias(_otherTableNameOrAlias), - OtherColSpecs(_otherCol) - {} + OtherColSpecs(_otherCol) { ; } stuConditionData( QString _tableNameOrAlias, @@ -737,8 +707,7 @@ struct stuConditionData ColSpecs(_col), Operator(_operator), OtherTableNameOrAlias(_otherTableNameOrAlias), - OtherColSpecs(_otherColSpecs) - {} + OtherColSpecs(_otherColSpecs) { ; } stuConditionData( QString _tableNameOrAlias, const clsColSpecs& _colSpecs, @@ -750,8 +719,7 @@ struct stuConditionData ColSpecs(_colSpecs), Operator(_operator), OtherTableNameOrAlias(_otherTableNameOrAlias), - OtherColSpecs(_otherColSpecs) - {} + OtherColSpecs(_otherColSpecs) { ; } */ bool isAggregator() const { return this->IsAggregator; } //Col.startsWith(" "); } @@ -764,10 +732,10 @@ class clsConditionData : public QSharedData //public: // clsConditionData(QString _col, enuConditionOperator::Type _operator = enuConditionOperator::Null, QVariant _value = {}) : // IsAggregator(false), Col(_col), Operator(_operator), Value(_value) -// {} +// { ; } // clsConditionData(QString _tableAlias, QString _col, enuConditionOperator::Type _operator = enuConditionOperator::Null, QVariant _value = {}) : // IsAggregator(false), TableAlias(_tableAlias), Col(_col), Operator(_operator), Value(_value) -// {} +// { ; } // bool isAggregator() const { return this->IsAggregator; } //Col.startsWith(" "); } // bool isOpenPar() const { return this->Col == "("; } // bool isClosePar() const { return this->Col == ")"; } @@ -785,9 +753,9 @@ class clsConditionData : public QSharedData /***************************************************************************************/ /* clsCondition ************************************************************************/ /***************************************************************************************/ -clsCondition::clsCondition() : Data(new clsConditionData) {} -clsCondition::clsCondition(const clsCondition& _other) : Data(_other.Data) {} -clsCondition::~clsCondition() {} +clsCondition::clsCondition() : Data(new clsConditionData) { ; } +clsCondition::clsCondition(const clsCondition& _other) : Data(_other.Data) { ; } +clsCondition::~clsCondition() { ; } clsCondition::clsCondition(QString _col, enuConditionOperator::Type _operator, QVariant _value) : Data(new clsConditionData) { this->Data->Conditions.append({ "", { _col, {} }, _operator, _value }); } //clsCondition::clsCondition(QString _col, enuConditionOperator::Type _operator, QString _value) : Data(new clsConditionData) { this->Data->Conditions.append({ "", { _col, {} }, _operator, _value }); } @@ -900,7 +868,8 @@ QString clsCondition::buildConditionString( const QString& _tableNameOrAlias, clsColSpecs& _colSpecs, bool *_statusColHasCriteria - ) { + ) +{ // if (_tableNameOrAlias.length() && (_tableNameOrAlias != _mainTableNameOrAlias)) // return QString("%1.%2") // .arg(_tableNameOrAlias) @@ -952,12 +921,10 @@ QString clsCondition::buildConditionString( for (QList::const_iterator iter = this->Data->Conditions.begin(); iter != this->Data->Conditions.end(); - ++iter) - { + ++iter) { stuConditionData conditionData = *iter; - if (conditionData.isAggregator()) - { + if (conditionData.isAggregator()) { if (iter == this->Data->Conditions.end()-1) throw exQueryBuilder(QString("aggregator '%1' must follow a valid condition").arg(conditionData.ColSpecs.Data->Name)); @@ -967,11 +934,8 @@ QString clsCondition::buildConditionString( CondStr += " " + conditionData.ColSpecs.Data->Name; CondStr += " "; - } - else if (conditionData.Condition.isEmpty() == false) - { - if (conditionData.Condition.hasMany()) - { + } else if (conditionData.Condition.isEmpty() == false) { + if (conditionData.Condition.hasMany()) { CondStr += "("; if (SQLPrettyLen) CondStr += "\n" + QString(SQLPrettyLen, ' ') + " "; @@ -986,15 +950,12 @@ QString clsCondition::buildConditionString( _renamedColumns, _statusColHasCriteria); - if (conditionData.Condition.hasMany()) - { + if (conditionData.Condition.hasMany()) { if (SQLPrettyLen) CondStr += "\n" + QString(SQLPrettyLen, ' ') + " "; CondStr += ")"; } - } - else - { + } else { CondStr += makeColNameHelper( conditionData.TableNameOrAlias, conditionData.ColSpecs, @@ -1004,8 +965,7 @@ QString clsCondition::buildConditionString( CondStr += " IS NULL"; else if (conditionData.Operator == enuConditionOperator::NotNull) CondStr += " IS NOT NULL"; - else if (conditionData.Operator == enuConditionOperator::Like) - { + else if (conditionData.Operator == enuConditionOperator::Like) { if (conditionData.Value.isValid() == false) throw exQueryBuilder("Value of LIKE condition is empty"); @@ -1016,9 +976,7 @@ QString clsCondition::buildConditionString( LikeVal = "%" + LikeVal + "%"; CondStr += LikeVal; CondStr += "'"; - } - else if (conditionData.Operator == enuConditionOperator::In) - { + } else if (conditionData.Operator == enuConditionOperator::In) { if (conditionData.Value.isValid() == false) throw exQueryBuilder("Value of IN condition is empty"); @@ -1026,9 +984,7 @@ QString clsCondition::buildConditionString( //makeValueAsSQL( CondStr += conditionData.Value.value(); CondStr += ")"; - } - else if (conditionData.Operator == enuConditionOperator::NotIn) - { + } else if (conditionData.Operator == enuConditionOperator::NotIn) { if (conditionData.Value.isValid() == false) throw exQueryBuilder("Value of IN condition is empty"); @@ -1036,9 +992,7 @@ QString clsCondition::buildConditionString( //makeValueAsSQL( CondStr += conditionData.Value.value(); CondStr += ")"; - } - else - { + } else { if (SQLPrettyLen) CondStr += " "; @@ -1068,8 +1022,7 @@ QString clsCondition::buildConditionString( if (SQLPrettyLen) CondStr += " "; - if (conditionData.Value.isValid()) - { + if (conditionData.Value.isValid()) { stuRelatedORMField relatedORMField; if (conditionData.ColSpecs.Data->Name.isEmpty() == false) relatedORMField = _filterableColsMap.value(conditionData.ColSpecs.Data->Name); @@ -1084,9 +1037,7 @@ QString clsCondition::buildConditionString( conditionData.Value, true, relatedORMField.isValid() ? &relatedORMField.Col : nullptr); - } - else - { + } else { CondStr += makeColNameHelper( conditionData.OtherTableNameOrAlias, conditionData.OtherColSpecs, @@ -1112,28 +1063,28 @@ struct stuJoin { stuJoin(const enuJoinType::Type& _joinType, const QString& _foreignTable) : JoinType(_joinType), ForeignTable(_foreignTable) - {} + { ; } stuJoin(const enuJoinType::Type& _joinType, const QString& _foreignTable, const QString& _alias) : JoinType(_joinType), ForeignTable(_foreignTable), Alias(_alias) - {} + { ; } stuJoin(const enuJoinType::Type& _joinType, const QString& _foreignTable, const clsCondition& _on) : JoinType(_joinType), ForeignTable(_foreignTable), On(_on) - {} + { ; } stuJoin(const enuJoinType::Type& _joinType, const QString& _foreignTable, const QString& _alias, const clsCondition& _on) : JoinType(_joinType), ForeignTable(_foreignTable), Alias(_alias), On(_on) - {} + { ; } }; struct stuOrderBy { QString Col; enuOrderDir::Type Dir; -// stuOrderBy() {} - stuOrderBy(const stuOrderBy& _other) : Col(_other.Col), Dir(_other.Dir) {} - stuOrderBy(const QString& _col, const enuOrderDir::Type& _dir) : Col(_col), Dir(_dir) {} +// stuOrderBy() { ; } + stuOrderBy(const stuOrderBy& _other) : Col(_other.Col), Dir(_other.Dir) { ; } + stuOrderBy(const QString& _col, const enuOrderDir::Type& _dir) : Col(_col), Dir(_dir) { ; } }; TARGOMAN_DEFINE_ENUM(enuUnionType, @@ -1145,8 +1096,8 @@ struct stuUnion { SelectQuery Query; enuUnionType::Type UnionType; - stuUnion(const stuUnion& _other) : Query(_other.Query), UnionType(_other.UnionType) {} - stuUnion(const SelectQuery& _query, enuUnionType::Type _unionType) : Query(_query), UnionType(_unionType) {} + stuUnion(const stuUnion& _other) : Query(_other.Query), UnionType(_other.UnionType) { ; } + stuUnion(const SelectQuery& _query, enuUnionType::Type _unionType) : Query(_query), UnionType(_unionType) { ; } }; /***************************************************************************************/ @@ -1164,7 +1115,10 @@ class clsBaseQueryData : public QSharedData public: clsBaseQueryData(clsTable& _table, const QString& _alias = {}) : Table(_table), Alias(_alias) - {} + { ; } + + virtual ~clsBaseQueryData() + { ; } virtual void prepare(quint64 _currentUserID, bool _useBinding) { Q_UNUSED(_currentUserID) @@ -1199,12 +1153,12 @@ class clsBaseQueryData : public QSharedData template tmplBaseQuery::tmplBaseQuery() : Data(nullptr) -{} +{ ; } template tmplBaseQuery::tmplBaseQuery(const tmplBaseQuery& _other) : Data(_other.Data) -{} +{ ; } template tmplBaseQuery::tmplBaseQuery(clsTable& _table, const QString& _alias) : @@ -1231,13 +1185,11 @@ bool tmplBaseQuery::isValid() { //} template -const QStringList& tmplBaseQuery::getRenamedCols() -{ +const QStringList& tmplBaseQuery::getRenamedCols() { return this->Data->BaseQueryPreparedItems.RenamedCols; } template -void tmplBaseQuery::addRenamedCols(const QStringList& _cols, const QString& _alias) -{ +void tmplBaseQuery::addRenamedCols(const QStringList& _cols, const QString& _alias) { if (_cols.isEmpty()) return; @@ -1262,7 +1214,10 @@ class clsQueryJoinTraitData : public QSharedData public: clsQueryJoinTraitData(itmplDerived* _owner) : Owner(_owner), IsPrepared(false) - {} + { ; } + + virtual ~clsQueryJoinTraitData() + { ; } virtual void prepare() { if (this->IsPrepared) @@ -1298,14 +1253,11 @@ class clsQueryJoinTraitData : public QSharedData } //1: check duplication - if (Join.Alias.length()) - { + if (Join.Alias.length()) { if (AppliedJoins.contains(Join.Alias)) throw exHTTPInternalServerError(QString("Duplicated join on table (%1) alias (%2).").arg(Join.ForeignTable).arg(Join.Alias)); AppliedJoins.insert(Join.Alias); - } - else - { + } else { if (AppliedJoins.contains(Join.ForeignTable)) throw exHTTPInternalServerError(QString("Duplicated join on table (%1).").arg(Join.ForeignTable)); AppliedJoins.insert(Join.ForeignTable); @@ -1315,9 +1267,7 @@ class clsQueryJoinTraitData : public QSharedData if (Join.ForeignTable.startsWith("(")) //nested join { ReferenceTable = Join.ForeignTable; - } - else - { + } else { //2: find relation definition // stuRelation* Relation = nullptr; // foreach (stuRelation Rel, this->Owner->Data->Table.Relations) @@ -1351,8 +1301,7 @@ class clsQueryJoinTraitData : public QSharedData j += ReferenceTable; if (Join.Alias.size()) j += " " + Join.Alias; - if (Join.JoinType != enuJoinType::CROSS) - { + if (Join.JoinType != enuJoinType::CROSS) { if (Join.On.isEmpty()) throw exHTTPInternalServerError("Condition part of relation not defined."); @@ -1406,30 +1355,30 @@ class clsQueryJoinTraitData : public QSharedData /***************************************************************************************/ template tmplQueryJoinTrait::tmplQueryJoinTrait(const tmplQueryJoinTrait& _other) : - JoinTraitData(_other.JoinTraitData) {} + JoinTraitData(_other.JoinTraitData) +{ ; } template tmplQueryJoinTrait::tmplQueryJoinTrait(itmplDerived* _owner) : - JoinTraitData(new clsQueryJoinTraitData(_owner)) { -} + JoinTraitData(new clsQueryJoinTraitData(_owner)) +{ ; } template -tmplQueryJoinTrait::~tmplQueryJoinTrait() {} +tmplQueryJoinTrait::~tmplQueryJoinTrait() +{ ; } /***********************\ |* Join *| \***********************/ template -itmplDerived& tmplQueryJoinTrait::join(enuJoinType::Type _joinType, QString _foreignTable, const QString& _alias, const clsCondition& _on) -{ +itmplDerived& tmplQueryJoinTrait::join(enuJoinType::Type _joinType, QString _foreignTable, const QString& _alias, const clsCondition& _on) { if (_foreignTable.isEmpty()) throw exHTTPInternalServerError("Foreign Table is empty."); if (_foreignTable.indexOf('.') < 0) _foreignTable = QString("%1.%2").arg(this->JoinTraitData->Owner->Data->Table.Schema).arg(_foreignTable); - if ((_joinType == enuJoinType::CROSS) || (_on.isEmpty() == false)) - { + if ((_joinType == enuJoinType::CROSS) || (_on.isEmpty() == false)) { //prefix table name with schema _foreignTable = PrependSchema(_foreignTable); @@ -1455,14 +1404,12 @@ itmplDerived& tmplQueryJoinTrait::join(enuJoinType::Type _joinType //find relation definition bool RelationFound = false; stuRelation Relation("", "", ""); - foreach (stuRelation Rel, this->JoinTraitData->Owner->Data->Table.Relations) - { + foreach (stuRelation Rel, this->JoinTraitData->Owner->Data->Table.Relations) { // parts = Rel.ReferenceTable.split('.', QString::SkipEmptyParts); // if (parts[parts.length() - 1] == ForeignTable_Name) // qDebug() << "&&&&&&& search relation" << Rel.ReferenceTable << _foreignTable; - if (Rel.ReferenceTable == _foreignTable) - { + if (Rel.ReferenceTable == _foreignTable) { if (RelationFound) throw exHTTPInternalServerError(QString("Multiple relations defined to table (%1).").arg(_foreignTable)); @@ -1508,8 +1455,7 @@ template itmplDerived& tmplQueryJoinTrait::in template itmplDerived& tmplQueryJoinTrait::crossJoin(const QString& _foreignTable, const QString& _alias) { return this->join(enuJoinType::CROSS, _foreignTable, _alias); } //-- nested ------------------------- -template itmplDerived& tmplQueryJoinTrait::join(enuJoinType::Type _joinType, SelectQuery& _nestedQuery, const QString _alias, const clsCondition& _on) -{ +template itmplDerived& tmplQueryJoinTrait::join(enuJoinType::Type _joinType, SelectQuery& _nestedQuery, const QString _alias, const clsCondition& _on) { if (_alias.length()) this->JoinTraitData->Owner->Data->BaseQueryPreparedItems.RenamedCols.append(_alias); @@ -1539,8 +1485,7 @@ template itmplDerived& tmplQueryJoinTrait::cr //-- with ------------------------- template -itmplDerived& tmplQueryJoinTrait::joinWith(enuJoinType::Type _joinType, const QString& _relationName, const QString& _alias) -{ +itmplDerived& tmplQueryJoinTrait::joinWith(enuJoinType::Type _joinType, const QString& _relationName, const QString& _alias) { if (_relationName.isEmpty()) throw exHTTPInternalServerError("Relation Name is empty."); @@ -1605,7 +1550,10 @@ class clsQueryWhereTraitData : public QSharedData public: clsQueryWhereTraitData(itmplDerived* _owner) : Owner(_owner), IsPrepared(false) - {} + { ; } + + virtual ~clsQueryWhereTraitData() + { ; } virtual void prepare(bool _checkStatusCol=false) { if (this->IsPrepared) @@ -1652,8 +1600,7 @@ class clsQueryWhereTraitData : public QSharedData CanStartWithLogical = false; LastLogical.clear(); OpenParenthesis++; - } - else if (Filter == ")") { + } else if (Filter == ")") { if (OpenParenthesis <= 0) throw exHTTPBadRequest("Invalid close parenthesis without any open"); if (SQLPrettyLen) Rule += "\n" + QString(SQLPrettyLen, ' ') + " "; @@ -1662,22 +1609,22 @@ class clsQueryWhereTraitData : public QSharedData // Rule += "\n"; OpenParenthesis--; CanStartWithLogical = true; - } - else if (Filter == '+' || Filter == '|' || Filter == '*') { + } else if (Filter == '+' || Filter == '|' || Filter == '*') { if (CanStartWithLogical == false) throw exHTTPBadRequest("Invalid logical expression prior to any rule"); + if (Filter == '+') LastLogical = "AND"; else if (Filter == '|') LastLogical = "OR"; else if (Filter == '*') LastLogical = "XOR"; if (SQLPrettyLen) LastLogical = "\n" + LastLogical.rightJustified(SQLPrettyLen); + LastLogical += " "; CanStartWithLogical = false; continue; - } - else { + } else { static QRegularExpression rxFilterPattern("([a-zA-Z0-9\\_]+)([<>!=~]=?)(.+)"); Filter = Filter.replace("$SPACE$", " "); QRegularExpressionMatch PatternMatches = rxFilterPattern.match(Filter); @@ -1758,17 +1705,14 @@ class clsQueryWhereTraitData : public QSharedData } /****************************************************************************/ - if (this->PksByPath.size()) - { + if (this->PksByPath.size()) { QStringList PkFilters; QStringList Pks = this->PksByPath.split(QRegularExpression("(;|,)")); foreach (auto PkValue, Pks) { foreach (stuRelatedORMField baseCol, this->Owner->Data->Table.AllCols) { - if ((baseCol.Relation == InvalidRelation) && baseCol.Col.isPrimaryKey()) - { - if (PkValue.size()) - { + if ((baseCol.Relation == InvalidRelation) && baseCol.Col.isPrimaryKey()) { + if (PkValue.size()) { QString ColName = makeColName( this->Owner->Data->Table.Name, this->Owner->Data->Alias, @@ -1796,10 +1740,8 @@ class clsQueryWhereTraitData : public QSharedData /****************************************************************************/ //only check for stand alone select query QStringList w; - foreach (stuRelatedORMField baseCol, this->Owner->Data->Table.AllCols) - { - if (baseCol.Relation == InvalidRelation) - { + foreach (stuRelatedORMField baseCol, this->Owner->Data->Table.AllCols) { + if (baseCol.Relation == InvalidRelation) { if (_checkStatusCol && (StatusColHasCriteria == false) && baseCol.Col.updatableBy() == enuUpdatableBy::__STATUS__) w.append(QString("%1 != 'R'").arg(makeColName(this->Owner->Data->Table.Name, this->Owner->Data->Alias, baseCol.Col, false))); @@ -1808,10 +1750,8 @@ class clsQueryWhereTraitData : public QSharedData } } - if (w.length()) - { - if (this->PreparedItems.Where.length()) - { + if (w.length()) { + if (this->PreparedItems.Where.length()) { if (SQLPrettyLen) w.append(QString("(\n%1 %2\n%1 )").arg(QString(SQLPrettyLen, ' ')).arg(this->PreparedItems.Where)); else @@ -1845,22 +1785,23 @@ class clsQueryWhereTraitData : public QSharedData /***************************************************************************************/ template tmplQueryWhereTrait::tmplQueryWhereTrait(const tmplQueryWhereTrait& _other) : - WhereTraitData(_other.WhereTraitData) {} + WhereTraitData(_other.WhereTraitData) +{ ; } template tmplQueryWhereTrait::tmplQueryWhereTrait(itmplDerived* _owner) : - WhereTraitData(new clsQueryWhereTraitData(_owner)) { -} + WhereTraitData(new clsQueryWhereTraitData(_owner)) +{ ; } template -tmplQueryWhereTrait::~tmplQueryWhereTrait() {} +tmplQueryWhereTrait::~tmplQueryWhereTrait() +{ ; } /***********************\ |* Where *| \***********************/ template -itmplDerived& tmplQueryWhereTrait::where(const clsCondition& _condition) -{ +itmplDerived& tmplQueryWhereTrait::where(const clsCondition& _condition) { if (_condition.isEmpty() == false) this->WhereTraitData->WhereClauses = _condition; @@ -1868,8 +1809,7 @@ itmplDerived& tmplQueryWhereTrait::where(const clsCondition& _cond } template -itmplDerived& tmplQueryWhereTrait::andWhere(const clsCondition& _condition) -{ +itmplDerived& tmplQueryWhereTrait::andWhere(const clsCondition& _condition) { if (_condition.isEmpty() == false) { if (this->WhereTraitData->WhereClauses.isEmpty()) this->WhereTraitData->WhereClauses = _condition; @@ -1881,8 +1821,7 @@ itmplDerived& tmplQueryWhereTrait::andWhere(const clsCondition& _c } template -itmplDerived& tmplQueryWhereTrait::orWhere(const clsCondition& _condition) -{ +itmplDerived& tmplQueryWhereTrait::orWhere(const clsCondition& _condition) { if (_condition.isEmpty() == false) { if (this->WhereTraitData->WhereClauses.isEmpty()) this->WhereTraitData->WhereClauses = _condition; @@ -1894,8 +1833,7 @@ itmplDerived& tmplQueryWhereTrait::orWhere(const clsCondition& _co } template -itmplDerived& tmplQueryWhereTrait::xorWhere(const clsCondition& _condition) -{ +itmplDerived& tmplQueryWhereTrait::xorWhere(const clsCondition& _condition) { if (_condition.isEmpty() == false) { if (this->WhereTraitData->WhereClauses.isEmpty()) this->WhereTraitData->WhereClauses = _condition; @@ -1910,24 +1848,21 @@ itmplDerived& tmplQueryWhereTrait::xorWhere(const clsCondition& _c |* PKsByPath *| \***********************/ template -itmplDerived& tmplQueryWhereTrait::setPksByPath(quint32 _pksByPath) -{ +itmplDerived& tmplQueryWhereTrait::setPksByPath(quint32 _pksByPath) { this->WhereTraitData->PksByPath = QString("%1").arg(_pksByPath); return (itmplDerived&)*this; } template -itmplDerived& tmplQueryWhereTrait::setPksByPath(quint64 _pksByPath) -{ +itmplDerived& tmplQueryWhereTrait::setPksByPath(quint64 _pksByPath) { this->WhereTraitData->PksByPath = QString("%1").arg(_pksByPath); return (itmplDerived&)*this; } template -itmplDerived& tmplQueryWhereTrait::setPksByPath(TAPI::PKsByPath_t _pksByPath) -{ +itmplDerived& tmplQueryWhereTrait::setPksByPath(TAPI::PKsByPath_t _pksByPath) { this->WhereTraitData->PksByPath = _pksByPath.trimmed(); return (itmplDerived&)*this; @@ -1937,8 +1872,7 @@ itmplDerived& tmplQueryWhereTrait::setPksByPath(TAPI::PKsByPath_t |* Filters *| \***********************/ template -itmplDerived& tmplQueryWhereTrait::addFilters(const QString& _filters) -{ +itmplDerived& tmplQueryWhereTrait::addFilters(const QString& _filters) { QString Filters = _filters.trimmed(); if (Filters.isEmpty() == false) { @@ -1954,8 +1888,7 @@ itmplDerived& tmplQueryWhereTrait::addFilters(const QString& _filt return (itmplDerived&)*this; } template -itmplDerived& tmplQueryWhereTrait::addFilters(const QStringList& _filters) -{ +itmplDerived& tmplQueryWhereTrait::addFilters(const QStringList& _filters) { this->WhereTraitData->Filters.append(_filters); return (itmplDerived&)*this; @@ -1975,7 +1908,10 @@ class clsQueryGroupAndHavingTraitData : public QSharedData public: clsQueryGroupAndHavingTraitData(itmplDerived* _owner) : Owner(_owner), IsPrepared(false) - {} + { ; } + + virtual ~clsQueryGroupAndHavingTraitData() + { ; } virtual void prepare() { if (this->IsPrepared) @@ -2015,23 +1951,24 @@ class clsQueryGroupAndHavingTraitData : public QSharedData /***************************************************************************************/ template tmplQueryGroupAndHavingTrait::tmplQueryGroupAndHavingTrait(const tmplQueryGroupAndHavingTrait& _other) : - GroupAndHavingTraitData(_other.GroupAndHavingTraitData) {} + GroupAndHavingTraitData(_other.GroupAndHavingTraitData) +{ ; } template tmplQueryGroupAndHavingTrait::tmplQueryGroupAndHavingTrait(itmplDerived* _owner) : - GroupAndHavingTraitData(new clsQueryGroupAndHavingTraitData(_owner)) { -} + GroupAndHavingTraitData(new clsQueryGroupAndHavingTraitData(_owner)) +{ ; } template -tmplQueryGroupAndHavingTrait::~tmplQueryGroupAndHavingTrait() {} +tmplQueryGroupAndHavingTrait::~tmplQueryGroupAndHavingTrait() +{ ; } /***********************\ |* Group *| \***********************/ //template itmplDerived& tmplQueryGroupAndHavingTrait::groupBy(const clsCondition& _condition); template -itmplDerived& tmplQueryGroupAndHavingTrait::groupBy(const QString& _col) -{ +itmplDerived& tmplQueryGroupAndHavingTrait::groupBy(const QString& _col) { if (_col.isEmpty() == false) this->GroupAndHavingTraitData->GroupByCols.append(_col); @@ -2039,8 +1976,7 @@ itmplDerived& tmplQueryGroupAndHavingTrait::groupBy(const QString& } template -itmplDerived& tmplQueryGroupAndHavingTrait::groupBy(const QStringList& _cols) -{ +itmplDerived& tmplQueryGroupAndHavingTrait::groupBy(const QStringList& _cols) { if (_cols.length()) { foreach(auto Col, _cols) this->groupBy(Col); @@ -2053,8 +1989,7 @@ itmplDerived& tmplQueryGroupAndHavingTrait::groupBy(const QStringL |* Having *| \***********************/ template -itmplDerived& tmplQueryGroupAndHavingTrait::having(const clsCondition& _condition) -{ +itmplDerived& tmplQueryGroupAndHavingTrait::having(const clsCondition& _condition) { // if (this->GroupAndHavingTraitData->HavingClauses.isEmpty() != false) // throw exQueryBuilder("Having clauses are not empty. Please use andHaving, orHaving or xorHaving"); @@ -2063,8 +1998,7 @@ itmplDerived& tmplQueryGroupAndHavingTrait::having(const clsCondit } template -itmplDerived& tmplQueryGroupAndHavingTrait::andHaving(const clsCondition& _condition) -{ +itmplDerived& tmplQueryGroupAndHavingTrait::andHaving(const clsCondition& _condition) { if (this->GroupAndHavingTraitData->HavingClauses.isEmpty()) this->GroupAndHavingTraitData->HavingClauses = _condition; else @@ -2073,8 +2007,7 @@ itmplDerived& tmplQueryGroupAndHavingTrait::andHaving(const clsCon } template -itmplDerived& tmplQueryGroupAndHavingTrait::orHaving(const clsCondition& _condition) -{ +itmplDerived& tmplQueryGroupAndHavingTrait::orHaving(const clsCondition& _condition) { if (this->GroupAndHavingTraitData->HavingClauses.isEmpty()) this->GroupAndHavingTraitData->HavingClauses = _condition; else @@ -2083,8 +2016,7 @@ itmplDerived& tmplQueryGroupAndHavingTrait::orHaving(const clsCond } template -itmplDerived& tmplQueryGroupAndHavingTrait::xorHaving(const clsCondition& _condition) -{ +itmplDerived& tmplQueryGroupAndHavingTrait::xorHaving(const clsCondition& _condition) { if (this->GroupAndHavingTraitData->HavingClauses.isEmpty()) this->GroupAndHavingTraitData->HavingClauses = _condition; else @@ -2105,9 +2037,9 @@ struct stuSelectQueryPreparedItems { class clsSelectQueryData : public clsBaseQueryData { public: - clsSelectQueryData(clsTable& _table, const QString& _alias = {}) : clsBaseQueryData(_table, _alias) {} -// clsSelectQueryData(const clsSelectQueryData& _other) : Table(_other.Table), Alias(_other.Alias) {} -// ~clsSelectQueryData() {} + clsSelectQueryData(clsTable& _table, const QString& _alias = {}) : clsBaseQueryData(_table, _alias) { ; } +// clsSelectQueryData(const clsSelectQueryData& _other) : Table(_other.Table), Alias(_other.Alias) { ; } +// ~clsSelectQueryData() { ; } virtual void prepare(quint64 _currentUserID, bool _useBinding) { if (this->SelectQueryPreparedItems.IsPrepared) @@ -2120,8 +2052,7 @@ class clsSelectQueryData : public clsBaseQueryData QString MainTableNameOrAlias = this->Alias.length() ? this->Alias : this->Table.Name; /****************************************************************************/ - auto addCol = [this](clsColSpecs& _col, const stuRelation& _relation = InvalidRelation) - { + auto addCol = [this](clsColSpecs& _col, const stuRelation& _relation = InvalidRelation) { this->SelectQueryPreparedItems.Cols.append( _col.buildColNameString( this->Table.Name, @@ -2147,8 +2078,7 @@ class clsSelectQueryData : public clsBaseQueryData if ((baseCol.Relation == InvalidRelation) && baseCol.Col.isSelectable()) this->SelectQueryPreparedItems.Cols.append(makeColName(this->Table.Name, this->Alias, baseCol.Col, true)); } - } - else { + } else { // qDebug() << MainTableNameOrAlias << "has RequiredCols"; // int i = 0; foreach(clsColSpecs Col, this->RequiredCols) { @@ -2189,52 +2119,52 @@ class clsSelectQueryData : public clsBaseQueryData bool CanStartWithLogical = false; QString LastLogical = ""; _filters = _filters.replace("\\ ", "$SPACE$"); - foreach(auto Filter, _filters.split(" ", QString::SkipEmptyParts)){ + foreach(auto Filter, _filters.split(" ", QString::SkipEmptyParts)) { QString Rule; Filter = Filter.trimmed (); - if(Filter == ")"){ - if(OpenParenthesis <= 0) throw exHTTPBadRequest("Invalid close parenthesis without any open"); + if (Filter == ")") { + if (OpenParenthesis <= 0) throw exHTTPBadRequest("Invalid close parenthesis without any open"); Rule = " )"; OpenParenthesis--; CanStartWithLogical = true; - }else if(Filter == "("){ + } else if (Filter == "(") { Rule = LastLogical + "("; CanStartWithLogical = false; LastLogical.clear(); OpenParenthesis++; - }else if(Filter == '+' || Filter == '|' || Filter == '*'){ - if(CanStartWithLogical == false) throw exHTTPBadRequest("Invalid logical expression prior to any rule"); - if(Filter == '+') LastLogical = "AND "; - else if(Filter == '|') LastLogical = "OR "; - else if(Filter == '*') LastLogical = "XOR "; + } else if (Filter == '+' || Filter == '|' || Filter == '*') { + if (CanStartWithLogical == false) throw exHTTPBadRequest("Invalid logical expression prior to any rule"); + if (Filter == '+') LastLogical = "AND "; + else if (Filter == '|') LastLogical = "OR "; + else if (Filter == '*') LastLogical = "XOR "; CanStartWithLogical = false; continue; - }else{ + } else { static QRegularExpression rxFilterPattern("([a-zA-Z0-9\\_]+)([<>!=~]=?)(.+)"); Filter = Filter.replace("$SPACE$", " "); QRegularExpressionMatch PatternMatches = rxFilterPattern.match(Filter); - if(PatternMatches.lastCapturedIndex() != 3) + if (PatternMatches.lastCapturedIndex() != 3) throw exHTTPBadRequest("Invalid filter set: " + Filter); Rule = LastLogical; stuRelatedORMField relatedORMField = this->FilterableColsMap.value(PatternMatches.captured(1).trimmed()); - if(relatedORMField.isValid()) + if (relatedORMField.isValid()) Rule+=makeColName(this->Name, relatedORMField.Col, false, relatedORMField.Relation); else throw exHTTPBadRequest("Invalid column for filtering:::: " + PatternMatches.captured(1)); - if(relatedORMField.Col.updatableBy() == enuUpdatableBy::__STATUS__) + if (relatedORMField.Col.updatableBy() == enuUpdatableBy::__STATUS__) StatusColHasCriteria = true; - if(relatedORMField.Relation.Column.size() && UsedJoins.contains(relatedORMField.Relation) == false) + if (relatedORMField.Relation.Column.size() && UsedJoins.contains(relatedORMField.Relation) == false) UsedJoins.insert(relatedORMField.Relation); - if(PatternMatches.captured(3) == "NULL"){ - if(PatternMatches.captured(2) == "=") + if (PatternMatches.captured(3) == "NULL") { + if (PatternMatches.captured(2) == "=") Rule += " IS NULL"; - else if(PatternMatches.captured(2) == "!=") + else if (PatternMatches.captured(2) == "!=") Rule += " IS NOT NULL"; else throw exHTTPBadRequest("Invalid filter with NULL expression: " + Filter); @@ -2245,23 +2175,23 @@ class clsSelectQueryData : public clsBaseQueryData continue; } - if(PatternMatches.captured(2) == "<") Rule += " < "; - else if(PatternMatches.captured(2) == "<=") Rule += " <= "; - else if(PatternMatches.captured(2) == ">") Rule += " > "; - else if(PatternMatches.captured(2) == ">=") Rule += " >= "; - else if(PatternMatches.captured(2) == "!=") Rule += " != "; - else if(PatternMatches.captured(2) == "~=") Rule += " LIKE "; - else if(PatternMatches.captured(2) == "=") Rule += " = "; + if (PatternMatches.captured(2) == "<") Rule += " < "; + else if (PatternMatches.captured(2) == "<=") Rule += " <= "; + else if (PatternMatches.captured(2) == ">") Rule += " > "; + else if (PatternMatches.captured(2) == ">=") Rule += " >= "; + else if (PatternMatches.captured(2) == "!=") Rule += " != "; + else if (PatternMatches.captured(2) == "~=") Rule += " LIKE "; + else if (PatternMatches.captured(2) == "=") Rule += " = "; else throw exHTTPBadRequest("Invalid filter criteria: " + Filter); Rule += relatedORMField.Col.argSpecs().isPrimitiveType() ? "" : "'"; QString Value = PatternMatches.captured(3); - if(Value == "NOW()" + if (Value == "NOW()" || Value.startsWith("DATE_ADD(") || Value.startsWith("DATE_SUB(") ) Rule += Value.replace("$SPACE$", " "); - else{ + else { relatedORMField.Col.argSpecs().validate(Value, PatternMatches.captured(1).trimmed().toLatin1()); Rule += relatedORMField.Col.toDB(Value).toString(); } @@ -2273,20 +2203,20 @@ class clsSelectQueryData : public clsBaseQueryData SelectItems.Where.append(Rule); } - if(OpenParenthesis != 0) + if (OpenParenthesis != 0) throw exHTTPBadRequest("count of open and closed parenthesises does not match"); - if(SelectItems.Where.isEmpty()) + if (SelectItems.Where.isEmpty()) SelectItems.Where.append("TRUE"); - if(StatusColHasCriteria == false) + if (StatusColHasCriteria == false) foreach(auto FCol, this->FilterableColsMap) - if(FCol.Col.updatableBy() == enuUpdatableBy::__STATUS__){ - if(FCol.Relation.LeftJoin) + if (FCol.Col.updatableBy() == enuUpdatableBy::__STATUS__) { + if (FCol.Relation.LeftJoin) SelectItems.Where.append(QString("AND (ISNULL(%1) OR %1!='R')").arg(makeColName(this->Name, FCol.Col, false, FCol.Relation))); else SelectItems.Where.append(QString("AND %1!='R'").arg(makeColName(this->Name, FCol.Col, false, FCol.Relation))); - if(FCol.Relation.Column.size()) + if (FCol.Relation.Column.size()) UsedJoins.insert(FCol.Relation); } */ @@ -2352,9 +2282,7 @@ SelectQuery::SelectQuery() : tmplBaseQuery(), tmplQueryJoinTrait(this), tmplQueryWhereTrait(this), - tmplQueryGroupAndHavingTrait(this) - -{ + tmplQueryGroupAndHavingTrait(this) { tmplQueryJoinTrait::JoinTraitData->Owner = this; tmplQueryWhereTrait::WhereTraitData->Owner = this; tmplQueryGroupAndHavingTrait::GroupAndHavingTraitData->Owner = this; @@ -2363,8 +2291,7 @@ SelectQuery::SelectQuery(const SelectQuery& _other) : tmplBaseQuery(_other), tmplQueryJoinTrait(_other), tmplQueryWhereTrait(_other), - tmplQueryGroupAndHavingTrait(_other) -{ + tmplQueryGroupAndHavingTrait(_other) { tmplQueryJoinTrait::JoinTraitData->Owner = this; tmplQueryWhereTrait::WhereTraitData->Owner = this; tmplQueryGroupAndHavingTrait::GroupAndHavingTraitData->Owner = this; @@ -2374,22 +2301,20 @@ SelectQuery::SelectQuery(clsTable& _table, const QString& _alias) : tmplQueryJoinTrait(this), tmplQueryWhereTrait(this), tmplQueryGroupAndHavingTrait(this) -{} -SelectQuery::~SelectQuery() {} +{ ; } +SelectQuery::~SelectQuery() { ; } /***********************\ |* Columns *| \***********************/ -SelectQuery& SelectQuery::addCol(const clsColSpecs& _colSpecs) -{ +SelectQuery& SelectQuery::addCol(const clsColSpecs& _colSpecs) { this->Data->RequiredCols.append(_colSpecs); return *this; } //used by APPLY_GET_METHOD_CALL_ARGS_APICALL_TO_QUERY //TAPI::Cols_t -> QString -SelectQuery& SelectQuery::addCSVCols(const QString& _commaSeperatedCols, const QString& _seperator) -{ +SelectQuery& SelectQuery::addCSVCols(const QString& _commaSeperatedCols, const QString& _seperator) { QString sCols = _commaSeperatedCols.trimmed(); if (sCols.isEmpty()) @@ -2403,8 +2328,7 @@ SelectQuery& SelectQuery::addCSVCols(const QString& _commaSeperatedCols, const Q return this->addCols(cols); } -SelectQuery& SelectQuery::addCols(const QStringList& _cols) -{ +SelectQuery& SelectQuery::addCols(const QStringList& _cols) { if (_cols.length()) { foreach(QString col, _cols) { if (col.isEmpty() == false) @@ -2415,8 +2339,7 @@ SelectQuery& SelectQuery::addCols(const QStringList& _cols) return *this; } -SelectQuery& SelectQuery::addCol(const QString& _col, const QString& _renameAs) -{ +SelectQuery& SelectQuery::addCol(const QString& _col, const QString& _renameAs) { // Q_ASSERT(_col.isEmpty() == false); if (_col.isEmpty() == false) @@ -2425,15 +2348,13 @@ SelectQuery& SelectQuery::addCol(const QString& _col, const QString& _renameAs) return *this; } -SelectQuery& SelectQuery::addCol(const DBExpression& _expr, const QString& _renameAs) -{ +SelectQuery& SelectQuery::addCol(const DBExpression& _expr, const QString& _renameAs) { this->addCol({ _expr, _renameAs }); return *this; } -SelectQuery& SelectQuery::addCol(enuAggregation::Type _aggFunc, const QString& _col, const QString& _renameAs) -{ +SelectQuery& SelectQuery::addCol(enuAggregation::Type _aggFunc, const QString& _col, const QString& _renameAs) { Q_ASSERT(_col.isEmpty() == false); this->addCol({ _aggFunc, _col, _renameAs }); @@ -2441,8 +2362,7 @@ SelectQuery& SelectQuery::addCol(enuAggregation::Type _aggFunc, const QString& _ return *this; } -SelectQuery& SelectQuery::addCol(enuConditionalAggregation::Type _aggFunc, const clsCondition& _condition, const QString& _renameAs) -{ +SelectQuery& SelectQuery::addCol(enuConditionalAggregation::Type _aggFunc, const clsCondition& _condition, const QString& _renameAs) { if (_aggFunc == enuConditionalAggregation::COUNTIF) this->addCol({ _aggFunc, _condition, _renameAs, 1, DBExpression::NIL() }); else @@ -2450,8 +2370,7 @@ SelectQuery& SelectQuery::addCol(enuConditionalAggregation::Type _aggFunc, const return *this; } -SelectQuery& SelectQuery::addCol(enuConditionalAggregation::Type _aggFunc, const clsCondition& _condition, QVariant _trueValue, QVariant _falseValue, const QString& _renameAs) -{ +SelectQuery& SelectQuery::addCol(enuConditionalAggregation::Type _aggFunc, const clsCondition& _condition, QVariant _trueValue, QVariant _falseValue, const QString& _renameAs) { this->addCol({ _aggFunc, _condition, _renameAs, _trueValue, _falseValue }); return *this; @@ -2466,8 +2385,7 @@ SelectQuery& SelectQuery::addCol(enuConditionalAggregation::Type _aggFunc, const /***********************\ |* Order *| \***********************/ -SelectQuery& SelectQuery::orderBy(const QString& _col, enuOrderDir::Type _dir) -{ +SelectQuery& SelectQuery::orderBy(const QString& _col, enuOrderDir::Type _dir) { if (_col.isEmpty() == false) this->Data->OrderByCols.append({ _col, _dir }); return *this; @@ -2476,18 +2394,15 @@ SelectQuery& SelectQuery::orderBy(const QString& _col, enuOrderDir::Type _dir) /***********************\ |* Union *| \***********************/ -SelectQuery& SelectQuery::addUnion(SelectQuery& _query) -{ +SelectQuery& SelectQuery::addUnion(SelectQuery& _query) { this->Data->UnionParts.append({ _query, enuUnionType::Normal }); return *this; } -SelectQuery& SelectQuery::addUnionAll(SelectQuery& _query) -{ +SelectQuery& SelectQuery::addUnionAll(SelectQuery& _query) { this->Data->UnionParts.append({ _query, enuUnionType::All }); return *this; } -SelectQuery& SelectQuery::addUnionDistinct(SelectQuery& _query) -{ +SelectQuery& SelectQuery::addUnionDistinct(SelectQuery& _query) { this->Data->UnionParts.append({ _query, enuUnionType::Distinct }); return *this; } @@ -2496,21 +2411,18 @@ SelectQuery& SelectQuery::addUnionDistinct(SelectQuery& _query) |* Other *| \***********************/ //used by APPLY_GET_METHOD_CALL_ARGS_APICALL_TO_QUERY -SelectQuery& SelectQuery::offset(quint64 _offset) -{ +SelectQuery& SelectQuery::offset(quint64 _offset) { this->Data->Offset = _offset; return *this; } //used by APPLY_GET_METHOD_CALL_ARGS_APICALL_TO_QUERY -SelectQuery& SelectQuery::limit(quint16 _limit) -{ +SelectQuery& SelectQuery::limit(quint16 _limit) { this->Data->Limit = _limit; return *this; } -SelectQuery& SelectQuery::setCacheTime(quint16 _cacheTime) -{ +SelectQuery& SelectQuery::setCacheTime(quint16 _cacheTime) { this->Data->CahceTime = _cacheTime; return *this; } @@ -2555,8 +2467,7 @@ into_option: { } */ -QString SelectQuery::buildQueryString(QVariantMap _args, bool _selectOne, bool _reportCount, bool _checkStatusCol) -{ +QString SelectQuery::buildQueryString(QVariantMap _args, bool _selectOne, bool _reportCount, bool _checkStatusCol) { //this->Data->Table.prepareFiltersList(); this->Data->prepare(0, false); this->WhereTraitData->prepare(_checkStatusCol); @@ -2568,12 +2479,10 @@ QString SelectQuery::buildQueryString(QVariantMap _args, bool _selectOne, bool _ quint64 offset = this->Data->Offset; quint16 limit = this->Data->Limit; - if (_reportCount) - { + if (_reportCount) { this->Data->Offset = 0; this->Data->Limit = 0; - } - else if (_selectOne) + } else if (_selectOne) this->Data->Limit = 1; QStringList QueryParts; @@ -2583,8 +2492,7 @@ QString SelectQuery::buildQueryString(QVariantMap _args, bool _selectOne, bool _ QueryParts.append(QString("SELECT").rightJustified(SQLPrettyLen) + " " + this->Data->SelectQueryPreparedItems.Cols.join("\n" + QString(SQLPrettyLen - 1, ' ') + "," + " ")); - } - else { + } else { QueryParts.append("SELECT"); QueryParts.append(this->Data->SelectQueryPreparedItems.Cols.join(",")); } @@ -2594,8 +2502,7 @@ QString SelectQuery::buildQueryString(QVariantMap _args, bool _selectOne, bool _ QueryParts.append(QString("FROM").rightJustified(SQLPrettyLen) + " " + this->Data->BaseQueryPreparedItems.From); - } - else { + } else { QueryParts.append("FROM"); QueryParts.append(this->Data->BaseQueryPreparedItems.From); } @@ -2613,92 +2520,77 @@ QString SelectQuery::buildQueryString(QVariantMap _args, bool _selectOne, bool _ if (this->WhereTraitData->PreparedItems.Where.size()) WhereParts.append(this->WhereTraitData->PreparedItems.Where); - if (WhereParts.size()) - { + if (WhereParts.size()) { if (SQLPrettyLen) { QueryParts.append(QString("WHERE").rightJustified(SQLPrettyLen) + " " + WhereParts.join("\n" + QString(SQLPrettyLen, ' ') + " ")); - } - else { + } else { QueryParts.append("WHERE"); QueryParts.append(WhereParts.join(" ")); } } //----------- - if (this->GroupAndHavingTraitData->PreparedItems.GroupBy.size()) - { + if (this->GroupAndHavingTraitData->PreparedItems.GroupBy.size()) { if (SQLPrettyLen) { QueryParts.append(QString("GROUP BY").rightJustified(SQLPrettyLen) + " " + this->GroupAndHavingTraitData->PreparedItems.GroupBy.join("\n" + QString(SQLPrettyLen - 1, ' ') + "," + " ")); - } - else { + } else { QueryParts.append("GROUP BY"); QueryParts.append(this->GroupAndHavingTraitData->PreparedItems.GroupBy.join(",")); } } //----------- - if (this->GroupAndHavingTraitData->PreparedItems.Having.size()) - { + if (this->GroupAndHavingTraitData->PreparedItems.Having.size()) { if (SQLPrettyLen) { QueryParts.append(QString("HAVING").rightJustified(SQLPrettyLen) + " " + this->GroupAndHavingTraitData->PreparedItems.Having); - } - else { + } else { QueryParts.append("HAVING"); QueryParts.append(this->GroupAndHavingTraitData->PreparedItems.Having); } } //----------- - if (this->Data->SelectQueryPreparedItems.OrderBy.size()) - { + if (this->Data->SelectQueryPreparedItems.OrderBy.size()) { if (SQLPrettyLen) { QueryParts.append(QString("ORDER BY").rightJustified(SQLPrettyLen) + " " + this->Data->SelectQueryPreparedItems.OrderBy.join("\n" + QString(SQLPrettyLen - 1, ' ') + "," + " ")); - } - else { + } else { QueryParts.append("ORDER BY"); QueryParts.append(this->Data->SelectQueryPreparedItems.OrderBy.join(",")); } } //----------- - if (_reportCount == false) - { - if (this->WhereTraitData->PksByPath.isEmpty()) - { - if ((this->Data->Offset > 0) || (this->Data->Limit > 0)) - { + if (_reportCount == false) { + if (this->WhereTraitData->PksByPath.isEmpty()) { + if ((this->Data->Offset > 0) || (this->Data->Limit > 0)) { QString sLimit; - if (this->Data->Offset > 0) - { + if (this->Data->Offset > 0) { if (this->Data->Limit > 0) sLimit = QString("%1,%2").arg(this->Data->Offset).arg(this->Data->Limit); else sLimit = QString("%1").arg(this->Data->Offset); - } - else //limit > 0 + } else //limit > 0 sLimit = QString("0,%1").arg(this->Data->Limit); if (SQLPrettyLen) { QueryParts.append(QString("LIMIT").rightJustified(SQLPrettyLen) + " " + sLimit); - } - else { + } else { QueryParts.append(QString("LIMIT") + " " + sLimit); } } - } - else { + } else { if (SQLPrettyLen) QueryParts.append(QString("LIMIT").rightJustified(SQLPrettyLen) + " " @@ -2719,10 +2611,8 @@ QString SelectQuery::buildQueryString(QVariantMap _args, bool _selectOne, bool _ //----------- QString QueryString = QueryParts.join(SQLPrettyLen ? "\n" : " "); - if (_args.size()) - { - for (QVariantMap::const_iterator arg = _args.begin(); arg != _args.end(); ++arg) - { + if (_args.size()) { + for (QVariantMap::const_iterator arg = _args.begin(); arg != _args.end(); ++arg) { QueryString.replace(arg.key(), arg.value().toString()); } } @@ -2741,8 +2631,7 @@ QString SelectQuery::buildQueryString(QVariantMap _args, bool _selectOne, bool _ QueryParts.append(QString(")").rightJustified(SQLPrettyLen + 2) + " `qry`"); QueryString = QueryParts.join(SQLPrettyLen ? "\n" : " "); - } - else { + } else { QueryString = "SELECT COUNT(*) AS `cnt` FROM (" + QueryString + ") `qry`"; } } @@ -2756,8 +2645,7 @@ QString SelectQuery::buildQueryString(QVariantMap _args, bool _selectOne, bool _ } /* -quint64 SelectQuery::count(QVariantMap _args) -{ +quint64 SelectQuery::count(QVariantMap _args) { QString QueryString = this->buildQueryString(_currentUserID, _args, false, true, true); //execute @@ -2776,8 +2664,7 @@ quint64 SelectQuery::count(QVariantMap _args) // return t; //} -QVariantMap SelectQuery::one(QVariantMap _args) -{ +QVariantMap SelectQuery::one(QVariantMap _args) { QString QueryString = this->buildQueryString(_args, true, false, true); #ifdef QT_DEBUG @@ -2800,14 +2687,13 @@ QVariantMap SelectQuery::one(QVariantMap _args) throw exHTTPNotFound(QString("No item could be found in table (%1.%2)").arg(PrependSchema(this->Data->Table.Schema)).arg(this->Data->Table.Name)); // qDebug() << "--- SelectQuery::one()" << __FILE__ << __LINE__ << Result; -// qDebug() << "--- SelectQuery::one(){tovariant}" << __FILE__ << __LINE__ << Result.toVariant(); -// qDebug() << "--- SelectQuery::one(){tovariant.tomap}" << __FILE__ << __LINE__ << Result.toVariant().toMap(); +// qDebug() << "--- SelectQuery::one() {tovariant}" << __FILE__ << __LINE__ << Result.toVariant(); +// qDebug() << "--- SelectQuery::one() {tovariant.tomap}" << __FILE__ << __LINE__ << Result.toVariant().toMap(); return Result.toVariant().toMap(); } -QVariantMap SelectQuery::tryOne(QVariantMap _args) -{ +QVariantMap SelectQuery::tryOne(QVariantMap _args) { QT_TRY { return this->one(_args); } @@ -2816,8 +2702,7 @@ QVariantMap SelectQuery::tryOne(QVariantMap _args) } } -QVariantList SelectQuery::all(QVariantMap _args, quint16 _maxCount, quint64 _from) -{ +QVariantList SelectQuery::all(QVariantMap _args, quint16 _maxCount, quint64 _from) { this->Data->Offset = _from; this->Data->Limit = _maxCount; @@ -2846,8 +2731,7 @@ QVariantList SelectQuery::all(QVariantMap _args, quint16 _maxCount, quint64 _fro return Result.toVariant().toList(); } -TAPI::stuTable SelectQuery::allWithCount(QVariantMap _args, quint16 _maxCount, quint64 _from) -{ +TAPI::stuTable SelectQuery::allWithCount(QVariantMap _args, quint16 _maxCount, quint64 _from) { this->Data->Offset = _from; this->Data->Limit = _maxCount; @@ -2871,8 +2755,7 @@ TAPI::stuTable SelectQuery::allWithCount(QVariantMap _args, quint16 _maxCount, q ResultRows = DAC.execQueryCacheable(this->Data->CahceTime, "", QueryString) .toJson(false, this->Data->Table.Converters); - } - else { + } else { ResultTotalRows = DAC.execQuery("", CountingQueryString) .toJson(true); @@ -2909,9 +2792,9 @@ struct stuCreateQueryPreparedItems { class clsCreateQueryData : public clsBaseQueryData { public: - clsCreateQueryData(clsTable& _table, const QString& _alias = {}) : clsBaseQueryData(_table, _alias) {} -// clsCreateQueryData(const clsCreateQueryData& _other) : Table(_other.Table), Alias(_other.Alias) {} -// ~clsCreateQueryData() {} + clsCreateQueryData(clsTable& _table, const QString& _alias = {}) : clsBaseQueryData(_table, _alias) { ; } +// clsCreateQueryData(const clsCreateQueryData& _other) : Table(_other.Table), Alias(_other.Alias) { ; } +// ~clsCreateQueryData() { ; } virtual void prepare(quint64 _currentUserID, bool _useBinding) { Q_UNUSED(_currentUserID) @@ -2959,12 +2842,9 @@ class clsCreateQueryData : public clsBaseQueryData } //2- check BaseCols (required, ...) - foreach (stuRelatedORMField baseCol, this->Table.AllCols) - { - if (baseCol.Relation == InvalidRelation) - { - if (this->Cols.contains(baseCol.Col.name()) == false) - { + foreach (stuRelatedORMField baseCol, this->Table.AllCols) { + if (baseCol.Relation == InvalidRelation) { + if (this->Cols.contains(baseCol.Col.name()) == false) { if (baseCol.Col.defaultValue() == QRequired) throw exQueryBuilderColumnNotProvided("Required field <" + baseCol.Col.name() + "> not provided"); @@ -2972,20 +2852,16 @@ class clsCreateQueryData : public clsBaseQueryData // extraBaseCols.append(baseCol); this->CreateQueryPreparedItems.Cols.append(makeColName(this->Table.Name, this->Alias, baseCol.Col, false)); extraBaseColsValues.append(baseCol.Col.toDB(_currentUserID)); - } - else if (baseCol.Col.defaultValue() == QNow) - { + } else if (baseCol.Col.defaultValue() == QNow) { //NOW() is defined as default value in db schema // this->CreateQueryPreparedItems.Cols.append(makeColName(MainTableNameOrAlias, baseCol, false)); // extraBaseColsValues.append(DBExpression::NOW().toString()); - } - else if ((baseCol.Col.defaultValue() != QNull) + } else if ((baseCol.Col.defaultValue() != QNull) && (baseCol.Col.defaultValue() != QInvalid) && (baseCol.Col.defaultValue() != QAuto) && (baseCol.Col.defaultValue() != QDBInternal) - ) - { + ) { // qDebug() << "********************" << makeColName(MainTableNameOrAlias, baseCol, false) << baseCol.defaultValue() << baseCol.toDB(baseCol.defaultValue()); this->CreateQueryPreparedItems.Cols.append(makeColName(this->Table.Name, this->Alias, baseCol.Col, false)); extraBaseColsValues.append(baseCol.Col.toDB(baseCol.Col.defaultValue())); @@ -3021,8 +2897,7 @@ class clsCreateQueryData : public clsBaseQueryData QString v = makeValueAsSQL(val, _useBinding == false, &baseCol); //qDebug() << itr.key() << ": val(" << val << ") makeAsSQL(" << v << ") toDB(" << baseCol.toDB(val) << ")"; oneRecordToString.append(v); - } - else { + } else { oneRecordToString.append("?"); // QVariant v = makeValueAsVariant(val); // QString l = QString::fromUtf8(v.value().toJson(QJsonDocument::Compact)); @@ -3057,8 +2932,7 @@ class clsCreateQueryData : public clsBaseQueryData oneRecordToString.append("?"); QVariant v = makeValueAsVariant(val); this->CreateQueryPreparedItems.BindingValues.append(v); - } - else { + } else { QString v = makeValueAsSQL(val, true); // qDebug() << val << v; oneRecordToString.append(v); @@ -3070,8 +2944,7 @@ class clsCreateQueryData : public clsBaseQueryData } if (this->CreateQueryPreparedItems.Values.isEmpty()) throw exQueryBuilder("Values is empty"); - } - else if (this->Select.isValid()) { + } else if (this->Select.isValid()) { if (extraBaseColsValues.length()) { foreach (auto val, extraBaseColsValues) { this->Select.addCol(DBExpression(makeValueAsSQL(val, true), enuDBExpressionType::Value)); @@ -3079,8 +2952,7 @@ class clsCreateQueryData : public clsBaseQueryData } this->CreateQueryPreparedItems.Select = this->Select.buildQueryString({}, false, false, false); - } - else + } else throw exQueryBuilder("Values or Select not provided"); } @@ -3098,19 +2970,18 @@ class clsCreateQueryData : public clsBaseQueryData /***************************************************************************************/ CreateQuery::CreateQuery(const CreateQuery& _other) : tmplBaseQuery(_other) -{} +{ ; } CreateQuery::CreateQuery(clsTable& _table, const QString& _alias) : tmplBaseQuery(_table, _alias) -{} +{ ; } -CreateQuery::~CreateQuery() {} +CreateQuery::~CreateQuery() { ; } /***********************\ |* Options *| \***********************/ -CreateQuery& CreateQuery::options_ignore() -{ +CreateQuery& CreateQuery::options_ignore() { this->Data->Options_Ignore = true; return *this; } @@ -3118,8 +2989,7 @@ CreateQuery& CreateQuery::options_ignore() /***********************\ |* Columns *| \***********************/ -CreateQuery& CreateQuery::addCols(const QStringList& _cols) -{ +CreateQuery& CreateQuery::addCols(const QStringList& _cols) { // if (this->Data->Values.length()) // throw new exQueryBuilder("Columns must be defined before values"); @@ -3131,8 +3001,7 @@ CreateQuery& CreateQuery::addCols(const QStringList& _cols) return *this; } -CreateQuery& CreateQuery::addCol(const QString& _col) -{ +CreateQuery& CreateQuery::addCol(const QString& _col) { // if (this->Data->Values.length()) // throw new exQueryBuilder("Columns must be defined before values"); @@ -3145,8 +3014,7 @@ CreateQuery& CreateQuery::addCol(const QString& _col) /***********************\ |* Values *| \***********************/ -CreateQuery& CreateQuery::values(const QVariantMap& _oneRecordValues) -{ +CreateQuery& CreateQuery::values(const QVariantMap& _oneRecordValues) { if (this->Data->Cols.isEmpty()) throw new exQueryBuilder("Columns must be defined before values"); @@ -3160,8 +3028,7 @@ CreateQuery& CreateQuery::values(const QVariantMap& _oneRecordValues) return *this; } -CreateQuery& CreateQuery::values(const QList& _multipleRecordValues) -{ +CreateQuery& CreateQuery::values(const QList& _multipleRecordValues) { if (this->Data->Cols.isEmpty()) throw new exQueryBuilder("Columns must be defined before values"); @@ -3175,8 +3042,7 @@ CreateQuery& CreateQuery::values(const QList& _multipleRecordValues /***********************\ |* Select *| \***********************/ -CreateQuery& CreateQuery::select(const SelectQuery& _selectQuery) -{ +CreateQuery& CreateQuery::select(const SelectQuery& _selectQuery) { if (this->Data->Cols.isEmpty()) throw new exQueryBuilder("Columns must be defined before select query"); @@ -3191,8 +3057,7 @@ CreateQuery& CreateQuery::select(const SelectQuery& _selectQuery) /***********************\ |* Execute *| \***********************/ -stuBoundQueryString CreateQuery::buildQueryString(quint64 _currentUserID, QVariantMap _args, bool _useBinding) -{ +stuBoundQueryString CreateQuery::buildQueryString(quint64 _currentUserID, QVariantMap _args, bool _useBinding) { stuBoundQueryString BoundQueryString; this->Data->prepare(_currentUserID, _useBinding); @@ -3227,8 +3092,7 @@ stuBoundQueryString CreateQuery::buildQueryString(quint64 _currentUserID, QVaria QueryParts.append(QString(SQLPrettyLen, ' ') + " " + ")"); - } - else { + } else { QueryParts.append("INSERT"); if (options.length()) QueryParts.append(options.join(" ")); @@ -3248,8 +3112,7 @@ stuBoundQueryString CreateQuery::buildQueryString(quint64 _currentUserID, QVaria rows.append(QString(SQLPrettyLen, ' ') + " " + row.join("\n" + QString(SQLPrettyLen - 1, ' ') + "," + " ")); - } - else { + } else { rows.append(row.join(",")); } } @@ -3272,24 +3135,20 @@ stuBoundQueryString CreateQuery::buildQueryString(quint64 _currentUserID, QVaria + (_useBinding ? "" : QString(SQLPrettyLen, ' ')) + (_useBinding ? "" : " ") + ")"); - } - else { + } else { QueryParts.append("VALUES("); QueryParts.append(rows.join("),(")); QueryParts.append("VALUES("); } - } - else { + } else { QueryParts.append(this->Data->CreateQueryPreparedItems.Select); } //----------- BoundQueryString.QueryString = QueryParts.join(SQLPrettyLen ? "\n" : " "); - if (_args.size()) - { - for (QVariantMap::const_iterator arg = _args.begin(); arg != _args.end(); ++arg) - { + if (_args.size()) { + for (QVariantMap::const_iterator arg = _args.begin(); arg != _args.end(); ++arg) { BoundQueryString.QueryString.replace(arg.key(), arg.value().toString()); } } @@ -3303,8 +3162,7 @@ stuBoundQueryString CreateQuery::buildQueryString(quint64 _currentUserID, QVaria // throw exQueryBuilder("multi values for insert query with select clause can not be used in tables with `invalidated at` field"); //} -QString getInvalidatedAtQueryString(clsTable& _table, bool _makeWithUniqeIndex, bool _lookupFromRegistryFirst) -{ +QString getInvalidatedAtQueryString(clsTable& _table, bool _makeWithUniqeIndex, bool _lookupFromRegistryFirst) { QString invalidatedAtFieldName = _table.getDBProperty(ORM_TABLE_DBPROPERTY_INVALIDATE_AT_FIELD_NAME).toString(); if (invalidatedAtFieldName.isEmpty()) return ""; @@ -3315,8 +3173,7 @@ QString getInvalidatedAtQueryString(clsTable& _table, bool _makeWithUniqeIndex, QString invalidateQueryString; - if (_lookupFromRegistryFirst) - { + if (_lookupFromRegistryFirst) { QVariant invalidateQuery = _table.getDBProperty(ORM_TABLE_DBPROPERTY_INVALIDATE_QUERY); if (invalidateQuery.isValid()) invalidateQueryString = invalidateQuery.toString(); @@ -3333,10 +3190,8 @@ QString getInvalidatedAtQueryString(clsTable& _table, bool _makeWithUniqeIndex, if (invalidateQueryString.isEmpty()) throw exQueryBuilder("invalidate update query not provided for " + _table.Name); - if (invalidateQueryString.length()) - { - if (_makeWithUniqeIndex) - { + if (invalidateQueryString.length()) { + if (_makeWithUniqeIndex) { //make invalidate update query dynamically QStringList w; @@ -3366,38 +3221,30 @@ QString getInvalidatedAtQueryString(clsTable& _table, bool _makeWithUniqeIndex, } ///TODO: BUG: the create query may results more than one rows, but only last inserted id returns by .execute -quint64 CreateQuery::execute(quint64 _currentUserID, QVariantMap _args, bool _useBinding) -{ +quint64 CreateQuery::execute(quint64 _currentUserID, QVariantMap _args, bool _useBinding) { stuBoundQueryString BoundQueryString = this->buildQueryString(_currentUserID, _args, _useBinding); clsDAC DAC(this->Data->Table.domain(), PrependSchema(this->Data->Table.Schema)); ///TODO: start transaction - QT_TRY - { + QT_TRY { //1: invalidate OLD removed row(s) QString invalidateQueryString = getInvalidatedAtQueryString(this->Data->Table, true, true); - if (invalidateQueryString.length()) - { + if (invalidateQueryString.length()) { if (this->Data->Select.isValid()) throw exQueryBuilder("multi values for insert query with select clause can not be used in tables with `invalidated at` field"); // updateInvalidatedAt(this->Data->Select, invalidateQueryString); - else - { - foreach (QVariantMap oneRecord, this->Data->Values) - { + else { + foreach (QVariantMap oneRecord, this->Data->Values) { QString query = invalidateQueryString; - foreach (stuRelatedORMField baseCol, this->Data->Table.AllCols) - { - if (baseCol.Relation == InvalidRelation) - { + foreach (stuRelatedORMField baseCol, this->Data->Table.AllCols) { + if (baseCol.Relation == InvalidRelation) { //ignore statusFieldName in update conditions // if (statusFieldName.length() && (Col.name() == statusFieldName)) // continue; - for (QVariantMap::const_iterator itr = oneRecord.constBegin(); itr != oneRecord.constEnd(); itr++) - { + for (QVariantMap::const_iterator itr = oneRecord.constBegin(); itr != oneRecord.constEnd(); itr++) { QString key = itr.key(); if (key == baseCol.Col.name()) { QVariant val = itr.value(); @@ -3431,8 +3278,7 @@ quint64 CreateQuery::execute(quint64 _currentUserID, QVariantMap _args, bool _us << endl << "-- Query:" << endl << BoundQueryString.QueryString << endl << endl << "-- Binding Values:" << endl << BoundQueryString.BindingValues << endl << "-- [" << BindingValuesList.join(", ") << "]" << endl; - } - else { + } else { qDebug().nospace().noquote() << endl << endl << "-- Query:" << endl << BoundQueryString.QueryString << endl; } @@ -3452,8 +3298,7 @@ quint64 CreateQuery::execute(quint64 _currentUserID, QVariantMap _args, bool _us return ret; } - QT_CATCH(...) - { + QT_CATCH(...) { ///TODO: rollback QT_RETHROW; } @@ -3472,9 +3317,9 @@ struct stuUpdateQueryPreparedItems { class clsUpdateQueryData : public clsBaseQueryData { public: - clsUpdateQueryData(clsTable& _table, const QString& _alias = {}) : clsBaseQueryData(_table, _alias) {} -// clsUpdateQueryData(const clsUpdateQueryData& _other) : Table(_other.Table), Alias(_other.Alias) {} -// ~clsUpdateQueryData() {} + clsUpdateQueryData(clsTable& _table, const QString& _alias = {}) : clsBaseQueryData(_table, _alias) { ; } +// clsUpdateQueryData(const clsUpdateQueryData& _other) : Table(_other.Table), Alias(_other.Alias) { ; } +// ~clsUpdateQueryData() { ; } virtual void prepare(quint64 _currentUserID, bool _useBinding) { if (this->UpdateQueryPreparedItems.IsPrepared) @@ -3519,8 +3364,7 @@ class clsUpdateQueryData : public clsBaseQueryData this->UpdateQueryPreparedItems.SetCols.append(QString("%1%2%3").arg(colName).arg(equalSign).arg(colName)); else this->UpdateQueryPreparedItems.SetCols.append(QString("%1%2%3.%4").arg(colName).arg(equalSign).arg(tableName).arg(colName)); - } - else { + } else { providedCols.append(key); if (val.userType() != QMetaTypeId::qt_metatype_id()) @@ -3529,26 +3373,22 @@ class clsUpdateQueryData : public clsBaseQueryData if (val.userType() == QMetaTypeId::qt_metatype_id() || _useBinding == false) { QString v = makeValueAsSQL(val, _useBinding == false, &relatedORMField.Col); this->UpdateQueryPreparedItems.SetCols.append(QString("%1%2%3").arg(colName).arg(equalSign).arg(v)); - } - else { + } else { this->UpdateQueryPreparedItems.SetCols.append(QString("%1%2?").arg(colName).arg(equalSign)); this->UpdateQueryPreparedItems.BindingValues.append(relatedORMField.Col.toDB(val)); } } } - foreach (stuRelatedORMField baseCol, this->Table.AllCols) - { + foreach (stuRelatedORMField baseCol, this->Table.AllCols) { if ((baseCol.Relation == InvalidRelation) && (providedCols.contains(baseCol.Col.name()) == false) - && (baseCol.Col.updatableBy() == enuUpdatableBy::__UPDATER__ )) - { + && (baseCol.Col.updatableBy() == enuUpdatableBy::__UPDATER__ )) { auto colName = makeColName(this->Table.Name, this->Alias, baseCol.Col, false); if (_useBinding == false) this->UpdateQueryPreparedItems.SetCols.append(QString("%1%2%3").arg(colName).arg(equalSign).arg(baseCol.Col.toDB(_currentUserID).toString())); - else - { + else { this->UpdateQueryPreparedItems.SetCols.append(QString("%1%2?").arg(colName).arg(equalSign)); this->UpdateQueryPreparedItems.BindingValues.append(baseCol.Col.toDB(_currentUserID)); } @@ -3571,8 +3411,7 @@ class clsUpdateQueryData : public clsBaseQueryData UpdateQuery::UpdateQuery(const UpdateQuery& _other) : tmplBaseQuery(_other), tmplQueryJoinTrait(_other), - tmplQueryWhereTrait(_other) -{ + tmplQueryWhereTrait(_other) { tmplQueryJoinTrait::JoinTraitData->Owner = this; tmplQueryWhereTrait::WhereTraitData->Owner = this; } @@ -3580,23 +3419,20 @@ UpdateQuery::UpdateQuery(clsTable& _table, const QString& _alias) : tmplBaseQuery(_table, _alias), tmplQueryJoinTrait(this), tmplQueryWhereTrait(this) -{} -UpdateQuery::~UpdateQuery() {} +{ ; } +UpdateQuery::~UpdateQuery() { ; } /***********************\ |* Set *| \***********************/ -UpdateQuery& UpdateQuery::setNull(const QString& _col) -{ +UpdateQuery& UpdateQuery::setNull(const QString& _col) { return this->set(_col, DBExpression::NIL()); } -UpdateQuery& UpdateQuery::set(const QString& _col, const QVariant& _value) -{ +UpdateQuery& UpdateQuery::set(const QString& _col, const QVariant& _value) { this->Data->SetMaps.append({ _col, _value }); return *this; } -UpdateQuery& UpdateQuery::set(const QString& _col, const QString& _otherTable, const QString& _otherCol) -{ +UpdateQuery& UpdateQuery::set(const QString& _col, const QString& _otherTable, const QString& _otherCol) { this->Data->SetMaps.append({ _col, QStringList({ _otherTable, _otherCol }) }); return *this; } @@ -3605,8 +3441,7 @@ UpdateQuery& UpdateQuery::set(const QString& _col, const QString& _otherTable, c // this->Data->SetMaps.append({ _col, DBExpression::VALUE(QString("%1 + %2").arg(_col).arg(_value)) }); // return *this; //} -UpdateQuery& UpdateQuery::increament(const QString& _col, qreal _value) -{ +UpdateQuery& UpdateQuery::increament(const QString& _col, qreal _value) { this->Data->SetMaps.append({ _col, DBExpression::VALUE(QString("%1 + %2").arg(_col).arg(_value)) }); return *this; } @@ -3615,8 +3450,7 @@ UpdateQuery& UpdateQuery::increament(const QString& _col, qreal _value) // this->Data->SetMaps.append({ _col, DBExpression::VALUE(QString("%1 - %2").arg(_col).arg(_value)) }); // return *this; //} -UpdateQuery& UpdateQuery::decreament(const QString& _col, qreal _value) -{ +UpdateQuery& UpdateQuery::decreament(const QString& _col, qreal _value) { this->Data->SetMaps.append({ _col, DBExpression::VALUE(QString("%1 - %2").arg(_col).arg(_value)) }); return *this; } @@ -3624,8 +3458,7 @@ UpdateQuery& UpdateQuery::decreament(const QString& _col, qreal _value) /***********************\ |* Execute *| \***********************/ -stuBoundQueryString UpdateQuery::buildQueryString(quint64 _currentUserID, QVariantMap _args, bool _useBinding) -{ +stuBoundQueryString UpdateQuery::buildQueryString(quint64 _currentUserID, QVariantMap _args, bool _useBinding) { if (this->WhereTraitData->isEmpty()) throw exQueryBuilderWhereClauseNotProvided("Where conditions of update query is empty. This is very dangerous."); @@ -3649,8 +3482,7 @@ stuBoundQueryString UpdateQuery::buildQueryString(quint64 _currentUserID, QVaria QueryParts.append(QString("UPDATE").rightJustified(SQLPrettyLen) + " " + this->Data->BaseQueryPreparedItems.From); - } - else { + } else { QueryParts.append("UPDATE"); QueryParts.append(this->Data->BaseQueryPreparedItems.From); } @@ -3667,8 +3499,7 @@ stuBoundQueryString UpdateQuery::buildQueryString(quint64 _currentUserID, QVaria QueryParts.append(QString("SET").rightJustified(SQLPrettyLen) + " " + this->Data->UpdateQueryPreparedItems.SetCols.join("\n" + QString(SQLPrettyLen - 1, ' ') + "," + " ")); - } - else { + } else { QueryParts.append("SET"); QueryParts.append(this->Data->UpdateQueryPreparedItems.SetCols.join(",")); } @@ -3679,14 +3510,12 @@ stuBoundQueryString UpdateQuery::buildQueryString(quint64 _currentUserID, QVaria if (this->WhereTraitData->PreparedItems.Where.size()) WhereParts.append(this->WhereTraitData->PreparedItems.Where); - if (WhereParts.size()) - { + if (WhereParts.size()) { if (SQLPrettyLen) { QueryParts.append(QString("WHERE").rightJustified(SQLPrettyLen) + " " + WhereParts.join("\n" + QString(SQLPrettyLen, ' ') + " ")); - } - else { + } else { QueryParts.append("WHERE"); QueryParts.append(WhereParts.join(" ")); } @@ -3695,10 +3524,8 @@ stuBoundQueryString UpdateQuery::buildQueryString(quint64 _currentUserID, QVaria //----------- BoundQueryString.QueryString = QueryParts.join(SQLPrettyLen ? "\n" : " "); - if (_args.size()) - { - for (QVariantMap::const_iterator arg = _args.begin(); arg != _args.end(); ++arg) - { + if (_args.size()) { + for (QVariantMap::const_iterator arg = _args.begin(); arg != _args.end(); ++arg) { BoundQueryString.QueryString.replace(arg.key(), arg.value().toString()); } } @@ -3708,8 +3535,7 @@ stuBoundQueryString UpdateQuery::buildQueryString(quint64 _currentUserID, QVaria return BoundQueryString; } -quint64 UpdateQuery::execute(quint64 _currentUserID, QVariantMap _args, bool _useBinding) -{ +quint64 UpdateQuery::execute(quint64 _currentUserID, QVariantMap _args, bool _useBinding) { stuBoundQueryString BoundQueryString = this->buildQueryString(_currentUserID, _args, _useBinding); #ifdef QT_DEBUG @@ -3723,8 +3549,7 @@ quint64 UpdateQuery::execute(quint64 _currentUserID, QVariantMap _args, bool _us << endl << "-- Query:" << endl << BoundQueryString.QueryString << endl << endl << "-- Binding Values:" << endl << BoundQueryString.BindingValues << endl << "-- [" << BindingValuesList.join(", ") << "]" << endl; - } - else { + } else { qDebug().nospace().noquote() << endl << endl << "-- Query:" << endl << BoundQueryString.QueryString << endl; } @@ -3752,9 +3577,9 @@ struct stuDeleteQueryPreparedItems { class clsDeleteQueryData : public clsBaseQueryData { public: - clsDeleteQueryData(clsTable& _table, const QString& _alias = {}) : clsBaseQueryData(_table, _alias) {} -// clsDeleteQueryData(const clsDeleteQueryData& _other) : Table(_other.Table), Alias(_other.Alias) {} -// ~clsDeleteQueryData() {} + clsDeleteQueryData(clsTable& _table, const QString& _alias = {}) : clsBaseQueryData(_table, _alias) { ; } +// clsDeleteQueryData(const clsDeleteQueryData& _other) : Table(_other.Table), Alias(_other.Alias) { ; } +// ~clsDeleteQueryData() { ; } virtual void prepare(quint64 _currentUserID, bool _useBinding) { Q_UNUSED(_currentUserID) @@ -3785,8 +3610,7 @@ class clsDeleteQueryData : public clsBaseQueryData DeleteQuery::DeleteQuery(const DeleteQuery& _other) : tmplBaseQuery(_other), tmplQueryJoinTrait(_other), - tmplQueryWhereTrait(_other) -{ + tmplQueryWhereTrait(_other) { tmplQueryJoinTrait::JoinTraitData->Owner = this; tmplQueryWhereTrait::WhereTraitData->Owner = this; } @@ -3794,14 +3618,13 @@ DeleteQuery::DeleteQuery(clsTable& _table, const QString& _alias) : tmplBaseQuery(_table, _alias), tmplQueryJoinTrait(this), tmplQueryWhereTrait(this) -{} -DeleteQuery::~DeleteQuery() {} +{ ; } +DeleteQuery::~DeleteQuery() { ; } /***********************\ |* Target *| \***********************/ -DeleteQuery& DeleteQuery::addTarget(const QString& _targetTableName) -{ +DeleteQuery& DeleteQuery::addTarget(const QString& _targetTableName) { this->Data->Targets.append(_targetTableName); return *this; } @@ -3809,8 +3632,7 @@ DeleteQuery& DeleteQuery::addTarget(const QString& _targetTableName) /***********************\ |* Execute *| \***********************/ -QString DeleteQuery::buildQueryString(quint64 _currentUserID, QVariantMap _args) -{ +QString DeleteQuery::buildQueryString(quint64 _currentUserID, QVariantMap _args) { if (this->WhereTraitData->isEmpty()) throw exQueryBuilderWhereClauseNotProvided("Where conditions of delete query is empty. This is very dangerous."); @@ -3840,8 +3662,7 @@ QString DeleteQuery::buildQueryString(quint64 _currentUserID, QVariantMap _args) QueryParts.append(QString("FROM").rightJustified(SQLPrettyLen) + " " + this->Data->BaseQueryPreparedItems.From); - } - else { + } else { QueryParts.append("DELETE"); QueryParts.append(this->Data->BaseQueryPreparedItems.From); @@ -3866,14 +3687,12 @@ QString DeleteQuery::buildQueryString(quint64 _currentUserID, QVariantMap _args) if (this->WhereTraitData->PreparedItems.Where.size()) WhereParts.append(this->WhereTraitData->PreparedItems.Where); - if (WhereParts.size()) - { + if (WhereParts.size()) { if (SQLPrettyLen) { QueryParts.append(QString("WHERE").rightJustified(SQLPrettyLen) + " " + WhereParts.join("\n" + QString(SQLPrettyLen, ' ') + " ")); - } - else { + } else { QueryParts.append("WHERE"); QueryParts.append(WhereParts.join(" ")); } @@ -3882,10 +3701,8 @@ QString DeleteQuery::buildQueryString(quint64 _currentUserID, QVariantMap _args) //----------- QString QueryString = QueryParts.join(SQLPrettyLen ? "\n" : " "); - if (_args.size()) - { - for (QVariantMap::const_iterator arg = _args.begin(); arg != _args.end(); ++arg) - { + if (_args.size()) { + for (QVariantMap::const_iterator arg = _args.begin(); arg != _args.end(); ++arg) { QueryString.replace(arg.key(), arg.value().toString()); } } @@ -3895,16 +3712,14 @@ QString DeleteQuery::buildQueryString(quint64 _currentUserID, QVariantMap _args) return QueryString; } -quint64 DeleteQuery::execute(quint64 _currentUserID, QVariantMap _args, bool _realDelete) -{ +quint64 DeleteQuery::execute(quint64 _currentUserID, QVariantMap _args, bool _realDelete) { QString QueryString = this->buildQueryString(_currentUserID, _args); clsDAC DAC(this->Data->Table.domain(), PrependSchema(this->Data->Table.Schema)); ///TODO: start transaction - QT_TRY - { + QT_TRY { QString statusFieldName = this->Data->Table.getStatusColumnName(); //1: invalidate OLD removed row @@ -3912,15 +3727,13 @@ quint64 DeleteQuery::execute(quint64 _currentUserID, QVariantMap _args, bool _re // qDebug() << "-------------" << invalidateQueryString; - if (invalidateQueryString.length()) - { + if (invalidateQueryString.length()) { invalidateQueryString += QString(" AND (%1)").arg(this->WhereTraitData->PreparedItems.Where); DAC.execQuery("", invalidateQueryString).numRowsAffected(); } //2: soft delete this - QT_TRY - { + QT_TRY { quint64 rowsAffected = UpdateQuery(this->Data->Table) .set(statusFieldName, "Removed") .where(this->WhereTraitData->WhereClauses) @@ -3932,8 +3745,7 @@ quint64 DeleteQuery::execute(quint64 _currentUserID, QVariantMap _args, bool _re return rowsAffected; } } - QT_CATCH(...) - { + QT_CATCH(...) { //update failed. use hard delete instead if (_realDelete == false) QT_RETHROW; @@ -3958,8 +3770,7 @@ quint64 DeleteQuery::execute(quint64 _currentUserID, QVariantMap _args, bool _re return ret; } - QT_CATCH(...) - { + QT_CATCH(...) { ///TODO: rollback QT_RETHROW; } diff --git a/Interfaces/DBM/QueryBuilders.h b/Interfaces/DBM/QueryBuilders.h index 21a0e244..2702dae9 100644 --- a/Interfaces/DBM/QueryBuilders.h +++ b/Interfaces/DBM/QueryBuilders.h @@ -484,7 +484,7 @@ class SelectQuery : // QVariant execute(QVariantMap _args = {}, quint16 _maxCount = 20, quint64 _from = 0); private: - virtual void iAmAbstract() {} + virtual void iAmAbstract() { ; } QString buildQueryString(QVariantMap _args = {}, bool _selectOne = false, bool _reportCount = false, bool _checkStatusCol = false); friend clsSelectQueryData; @@ -520,7 +520,7 @@ class CreateQuery : stuBoundQueryString buildQueryString(quint64 _currentUserID, QVariantMap _args = {}, bool _useBinding = true); private: - virtual void iAmAbstract() {} + virtual void iAmAbstract() { ; } friend testQueryBuilders; }; @@ -548,7 +548,7 @@ class UpdateQuery : quint64 execute(quint64 _currentUserID, QVariantMap _args = {}, bool _useBinding = true); private: - virtual void iAmAbstract() {} + virtual void iAmAbstract() { ; } stuBoundQueryString buildQueryString(quint64 _currentUserID, QVariantMap _args = {}, bool _useBinding = true); friend tmplQueryJoinTrait; friend testQueryBuilders; @@ -573,7 +573,7 @@ class DeleteQuery : quint64 execute(quint64 _currentUserID, QVariantMap _args = {}, bool _realDelete = false); private: - virtual void iAmAbstract() {} + virtual void iAmAbstract() { ; } QString buildQueryString(quint64 _currentUserID, QVariantMap _args = {}); friend tmplQueryJoinTrait; friend testQueryBuilders; diff --git a/Interfaces/DBM/clsORMField.cpp b/Interfaces/DBM/clsORMField.cpp index 527a1e13..ecd99ba8 100644 --- a/Interfaces/DBM/clsORMField.cpp +++ b/Interfaces/DBM/clsORMField.cpp @@ -35,7 +35,7 @@ namespace Targoman::API::DBM { clsORMFieldData::clsORMFieldData() : ParameterType(QMetaType::UnknownType) -{} +{ ; } clsORMFieldData::clsORMFieldData(const clsORMFieldData& _o) : QSharedData(_o), @@ -46,8 +46,7 @@ clsORMFieldData::clsORMFieldData(const clsORMFieldData& _o) : ExtraValidator(_o.ExtraValidator), RenameAs(_o.RenameAs), UpdatableBy(_o.UpdatableBy), - Privs(_o.Privs) -{ + Privs(_o.Privs) { if (this->ParamTypeName.startsWith("NULLABLE_TYPE(")) { this->ParamTypeName .replace("(", "<") @@ -98,13 +97,11 @@ clsORMFieldData::clsORMFieldData(const QString& _name, /****************************************************************/ clsORMField::clsORMField() : Data(new clsORMFieldData) -{} +{ ; } clsORMField::clsORMField(const clsORMField& _other, const QString& _newName) : - Data(_other.Data) -{ - if (_newName.length() && (this->Data->Name != _newName)) - { + Data(_other.Data) { + if (_newName.length() && (this->Data->Name != _newName)) { // print_stacktrace(); this->Data.detach(); this->Data->MasterName = this->Data->Name; @@ -142,10 +139,9 @@ clsORMField::clsORMField( _renameAs ) ) -{} +{ ; } -void clsORMField::registerTypeIfNotRegisterd(intfPureModule* _module) -{ +void clsORMField::registerTypeIfNotRegisterd(intfPureModule* _module) { if (Q_UNLIKELY(this->Data->ParameterType == QMetaType::UnknownType)) { this->Data->ParameterType = static_cast(QMetaType::type(this->Data->ParamTypeName.toLatin1())); if (this->Data->ParameterType == QMetaType::UnknownType) @@ -154,18 +150,15 @@ void clsORMField::registerTypeIfNotRegisterd(intfPureModule* _module) } } -void clsORMField::updateTypeID(QMetaType::Type _type) -{ +void clsORMField::updateTypeID(QMetaType::Type _type) { this->Data->ParameterType = _type; } -void clsORMField::validate(const QVariant _value) -{ +void clsORMField::validate(const QVariant _value) { this->argSpecs().validate(_value, this->Data->Name.toLatin1()); } -const intfAPIArgManipulator& clsORMField::argSpecs() -{ +const intfAPIArgManipulator& clsORMField::argSpecs() { if (this->Data->ParameterType == QMetaType::UnknownType) qDebug() << "clsORMField::argSpecs()" << this->Data->Name << this->Data->ParamTypeName << this->Data->ParameterType; @@ -179,13 +172,11 @@ const intfAPIArgManipulator& clsORMField::argSpecs() : *gUserDefinedTypesInfo.at(this->Data->ParameterType - TAPI_BASE_USER_DEFINED_TYPEID); } -QString clsORMField::toString(const QVariant& _value) -{ +QString clsORMField::toString(const QVariant& _value) { return this->argSpecs().toString(_value); } -QVariant clsORMField::toDB(const QVariant& _value) -{ +QVariant clsORMField::toDB(const QVariant& _value) { // qDebug() << "***********************" << __FUNCTION__ << _value << this->name() << this->parameterType() << this->paramTypeName() // << (this->argSpecs().fromORMValueConverter() ? "has fromORMValueConverter" : "return _value") // << QMetaType::QChar << _value.toString(); @@ -198,8 +189,7 @@ QVariant clsORMField::toDB(const QVariant& _value) ; } -QVariant clsORMField::fromDB(const QString& _value) -{ +QVariant clsORMField::fromDB(const QString& _value) { return this->argSpecs().toORMValue(_value); } diff --git a/Interfaces/DBM/clsORMField.h b/Interfaces/DBM/clsORMField.h index bd7fe36c..c4e5af8b 100644 --- a/Interfaces/DBM/clsORMField.h +++ b/Interfaces/DBM/clsORMField.h @@ -72,7 +72,7 @@ class clsORMFieldData : public QSharedData bool _isSelectable, const QString& _renameAs); clsORMFieldData(const clsORMFieldData& _o); - ~clsORMFieldData() {} + ~clsORMFieldData() { ; } inline bool isSortable() { return this->Privs & 0x01; } inline bool isFilterable() { return this->Privs & 0x02; } diff --git a/Interfaces/DBM/clsTable.cpp b/Interfaces/DBM/clsTable.cpp index f2997737..adeb7bc9 100644 --- a/Interfaces/DBM/clsTable.cpp +++ b/Interfaces/DBM/clsTable.cpp @@ -43,7 +43,7 @@ namespace Targoman::API::DBM { QString COLS_KEY = "cols"; -uint qHash(const Targoman::API::DBM::stuRelation& _relation){ +uint qHash(const Targoman::API::DBM::stuRelation& _relation) { return qHash(_relation.Column + _relation.ForeignColumn + _relation.ReferenceTable + _relation.RenamingPrefix); } @@ -63,10 +63,8 @@ clsTable::clsTable(const QString& _domain, Relations(_relations), Indexes(_indexes), DBProperties(_dbProperties), - CountOfPKs(0) -{ - foreach (auto Col, this->BaseCols) - { + CountOfPKs(0) { + foreach (auto Col, this->BaseCols) { if (Col.name() == ORM_INVALIDATED_AT_FIELD_NAME) this->addDBProperty( ORM_TABLE_DBPROPERTY_INVALIDATE_AT_FIELD_NAME, @@ -98,44 +96,41 @@ clsTable::clsTable(const QString& _schema, _indexes, _dbProperties ) -{} +{ ; } -clsTable* clsTable::addDBProperty(const QString& _key, const QVariant& _value) -{ +clsTable* clsTable::addDBProperty(const QString& _key, const QVariant& _value) { this->DBProperties.insert(_key, _value); return this; } -const QVariant clsTable::getDBProperty(const QString& _key) -{ +const QVariant clsTable::getDBProperty(const QString& _key) { if (this->DBProperties.contains(_key)) return this->DBProperties[_key]; return QVariant(); } -QList clsTable::filterItems(THttpMethod _method) -{ +QList clsTable::filterItems(THttpMethod _method) { QList Filters; - switch(_method){ + switch (_method) { case qhttp::EHTTP_GET: case qhttp::EHTTP_DELETE: this->prepareFiltersList(); foreach(auto Filter, this->BaseCols) - if(Filter.isPrimaryKey()) + if (Filter.isPrimaryKey()) Filters.append(Filter); - if(_method == qhttp::EHTTP_GET) + if (_method == qhttp::EHTTP_GET) Filters.append(clsORMField(COLS_KEY, S(TAPI::Cols_t), QFV, ORM_SELF_VIRTUAL)); break; case qhttp::EHTTP_PATCH: foreach(auto Filter, this->BaseCols) - if(Filter.updatableBy() != enuUpdatableBy::__CREATOR__ + if (Filter.updatableBy() != enuUpdatableBy::__CREATOR__ && Filter.updatableBy() != enuUpdatableBy::__UPDATER__ && (Filter.isPrimaryKey() || Filter.isReadOnly() == false)) Filters.append(Filter); break; case qhttp::EHTTP_PUT: foreach(auto Filter, this->BaseCols) - if(Filter.updatableBy() != enuUpdatableBy::__CREATOR__ + if (Filter.updatableBy() != enuUpdatableBy::__CREATOR__ && Filter.updatableBy() != enuUpdatableBy::__UPDATER__ && Filter.defaultValue() != QInvalid && Filter.defaultValue() != QAuto @@ -151,16 +146,14 @@ QList clsTable::filterItems(THttpMethod _method) return Filters; } -void clsTable::updateFilterParamType(const QString& _fieldTypeName, QMetaType::Type _typeID) -{ - foreach(auto Col, this->BaseCols){ - if(Col.paramTypeName() == _fieldTypeName) +void clsTable::updateFilterParamType(const QString& _fieldTypeName, QMetaType::Type _typeID) { + foreach(auto Col, this->BaseCols) { + if (Col.paramTypeName() == _fieldTypeName) Col.updateTypeID(_typeID); } } -void clsTable::prepareFiltersList() -{ +void clsTable::prepareFiltersList() { if (this->AllCols.size()) return; @@ -191,21 +184,18 @@ void clsTable::prepareFiltersList() QStringList AppliedRelations; this->prepareRelationsFiltersList(this->Relations, AppliedRelations); - foreach (stuRelatedORMField baseCol, this->AllCols) - { + foreach (stuRelatedORMField baseCol, this->AllCols) { const intfAPIArgManipulator& argSpecs = baseCol.Col.argSpecs(); if (argSpecs.toORMValueConverter() && !this->Converters.contains(this->finalColName(baseCol.Col))) this->Converters.insert(this->finalColName(baseCol.Col), argSpecs.toORMValueConverter()); } } -void clsTable::prepareRelationsFiltersList(const QList &_relations, QStringList &_appliedRelations) -{ +void clsTable::prepareRelationsFiltersList(const QList &_relations, QStringList &_appliedRelations) { if (_relations.isEmpty()) return; - foreach (stuRelation Relation, _relations) - { + foreach (stuRelation Relation, _relations) { QStringList parts; if (Relation.RenamingPrefix.length()) parts.append(Relation.RenamingPrefix); @@ -221,8 +211,7 @@ void clsTable::prepareRelationsFiltersList(const QList &_relations, clsTable* ForeignTable = clsTable::Registry[Relation.ReferenceTable]; //if (ForeignTable == nullptr) - foreach (clsORMField Col, ForeignTable->BaseCols) - { + foreach (clsORMField Col, ForeignTable->BaseCols) { QString FinalColName = this->finalColName(Col, Relation.RenamingPrefix); clsORMField NewCol = clsORMField(Col, FinalColName); @@ -264,8 +253,7 @@ const QString clsTable::nameWithSchema() const return QString("%1.%2").arg(this->Schema).arg(this->Name); } -const QString clsTable::domain() -{ +const QString clsTable::domain() { if (this->Domain.length()) return this->Domain; @@ -281,51 +269,43 @@ const QString clsTable::domain() return ""; } -const QString clsTable::getStatusColumnName() -{ +const QString clsTable::getStatusColumnName() { return this->getDBProperty(ORM_TABLE_DBPROPERTY_STATUS_FIELD_NAME).toString(); } -clsDACResult clsTable::callSP(const QString& _spName, const QVariantMap& _spArgs, const QString& _purpose, quint64* _executionTime) -{ +clsDACResult clsTable::callSP(const QString& _spName, const QVariantMap& _spArgs, const QString& _purpose, quint64* _executionTime) { clsDAC DAC(this->domain(), this->Schema); return DAC.callSP({}, _spName, _spArgs, _purpose, _executionTime); } -clsDACResult clsTable::callSPCacheable(quint32 _maxCacheTime, const QString& _spName, const QVariantMap& _spArgs, const QString& _purpose, quint64* _executionTime) -{ +clsDACResult clsTable::callSPCacheable(quint32 _maxCacheTime, const QString& _spName, const QVariantMap& _spArgs, const QString& _purpose, quint64* _executionTime) { clsDAC DAC(this->domain(), this->Schema); return DAC.callSPCacheable(_maxCacheTime, {}, _spName, _spArgs, _purpose, _executionTime); } -clsDACResult clsTable::execQuery(const QString& _queryStr, const QVariantList& _params, const QString& _purpose, quint64* _executionTime) -{ +clsDACResult clsTable::execQuery(const QString& _queryStr, const QVariantList& _params, const QString& _purpose, quint64* _executionTime) { clsDAC DAC(this->domain(), this->Schema); return DAC.execQuery({}, _queryStr, _params, _purpose, _executionTime); } -clsDACResult clsTable::execQuery(const QString& _queryStr, const QVariantMap& _params, const QString& _purpose, quint64* _executionTime) -{ +clsDACResult clsTable::execQuery(const QString& _queryStr, const QVariantMap& _params, const QString& _purpose, quint64* _executionTime) { clsDAC DAC(this->domain(), this->Schema); return DAC.execQuery({}, _queryStr, _params, _purpose, _executionTime); } -clsDACResult clsTable::execQueryCacheable(quint32 _maxCacheTime, const QString& _queryStr, const QVariantList& _params, const QString& _purpose, quint64* _executionTime) -{ +clsDACResult clsTable::execQueryCacheable(quint32 _maxCacheTime, const QString& _queryStr, const QVariantList& _params, const QString& _purpose, quint64* _executionTime) { clsDAC DAC(this->domain(), this->Schema); return DAC.execQueryCacheable(_maxCacheTime, {}, _queryStr, _params, _purpose, _executionTime); } -clsDACResult clsTable::execQueryCacheable(quint32 _maxCacheTime, const QString& _queryStr, const QVariantMap& _params, const QString& _purpose, quint64* _executionTime) -{ +clsDACResult clsTable::execQueryCacheable(quint32 _maxCacheTime, const QString& _queryStr, const QVariantMap& _params, const QString& _purpose, quint64* _executionTime) { clsDAC DAC(this->domain(), this->Schema); return DAC.execQueryCacheable(_maxCacheTime, {}, _queryStr, _params, _purpose, _executionTime); } //TAPI::Filter_t -> QString //TODO: IMPORTANT! deprecated? -void clsTable::setSelfFilters(const QVariantMap& _requiredFilters, QString& _providedFilters) -{ +void clsTable::setSelfFilters(const QVariantMap& _requiredFilters, QString& _providedFilters) { QStringList Filters; for (auto FilterIter = _requiredFilters.begin(); FilterIter != _requiredFilters.end(); ++FilterIter) @@ -339,14 +319,13 @@ void clsTable::setSelfFilters(const QVariantMap& _requiredFilters, QString& _pro //void clsTable::setSelfFilters(const QVariantMap& _requiredFilters, QVariantMap& _extraFilters) //{ -// for(auto FilterIter = _requiredFilters.begin(); FilterIter != _requiredFilters.end(); ++FilterIter) +// for (auto FilterIter = _requiredFilters.begin(); FilterIter != _requiredFilters.end(); ++FilterIter) // _extraFilters.insert(FilterIter.key(), FilterIter.value()); //} -QStringList clsTable::privOn(qhttp::THttpMethod _method, QString _moduleName) -{ +QStringList clsTable::privOn(qhttp::THttpMethod _method, QString _moduleName) { QString CRUD; - switch(_method){ + switch (_method) { case qhttp::EHTTP_PUT: CRUD = "T000";break; case qhttp::EHTTP_GET: CRUD = "0T00";break; case qhttp::EHTTP_PATCH: CRUD = "00T0";break; @@ -363,7 +342,7 @@ QString clsTable::finalColName(const clsORMField &_col, const QString &_prefix) /* clsTable::stuSelectItems clsTable::makeListingQuery(const QString& _requiredCols, const QStringList& _extraJoins, QString _filters, const QString& _orderBy, const QString _groupBy) const { - if(_requiredCols.size()) + if (_requiredCols.size()) QFV.asciiAlNum(false, ",()").validate(_requiredCols, "cols"); QFV.optional(QFV.asciiAlNum(false, ",\\+\\-")).validate(_orderBy, "orderBy"); @@ -374,16 +353,16 @@ clsTable::stuSelectItems clsTable::makeListingQuery(const QString& _requiredCols //----------------------------------------------------- QStringList RequiredCols = _requiredCols.size() ? _requiredCols.split(",", QString::SkipEmptyParts) : QStringList("*"); - auto addCol = [this, _groupBy, RequiredCols](clsTable::stuSelectItems& _selectItems, auto _col, const stuRelation& _relation = InvalidRelation){ - foreach(auto RequiredCol, RequiredCols){ + auto addCol = [this, _groupBy, RequiredCols](clsTable::stuSelectItems& _selectItems, auto _col, const stuRelation& _relation = InvalidRelation) { + foreach(auto RequiredCol, RequiredCols) { QString ColName; QString Function; - if(RequiredCol.contains('(')){ - if(RequiredCol.endsWith(')') == false) + if (RequiredCol.contains('(')) { + if (RequiredCol.endsWith(')') == false) throw exHTTPBadRequest("Aggroupation rule found without closing parenthesis: " + RequiredCol); Function = RequiredCol.split('(').first(); ColName = RequiredCol.split('(').last().replace(')', ""); - if(Function != "COUNT" + if (Function != "COUNT" && Function != "COUNT_DISTINCT" && Function != "SUM" && Function != "AVG" @@ -398,7 +377,7 @@ clsTable::stuSelectItems clsTable::makeListingQuery(const QString& _requiredCols } if (ColName == _relation.RenamingPrefix + _col.name () || ColName == _relation.RenamingPrefix + _col.renameAs()) { - if (Function.size()){ + if (Function.size()) { QString ColFinalName = makeColName(this->Name, _col, true, _relation); if (Function == "COUNT_DISTINCT") _selectItems.Cols.append("COUNT(DISTINCT " + ColFinalName.split(' ').first()+ ") AS COUNT_" + ColFinalName.split(' ').last()); @@ -411,38 +390,38 @@ clsTable::stuSelectItems clsTable::makeListingQuery(const QString& _requiredCols } return false; }; - foreach(auto Col, this->BaseCols){ - if(RequiredCols.isEmpty() || RequiredCols.contains("*")) + foreach(auto Col, this->BaseCols) { + if (RequiredCols.isEmpty() || RequiredCols.contains("*")) SelectItems.Cols.append(makeColName(this->Name, Col, true)); else addCol(SelectItems, Col); } QSet UsedJoins; - foreach(auto Relation, this->Relations){ + foreach(auto Relation, this->Relations) { clsTable* ForeignTable = clsTable::Registry[Relation.ReferenceTable]; - if(ForeignTable == nullptr) + if (ForeignTable == nullptr) throw exHTTPInternalServerError("Reference table has not been registered: " + Relation.ReferenceTable); bool Joined = false; - foreach(auto Col, ForeignTable->BaseCols){ - if(RequiredCols.isEmpty() || RequiredCols.contains("*")){ + foreach(auto Col, ForeignTable->BaseCols) { + if (RequiredCols.isEmpty() || RequiredCols.contains("*")) { SelectItems.Cols.append(makeColName(this->Name, Col, true, Relation)); Joined = true; - }else{ - if(addCol(SelectItems, Col, Relation)) + } else { + if (addCol(SelectItems, Col, Relation)) Joined = true; } } - if(Joined) + if (Joined) UsedJoins.insert(Relation); } - if(SelectItems.Cols.isEmpty()) + if (SelectItems.Cols.isEmpty()) throw exHTTPBadRequest("No columns found to be reported"); - if(RequiredCols.size() && RequiredCols.size() > SelectItems.Cols.size()) + if (RequiredCols.size() && RequiredCols.size() > SelectItems.Cols.size()) throw exHTTPBadRequest("Seems that some columns could not be resolved: Actives are: [" +SelectItems.Cols.join(", ")+ "]"); //----------------------------------------------------- @@ -451,7 +430,7 @@ clsTable::stuSelectItems clsTable::makeListingQuery(const QString& _requiredCols bool CanStartWithLogical = false; QString LastLogical = ""; _filters = _filters.replace("\\ ", "$SPACE$"); - foreach(auto Filter, _filters.split(" ", QString::SkipEmptyParts)){ + foreach(auto Filter, _filters.split(" ", QString::SkipEmptyParts)) { QString Rule; Filter = Filter.trimmed (); if (Filter == "(") { @@ -459,16 +438,16 @@ clsTable::stuSelectItems clsTable::makeListingQuery(const QString& _requiredCols CanStartWithLogical = false; LastLogical.clear(); OpenParenthesis++; - } else if(Filter == ")") { - if(OpenParenthesis <= 0) throw exHTTPBadRequest("Invalid close parenthesis without any open"); + } else if (Filter == ")") { + if (OpenParenthesis <= 0) throw exHTTPBadRequest("Invalid close parenthesis without any open"); Rule = " )"; OpenParenthesis--; CanStartWithLogical = true; - } else if(Filter == '+' || Filter == '|' || Filter == '*') { - if(CanStartWithLogical == false) throw exHTTPBadRequest("Invalid logical expression prior to any rule"); - if(Filter == '+') LastLogical = "AND "; - else if(Filter == '|') LastLogical = "OR "; - else if(Filter == '*') LastLogical = "XOR "; + } else if (Filter == '+' || Filter == '|' || Filter == '*') { + if (CanStartWithLogical == false) throw exHTTPBadRequest("Invalid logical expression prior to any rule"); + if (Filter == '+') LastLogical = "AND "; + else if (Filter == '|') LastLogical = "OR "; + else if (Filter == '*') LastLogical = "XOR "; CanStartWithLogical = false; continue; @@ -476,27 +455,27 @@ clsTable::stuSelectItems clsTable::makeListingQuery(const QString& _requiredCols static QRegularExpression rxFilterPattern("([a-zA-Z0-9\\_]+)([<>!=~]=?)(.+)"); Filter = Filter.replace("$SPACE$", " "); QRegularExpressionMatch PatternMatches = rxFilterPattern.match(Filter); - if(PatternMatches.lastCapturedIndex() != 3) + if (PatternMatches.lastCapturedIndex() != 3) throw exHTTPBadRequest("Invalid filter set: " + Filter); Rule = LastLogical; stuRelatedORMField relatedORMField = this->FilterableColsMap.value(PatternMatches.captured(1).trimmed()); - if(relatedORMField.isValid()) + if (relatedORMField.isValid()) Rule+=makeColName(this->Name, relatedORMField.Col, false, relatedORMField.Relation); else throw exHTTPBadRequest("Invalid column for filtring: " + PatternMatches.captured(1)); - if(relatedORMField.Col.updatableBy() == enuUpdatableBy::__STATUS__) + if (relatedORMField.Col.updatableBy() == enuUpdatableBy::__STATUS__) StatusColHasCriteria = true; - if(relatedORMField.Relation.Column.size() && UsedJoins.contains(relatedORMField.Relation) == false) + if (relatedORMField.Relation.Column.size() && UsedJoins.contains(relatedORMField.Relation) == false) UsedJoins.insert(relatedORMField.Relation); - if(PatternMatches.captured(3) == "NULL"){ - if(PatternMatches.captured(2) == "=") + if (PatternMatches.captured(3) == "NULL") { + if (PatternMatches.captured(2) == "=") Rule += " IS NULL"; - else if(PatternMatches.captured(2) == "!=") + else if (PatternMatches.captured(2) == "!=") Rule += " IS NOT NULL"; else throw exHTTPBadRequest("Invalid filter with NULL expression: " + Filter); @@ -507,23 +486,23 @@ clsTable::stuSelectItems clsTable::makeListingQuery(const QString& _requiredCols continue; } - if(PatternMatches.captured(2) == "<") Rule += " < "; - else if(PatternMatches.captured(2) == "<=") Rule += " <= "; - else if(PatternMatches.captured(2) == ">") Rule += " > "; - else if(PatternMatches.captured(2) == ">=") Rule += " >= "; - else if(PatternMatches.captured(2) == "!=") Rule += " != "; - else if(PatternMatches.captured(2) == "~=") Rule += " LIKE "; - else if(PatternMatches.captured(2) == "=") Rule += " = "; + if (PatternMatches.captured(2) == "<") Rule += " < "; + else if (PatternMatches.captured(2) == "<=") Rule += " <= "; + else if (PatternMatches.captured(2) == ">") Rule += " > "; + else if (PatternMatches.captured(2) == ">=") Rule += " >= "; + else if (PatternMatches.captured(2) == "!=") Rule += " != "; + else if (PatternMatches.captured(2) == "~=") Rule += " LIKE "; + else if (PatternMatches.captured(2) == "=") Rule += " = "; else throw exHTTPBadRequest("Invalid filter criteria: " + Filter); Rule += relatedORMField.Col.argSpecs().isPrimitiveType() ? "" : "'"; QString Value = PatternMatches.captured(3); - if(Value == "NOW()" + if (Value == "NOW()" || Value.startsWith("DATE_ADD(") || Value.startsWith("DATE_SUB(") ) Rule += Value.replace("$SPACE$", " "); - else{ + else { relatedORMField.Col.argSpecs().validate(Value, PatternMatches.captured(1).trimmed().toLatin1()); Rule += relatedORMField.Col.toDB(Value).toString(); } @@ -535,26 +514,26 @@ clsTable::stuSelectItems clsTable::makeListingQuery(const QString& _requiredCols SelectItems.Where.append(Rule); } - if(OpenParenthesis != 0) + if (OpenParenthesis != 0) throw exHTTPBadRequest("count of open and closed parenthesises does not match"); - if(SelectItems.Where.isEmpty()) + if (SelectItems.Where.isEmpty()) SelectItems.Where.append("TRUE"); - if(StatusColHasCriteria == false) + if (StatusColHasCriteria == false) foreach(auto FCol, this->FilterableColsMap) - if(FCol.Col.updatableBy() == enuUpdatableBy::__STATUS__){ - if(FCol.Relation.IsLeftJoin) + if (FCol.Col.updatableBy() == enuUpdatableBy::__STATUS__) { + if (FCol.Relation.IsLeftJoin) SelectItems.Where.append(QString("AND (ISNULL(%1) OR %1!='R')").arg(makeColName(this->Name, FCol.Col, false, FCol.Relation))); else SelectItems.Where.append(QString("AND %1!='R'").arg(makeColName(this->Name, FCol.Col, false, FCol.Relation))); - if(FCol.Relation.Column.size()) + if (FCol.Relation.Column.size()) UsedJoins.insert(FCol.Relation); } //----------------------------------------------------- SelectItems.From.append(this->Schema + "." + this->Name); - foreach(auto Join, UsedJoins){ + foreach(auto Join, UsedJoins) { SelectItems.From.append((Join.IsLeftJoin ? "LEFT JOIN " : "JOIN ") + Join.ReferenceTable + (Join.RenamingPrefix.size() ? " `" + Join.RenamingPrefix + "`" : "") @@ -565,19 +544,19 @@ clsTable::stuSelectItems clsTable::makeListingQuery(const QString& _requiredCols ); } - if(_extraJoins.size()) + if (_extraJoins.size()) SelectItems.From.append(_extraJoins); //----------------------------------------------------- foreach(auto OrderByCriteria, _orderBy.split(",", QString::SkipEmptyParts)) { QString Direction = "ASC"; - if(OrderByCriteria.startsWith("-")){ + if (OrderByCriteria.startsWith("-")) { Direction = "DESC"; OrderByCriteria = OrderByCriteria.mid(1); - }else if(OrderByCriteria.startsWith("+")) + } else if (OrderByCriteria.startsWith("+")) OrderByCriteria = OrderByCriteria.mid(1); - if(this->SortableColsMap.contains(OrderByCriteria) == false) + if (this->SortableColsMap.contains(OrderByCriteria) == false) throw exHTTPBadRequest("Invalid Order by <"+OrderByCriteria+"> not found in columns"); SelectItems.OrderBy.append(OrderByCriteria + " " + Direction); @@ -586,7 +565,7 @@ clsTable::stuSelectItems clsTable::makeListingQuery(const QString& _requiredCols //----------------------------------------------------- foreach(auto GroupByCriteria, _groupBy.split(",", QString::SkipEmptyParts)) { stuRelatedORMField Filter = this->FilterableColsMap.value(GroupByCriteria.trimmed()); - if(Filter.isValid()) + if (Filter.isValid()) SelectItems.GroupBy.append(makeColName(this->Name, Filter.Col, false, Filter.Relation)); else throw exHTTPBadRequest("Invalid group by <"+GroupByCriteria+"> not found in columns"); @@ -596,7 +575,7 @@ clsTable::stuSelectItems clsTable::makeListingQuery(const QString& _requiredCols } */ /* -QVariant clsTable::selectFromTableByID(quint64 _id, QString _cols, const QStringList& _extraJoins, const QString& _groupBy){ +QVariant clsTable::selectFromTableByID(quint64 _id, QString _cols, const QStringList& _extraJoins, const QString& _groupBy) { return this->selectFromTable(_extraJoins, {}, QString("%1").arg(_id), 0, 2, _cols, {}, {}, _groupBy, false, 0); } */ @@ -611,14 +590,13 @@ QVariant clsTable::selectFromTable(const QStringList& _extraJoins, const QString& _orderBy, const QString& _groupBy, bool _reportCount, - quint32 _cacheTime) -{ + quint32 _cacheTime) { this->prepareFiltersList(); -// if(_ormFields.contains(COLS_KEY)) +// if (_ormFields.contains(COLS_KEY)) // _cols = _ormFields.value(COLS_KEY).toString(); stuSelectItems SelectItems = this->makeListingQuery(_cols, _extraJoins, _filters + " " + _extraFilters, _orderBy, _groupBy); - if(_pksByPath.isEmpty()){ + if (_pksByPath.isEmpty()) { TAPI::stuTable Table; clsDAC DAC(this->domain(), this->Schema); @@ -642,21 +620,21 @@ QVariant clsTable::selectFromTable(const QStringList& _extraJoins, + QUERY_SEPARATOR + QString("LIMIT %1,%2").arg(_offset).arg(_limit); - if(_cacheTime) + if (_cacheTime) Table.Rows = DAC.execQueryCacheable(_cacheTime, "", QueryString).toJson(false, this->Converters).toVariant().toList(); else Table.Rows = DAC.execQuery("", QueryString).toJson(false, this->Converters).toVariant().toList(); - if(_reportCount) + if (_reportCount) Table.TotalRows = static_cast(DAC.execQuery("","SELECT FOUND_ROWS() AS cnt").toJson(true).object().value("cnt").toDouble()); return Table.toVariant(); - }else{ + } else { QStringList PrimaryKeyQueries = _pksByPath.split(";"); QStringList Filters; foreach(auto Query, PrimaryKeyQueries) foreach(auto Col, this->BaseCols) - if(Col.isPrimaryKey()){ - if(Query.size()) + if (Col.isPrimaryKey()) { + if (Query.size()) Filters.append(makeColName(this->Name, Col) + " = \"" + Query + "\""); break; } @@ -676,14 +654,14 @@ QVariant clsTable::selectFromTable(const QStringList& _extraJoins, clsDAC DAC(this->domain(), this->Schema); QJsonDocument Result; - if(_cacheTime) + if (_cacheTime) Result = DAC.execQueryCacheable(_cacheTime, "", QueryString) .toJson(true, this->Converters); else Result = DAC.execQuery("", QueryString) .toJson(true, this->Converters); - if(Result.object().isEmpty()) + if (Result.object().isEmpty()) throw exHTTPNotFound("No item could be found"); return Result.toVariant(); @@ -691,13 +669,12 @@ QVariant clsTable::selectFromTable(const QStringList& _extraJoins, } */ /* -QVariant clsTable::create(quint64 _actorUserID, const TAPI::ORMFields_t& _createInfo) -{ +QVariant clsTable::create(quint64 _actorUserID, const TAPI::ORMFields_t& _createInfo) { this->prepareFiltersList(); QStringList CreateCommands; QVariantList Values; - const auto isEmpty = [](const QVariant& _value){ + const auto isEmpty = [](const QVariant& _value) { return _value.isNull() || (_value.canConvert() && _value.toList().isEmpty()) || (_value.canConvert() && _value.toMap().isEmpty()) @@ -705,11 +682,11 @@ QVariant clsTable::create(quint64 _actorUserID, const TAPI::ORMFields_t& _create }; foreach(auto Item, this->BaseCols) - if(Item.defaultValue() == QRequired && (_createInfo.contains(Item.name()) == false || isEmpty(_createInfo.value(Item.name())))) + if (Item.defaultValue() == QRequired && (_createInfo.contains(Item.name()) == false || isEmpty(_createInfo.value(Item.name())))) throw exHTTPBadRequest("Required field <"+ Item.name() +"> not provided: "); - for(auto InfoIter = _createInfo.begin(); InfoIter != _createInfo.end(); ++InfoIter){ - if(InfoIter->isValid() == false) + for (auto InfoIter = _createInfo.begin(); InfoIter != _createInfo.end(); ++InfoIter) { + if (InfoIter->isValid() == false) continue; if (this->SelectableColsMap.contains(InfoIter.key()) == false) throw exHTTPInternalServerError("Invalid create option: " + InfoIter.key()); @@ -723,13 +700,13 @@ QVariant clsTable::create(quint64 _actorUserID, const TAPI::ORMFields_t& _create } foreach(auto Col, this->BaseCols) - if(Col.updatableBy() == enuUpdatableBy::__CREATOR__){ + if (Col.updatableBy() == enuUpdatableBy::__CREATOR__) { CreateCommands.append(makeColName(this->Name, Col) + "=?"); Values.append(Col.toDB(_actorUserID)); } clsDAC DAC(this->domain(), this->Schema); - try{ + try { clsDACResult Result = DAC.execQuery("", QString("INSERT INTO ") + this->Schema + "." + this->Name + QUERY_SEPARATOR @@ -738,14 +715,14 @@ QVariant clsTable::create(quint64 _actorUserID, const TAPI::ORMFields_t& _create + QUERY_SEPARATOR ,Values); return Result.lastInsertId(); - }catch(DBManager::exTargomanDBMUnableToExecuteQuery &e){ + } catch (DBManager::exTargomanDBMUnableToExecuteQuery &e) { QStringList FKs; foreach(auto FK, this->Relations) - if(FK.RenamingPrefix.isEmpty()) + if (FK.RenamingPrefix.isEmpty()) FKs.append(FK.Column); QRegularExpressionMatch Matches; - if(e.what().contains(QRegularExpression(QString("FOREIGN KEY \\(`(%1)`\\)").arg(FKs.join('|'))), &Matches)) + if (e.what().contains(QRegularExpression(QString("FOREIGN KEY \\(`(%1)`\\)").arg(FKs.join('|'))), &Matches)) throw exHTTPBadRequest("not a valid " + Matches.captured() + " provided"); else if (e.what().contains(QRegularExpression(QString("Duplicate entry '[^']+'")), &Matches)) throw exHTTPBadRequest(Matches.captured()); @@ -758,29 +735,28 @@ QVariant clsTable::create(quint64 _actorUserID, const TAPI::ORMFields_t& _create bool clsTable::update(quint64 _actorUserID, TAPI::PKsByPath_t _pksByPath, const TAPI::ORMFields_t& _updateInfo, - const QVariantMap& _extraFilters) -{ + const QVariantMap& _extraFilters) { this->prepareFiltersList(); - if(_pksByPath.isEmpty() && _extraFilters.isEmpty()) + if (_pksByPath.isEmpty() && _extraFilters.isEmpty()) throw exHTTPBadRequest("No key provided to update"); - if(_updateInfo.isEmpty()) + if (_updateInfo.isEmpty()) throw exHTTPBadRequest("No change provided to update"); QStringList PrimaryKeyQueries = _pksByPath.split(";"); QStringList Filters; foreach(auto Query, PrimaryKeyQueries) foreach(auto Col, this->BaseCols) - if(Col.isPrimaryKey()){ - if(Query.size()) + if (Col.isPrimaryKey()) { + if (Query.size()) Filters.append(makeColName(this->Name, Col) + " = \"" + Query + "\""); break; } QStringList UpdateCommands; QVariantList Values; - for(auto InfoIter = _updateInfo.begin(); InfoIter != _updateInfo.end(); ++InfoIter) { - if(InfoIter->isValid() == false) + for (auto InfoIter = _updateInfo.begin(); InfoIter != _updateInfo.end(); ++InfoIter) { + if (InfoIter->isValid() == false) continue; stuRelatedORMField& relatedORMField = this->SelectableColsMap[InfoIter.key()]; if (relatedORMField.Col.isReadOnly()) @@ -792,15 +768,15 @@ bool clsTable::update(quint64 _actorUserID, } foreach(auto FCol, this->FilterableColsMap) - if(FCol.Col.updatableBy() == enuUpdatableBy::__UPDATER__){ - if(FCol.Relation.Column.isEmpty()){ + if (FCol.Col.updatableBy() == enuUpdatableBy::__UPDATER__) { + if (FCol.Relation.Column.isEmpty()) { UpdateCommands.append(makeColName(this->Name, FCol.Col) + "=?"); Values.append(_actorUserID); } } - for(auto FilterIter = _extraFilters.begin(); FilterIter != _extraFilters.end(); FilterIter++) { - if(FilterIter->isValid() == false) + for (auto FilterIter = _extraFilters.begin(); FilterIter != _extraFilters.end(); FilterIter++) { + if (FilterIter->isValid() == false) continue; const stuRelatedORMField& relatedORMField = this->SelectableColsMap[FilterIter.key()]; if (relatedORMField.Col.isFilterable() == false) @@ -809,7 +785,7 @@ bool clsTable::update(quint64 _actorUserID, Values.append(FilterIter.value()); } - try{ + try { clsDAC DAC(this->domain(), this->Schema); clsDACResult Result = DAC.execQuery("", QString("UPDATE ") + this->Schema + "." + this->Name @@ -824,14 +800,14 @@ bool clsTable::update(quint64 _actorUserID, return Result.numRowsAffected() > 0; - }catch(DBManager::exTargomanDBMUnableToExecuteQuery &e){ + } catch (DBManager::exTargomanDBMUnableToExecuteQuery &e) { QStringList FKs; foreach(auto FK, this->Relations) - if(FK.RenamingPrefix.isEmpty()) + if (FK.RenamingPrefix.isEmpty()) FKs.append(FK.Column); QRegularExpressionMatch Matches; - if(e.what().contains(QRegularExpression(QString("FOREIGN KEY \\(`(%1)`\\)").arg(FKs.join('|'))), &Matches)) + if (e.what().contains(QRegularExpression(QString("FOREIGN KEY \\(`(%1)`\\)").arg(FKs.join('|'))), &Matches)) throw exHTTPBadRequest("not a valid " + Matches.captured() + " provided"); else if (e.what().contains(QRegularExpression(QString("Duplicate entry '[^']+'")), &Matches)) throw exHTTPBadRequest(Matches.captured()); @@ -841,14 +817,13 @@ bool clsTable::update(quint64 _actorUserID, } */ /* -bool clsTable::deleteByPKs(quint64 _actorUserID, const TAPI::PKsByPath_t& _pksByPath, QVariantMap _extraFilters, bool _realDelete) -{ +bool clsTable::deleteByPKs(quint64 _actorUserID, const TAPI::PKsByPath_t& _pksByPath, QVariantMap _extraFilters, bool _realDelete) { this->prepareFiltersList(); - if(this->update(_actorUserID, _pksByPath, TAPI::ORMFields_t({{this->BaseCols.last().name(), "Removed"}}), _extraFilters) == 0) + if (this->update(_actorUserID, _pksByPath, TAPI::ORMFields_t({{this->BaseCols.last().name(), "Removed"}}), _extraFilters) == 0) return false; - if(_realDelete == false) + if (_realDelete == false) return true; QStringList PrimaryKeyQueries = _pksByPath.split(";"); @@ -856,14 +831,14 @@ bool clsTable::deleteByPKs(quint64 _actorUserID, const TAPI::PKsByPath_t& _pksBy QVariantList Values; foreach(auto Query, PrimaryKeyQueries) foreach(auto Col, this->BaseCols) - if(Col.isPrimaryKey()){ - if(Query.size()) + if (Col.isPrimaryKey()) { + if (Query.size()) _extraFilters.insert(this->finalColName(Col), Query); break; } - for(auto FilterIter = _extraFilters.begin(); FilterIter != _extraFilters.end(); ++FilterIter){ - if(FilterIter->isValid() == false) + for (auto FilterIter = _extraFilters.begin(); FilterIter != _extraFilters.end(); ++FilterIter) { + if (FilterIter->isValid() == false) continue; const stuRelatedORMField& relatedORMField = this->SelectableColsMap[FilterIter.key()]; Filters.append(makeColName(this->Name, relatedORMField.Col) + "=?"); diff --git a/Interfaces/Helpers/PhoneHelper.cpp b/Interfaces/Helpers/PhoneHelper.cpp index 3a9725ec..c2e3cc5b 100644 --- a/Interfaces/Helpers/PhoneHelper.cpp +++ b/Interfaces/Helpers/PhoneHelper.cpp @@ -27,10 +27,8 @@ namespace Targoman::API::Helpers { -QString PhoneHelper::GetErrorTypeAsString(const i18n::phonenumbers::PhoneNumberUtil::ErrorType& _errorType) -{ - switch (_errorType) - { +QString PhoneHelper::GetErrorTypeAsString(const i18n::phonenumbers::PhoneNumberUtil::ErrorType& _errorType) { + switch (_errorType) { case i18n::phonenumbers::PhoneNumberUtil::ErrorType::INVALID_COUNTRY_CODE_ERROR: return "Invalid Country Code"; case i18n::phonenumbers::PhoneNumberUtil::ErrorType::NOT_A_NUMBER: @@ -46,8 +44,7 @@ QString PhoneHelper::GetErrorTypeAsString(const i18n::phonenumbers::PhoneNumberU } } -QString PhoneHelper::NormalizePhoneNumber(QString _number, const QString& _country) -{ +QString PhoneHelper::NormalizePhoneNumber(QString _number, const QString& _country) { i18n::phonenumbers::PhoneNumberUtil* phoneNumberUtil = i18n::phonenumbers::PhoneNumberUtil::GetInstance(); i18n::phonenumbers::PhoneNumber number_proto; diff --git a/Interfaces/Helpers/RESTClientHelper.cpp b/Interfaces/Helpers/RESTClientHelper.cpp index ed3ca478..b5382759 100644 --- a/Interfaces/Helpers/RESTClientHelper.cpp +++ b/Interfaces/Helpers/RESTClientHelper.cpp @@ -90,8 +90,7 @@ QVariant RESTClientHelper::callAPI( if (_outResponseHeaders != nullptr) *_outResponseHeaders = ResponseHeaders; - if (EncodedJWT != _JWT["encodedJWT"].toString()) - { + if (EncodedJWT != _JWT["encodedJWT"].toString()) { QJWT::extractAndDecryptPayload(EncodedJWT, _JWT); _JWT["encodedJWT"] = EncodedJWT; } @@ -132,8 +131,7 @@ QVariant RESTClientHelper::callAPI( }; bool HasForm = false; - if (_formFiles.isEmpty() == false) - { + if (_formFiles.isEmpty() == false) { HasForm = true; for (auto iter=_formFiles.begin(); iter!=_formFiles.end(); ++iter) CUrl.mime_addFile(iter.key(), iter.value().toString()); @@ -145,20 +143,15 @@ QVariant RESTClientHelper::callAPI( Opt[CURLOPT_FAILONERROR] = true; QStringList Headers; - if (HasForm) - { - if (_postOrFormFields.isEmpty() == false) - { + if (HasForm) { + if (_postOrFormFields.isEmpty() == false) { for (auto iter = _postOrFormFields.begin(); iter != _postOrFormFields.end(); ++iter) CUrl.mime_addData(iter.key(), iter.value().toString()); } - } - else - { + } else { Headers.append("Content-Type: application/json"); - switch (_method) - { + switch (_method) { case GET: case DELETE: break; @@ -174,8 +167,7 @@ QVariant RESTClientHelper::callAPI( Opt[CURLOPT_HTTPHEADER] = Headers; - switch (_method) - { + switch (_method) { case GET: Opt[CURLOPT_CUSTOMREQUEST] = "GET"; break; @@ -201,8 +193,7 @@ QVariant RESTClientHelper::callAPI( *_outResponseHeaders = ResponseHeaders; //replace JWT by x-auth-new-token - if (ResponseHeaders.contains("x-auth-new-token")) - { + if (ResponseHeaders.contains("x-auth-new-token")) { _encodedJWT = ResponseHeaders.value("x-auth-new-token").toString(); qDebug() << "**********************************" << "JWT replaced by" << endl @@ -212,8 +203,7 @@ QVariant RESTClientHelper::callAPI( //Account::instance()->addResponseHeader("x-auth-new-token", _encodedJWT); } - if (CUrl.lastError().isOk() == false) - { + if (CUrl.lastError().isOk() == false) { auto LastError = CUrl.lastError(); qDebug().noquote().nospace() << "-- CURL ERROR: (" << LastError.code() << ") " << LastError.text() << endl diff --git a/Interfaces/Helpers/SecurityHelper.cpp b/Interfaces/Helpers/SecurityHelper.cpp index 3bd820b4..19ad8609 100644 --- a/Interfaces/Helpers/SecurityHelper.cpp +++ b/Interfaces/Helpers/SecurityHelper.cpp @@ -29,8 +29,7 @@ namespace Targoman::API::Helpers { -const QString SecurityHelper::UUIDtoMD5() -{ +const QString SecurityHelper::UUIDtoMD5() { QByteArray data; data.append(QRandomGenerator::global()->generate()); diff --git a/Interfaces/Helpers/URLHelper.cpp b/Interfaces/Helpers/URLHelper.cpp index 366ed3c0..b8cf8950 100644 --- a/Interfaces/Helpers/URLHelper.cpp +++ b/Interfaces/Helpers/URLHelper.cpp @@ -27,8 +27,7 @@ namespace Targoman::API::Helpers { -QString URLHelper::domain(QString _url) -{ +QString URLHelper::domain(QString _url) { if (!_url.startsWith("http://") && !_url.startsWith("https://") && (_url.indexOf("://") < 0)) _url = "http://" + _url; @@ -42,8 +41,7 @@ QString URLHelper::domain(QString _url) return Domain; }; -QString URLHelper::addParameter(const QString &_url, const QString& _paramName, const QVariant& _value) -{ +QString URLHelper::addParameter(const QString &_url, const QString& _paramName, const QVariant& _value) { QUrl Url = QUrl(_url); QUrlQuery UrlQuery = QUrlQuery(Url); diff --git a/Interfaces/ORM/intfActionLogs.cpp b/Interfaces/ORM/intfActionLogs.cpp index 59ae3fbe..9c618520 100644 --- a/Interfaces/ORM/intfActionLogs.cpp +++ b/Interfaces/ORM/intfActionLogs.cpp @@ -50,10 +50,9 @@ intfActionLogs::intfActionLogs( { tblActionLogs::atlBy_usrID, R(AAA::AAASchema, "tblUser"), "usrID", "By_" }, } ) -{} +{ ; } -QVariant intfActionLogs::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant intfActionLogs::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { // Authorization::checkPriv(_JWT, { this->ModuleName + ":ActionLogs:CRUD~0100" }); Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); diff --git a/Interfaces/ObjectStorage/Gateways/gtwAWSS3.h b/Interfaces/ObjectStorage/Gateways/gtwAWSS3.h index 5f003b04..bc69b585 100644 --- a/Interfaces/ObjectStorage/Gateways/gtwAWSS3.h +++ b/Interfaces/ObjectStorage/Gateways/gtwAWSS3.h @@ -64,8 +64,7 @@ struct __static_s3_initializer__ { static inline bool Initialized = false; static inline SDKOptions options; - __static_s3_initializer__() - { + __static_s3_initializer__() { if (Initialized) return; @@ -81,8 +80,7 @@ struct __static_s3_initializer__ { Initialized = true; } - ~__static_s3_initializer__() - { + ~__static_s3_initializer__() { if (Initialized == false) return; diff --git a/Interfaces/ObjectStorage/ORM/ObjectStorage.cpp b/Interfaces/ObjectStorage/ORM/ObjectStorage.cpp index 827028bc..4123faff 100644 --- a/Interfaces/ObjectStorage/ORM/ObjectStorage.cpp +++ b/Interfaces/ObjectStorage/ORM/ObjectStorage.cpp @@ -37,8 +37,7 @@ TAPI_REGISTER_TARGOMAN_ENUM(Targoman::API::ObjectStorage::ORM, enuUploadGatewayS namespace Targoman::API::ObjectStorage::ORM { namespace Private { -void stuProcessUploadQueueInfo::fromVariantMap(const QVariantMap& _info) -{ +void stuProcessUploadQueueInfo::fromVariantMap(const QVariantMap& _info) { //Upload Queue SET_FIELD_FROM_VARIANT_MAP_SAME_NAME(this->, uquID , _info, tblUploadQueue); SET_FIELD_FROM_VARIANT_MAP_SAME_NAME(this->, uqu_uflID , _info, tblUploadQueue); @@ -104,7 +103,7 @@ intfUploadFiles::intfUploadFiles( ORM_RELATION_OF_UPDATER(tblUploadFiles::uflUpdatedBy_usrID), } ) -{} +{ ; } /******************************************************************/ /******************************************************************/ @@ -133,7 +132,7 @@ intfUploadQueue::intfUploadQueue( ORM_RELATION_OF_UPDATER(tblUploadQueue::uquUpdatedBy_usrID), } ) -{} +{ ; } /******************************************************************/ /******************************************************************/ @@ -178,16 +177,14 @@ intfUploadGateways::intfUploadGateways( ORM_RELATION_OF_UPDATER(tblUploadGateways::ugwUpdatedBy_usrID), } ) -{} +{ ; } -QVariant intfUploadGateways::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant intfUploadGateways::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); } -quint32 intfUploadGateways::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) -{ +quint32 intfUploadGateways::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PUT, this->moduleBaseName())); // if (_createInfo.contains(tblintfUploadGateways::ugwAllowedDomainName)) @@ -196,14 +193,12 @@ quint32 intfUploadGateways::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) return /*Targoman::API::Query::*/this->Create(*this, CREATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool intfUploadGateways::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool intfUploadGateways::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PATCH, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool intfUploadGateways::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool intfUploadGateways::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())); return /*Targoman::API::Query::*/this->DeleteByPks(*this, DELETE_METHOD_CALL_ARGS_INTERNAL_CALL); } diff --git a/Interfaces/ObjectStorage/ORM/ObjectStorage.h b/Interfaces/ObjectStorage/ORM/ObjectStorage.h index 4493b0ad..2f914bda 100644 --- a/Interfaces/ObjectStorage/ORM/ObjectStorage.h +++ b/Interfaces/ObjectStorage/ORM/ObjectStorage.h @@ -178,10 +178,10 @@ class intfUploadFiles : public intfSQLBasedModule stuObjectStorageConfigs(const stuObjectStorageConfigs &_other) : TempLocalStoragePath(_other.TempLocalStoragePath) - {} + { ; } stuObjectStorageConfigs(const QString &_localStoragePath) : TempLocalStoragePath(_localStoragePath) - {} + { ; } }; virtual stuObjectStorageConfigs getObjectStorageConfigs() const = 0; diff --git a/Interfaces/ObjectStorage/ObjectStorageManager.cpp b/Interfaces/ObjectStorage/ObjectStorageManager.cpp index 4bd14b1f..a06f97be 100644 --- a/Interfaces/ObjectStorage/ObjectStorageManager.cpp +++ b/Interfaces/ObjectStorage/ObjectStorageManager.cpp @@ -120,10 +120,8 @@ QVariantMap ObjectStorageManager::saveFiles( ) { QVariantMap Result; - foreach(auto _file, _files) - { - try - { + foreach(auto _file, _files) { + try { quint64 ID = saveFile( _currentUserID, _uploadFiles, @@ -132,9 +130,7 @@ QVariantMap ObjectStorageManager::saveFiles( _file ); Result.insert(_file.Name, ID); - } - catch (std::exception &exp) - { + } catch (std::exception &exp) { Result.insert(_file.Name, exp.what()); } } @@ -176,8 +172,7 @@ quint64 ObjectStorageManager::saveFile( QString FullPath = _objectStorageConfigs.TempLocalStoragePath; QDir FullPathDir(FullPath); - if (FullPathDir.exists() == false) - { + if (FullPathDir.exists() == false) { if (FullPathDir.mkpath(".") == false) throw exTargomanBase("Could not create storage folder.", ESTATUS_INTERNAL_SERVER_ERROR); } @@ -188,8 +183,7 @@ quint64 ObjectStorageManager::saveFile( //get mime type QString MimeType = _file.Mime; - if (MimeType.isEmpty()) - { + if (MimeType.isEmpty()) { QMimeDatabase MimeDB; QString MimeType = MimeDB.mimeTypeForFile(_file.TempName).name().toLower(); } @@ -206,8 +200,7 @@ quint64 ObjectStorageManager::saveFile( //save to tblUploadFiles quint64 UploadedFileID; quint16 QueueRowsCount; - try - { + try { QVariantMap SpOutVars = _uploadFiles.callSP("spUploadedFile_Create", { { "iFileName", _file.Name }, { "iFileUUID", FileUUID }, @@ -222,18 +215,14 @@ quint64 ObjectStorageManager::saveFile( UploadedFileID = SpOutVars.value("oUploadedFileID").toULongLong(); QueueRowsCount = SpOutVars.value("oQueueRowsCount").toUInt(); - } - catch (std::exception &exp) - { + } catch (std::exception &exp) { TargomanDebug(5, "ERROR: spUploadedFile_Create:" << exp.what()); throw; } //trigger async upload to storage(s) - try - { - if (QueueRowsCount > 0) - { + try { + if (QueueRowsCount > 0) { TargomanDebug(5, "before queue ObjectStorageManager::processQueue(" << UploadedFileID << ")"); QFuture ret = QtConcurrent::run( ObjectStorageManager::processQueue, @@ -251,9 +240,7 @@ quint64 ObjectStorageManager::saveFile( // bool rrr = ret.result(); #endif } - } - catch (std::exception &exp) - { + } catch (std::exception &exp) { TargomanDebug(5, "ERROR: concurrent run of upload file queue(" << UploadedFileID << "):" << exp.what()); //convert iQueueStatus to New for post processing by cron @@ -267,8 +254,7 @@ quint64 ObjectStorageManager::saveFile( return UploadedFileID; } -bool ObjectStorageManager::processQueue(const stuProcessQueueParams &_processQueueParams) -{ +bool ObjectStorageManager::processQueue(const stuProcessQueueParams &_processQueueParams) { TargomanDebug(5, "ObjectStorageManager::processQueue(" << _processQueueParams.UploadedFileID << ")"); _processQueueParams.UploadQueue.prepareFiltersList(); @@ -312,17 +298,13 @@ bool ObjectStorageManager::processQueue(const stuProcessQueueParams &_processQue QVariantList QueueItems; - try - { + try { QueueItems = Query.all({}, _processQueueParams.MaxItemsCount); - } - catch (std::exception &exp) - { + } catch (std::exception &exp) { TargomanDebug(5, "ERROR: fetching upload queue items:" << exp.what()); } - if (QueueItems.isEmpty()) - { + if (QueueItems.isEmpty()) { if (_processQueueParams.UploadedFileID > 0) UpdateQuery(_processQueueParams.UploadFiles) .setPksByPath(_processQueueParams.UploadedFileID) @@ -336,8 +318,7 @@ bool ObjectStorageManager::processQueue(const stuProcessQueueParams &_processQue //update Queue Status to Uploading QStringList UploadingQueueIDs; - foreach(QVariant Var, QueueItems) - { + foreach(QVariant Var, QueueItems) { Targoman::API::ObjectStorage::ORM::Private::stuProcessUploadQueueInfo QueueInfo; QueueInfo.fromVariantMap(Var.toMap()); QueueInfos.append(QueueInfo); @@ -345,8 +326,7 @@ bool ObjectStorageManager::processQueue(const stuProcessQueueParams &_processQue if (QueueInfo.uquStatus == enuUploadQueueStatus::New) UploadingQueueIDs.append(QString::number(QueueInfo.uquID)); } - if (UploadingQueueIDs.length()) - { + if (UploadingQueueIDs.length()) { UpdateQuery(_processQueueParams.UploadQueue) .set(tblUploadQueue::uquStatus, enuUploadQueueStatus::Uploading) .where({ tblUploadQueue::uquID, enuConditionOperator::In, UploadingQueueIDs.join(",") }) @@ -361,11 +341,9 @@ bool ObjectStorageManager::processQueue(const stuProcessQueueParams &_processQue // QStringList FailedFileIDs; QStringList FailedQueueIDs; - foreach(Targoman::API::ObjectStorage::ORM::Private::stuProcessUploadQueueInfo QueueInfo, QueueInfos) - { + foreach(Targoman::API::ObjectStorage::ORM::Private::stuProcessUploadQueueInfo QueueInfo, QueueInfos) { bool Stored = false; - try - { + try { Stored = ObjectStorageManager::storeFile( QueueInfo.ugwType, QueueInfo.ugwMetaInfo, @@ -373,40 +351,30 @@ bool ObjectStorageManager::processQueue(const stuProcessQueueParams &_processQue QueueInfo.uflFileUUID, QueueInfo.uflLocalFullFileName ); - } - catch (std::exception &exp) - { + } catch (std::exception &exp) { TargomanDebug(5, "ERROR: storing file to remote storage:" << exp.what()); } - if (Stored) - { - if (GatewayUploadedFileCount.contains(QueueInfo.ugwID)) - { + if (Stored) { + if (GatewayUploadedFileCount.contains(QueueInfo.ugwID)) { GatewayUploadedFileCount[QueueInfo.ugwID] += 1; GatewayUploadedFileSize[QueueInfo.ugwID] += QueueInfo.uflSize; - } - else - { + } else { GatewayUploadedFileCount.insert(QueueInfo.ugwID, 1); GatewayUploadedFileSize.insert(QueueInfo.ugwID, QueueInfo.uflSize); } // QList UploadedFileIDs; UploadedQueueIDs.append(QString::number(QueueInfo.uquID)); - } - else - { + } else { // QList FailedFileIDs; FailedQueueIDs.append(QString::number(QueueInfo.uquID)); } } //update gateway ststictics - if (GatewayUploadedFileCount.count()) - { - foreach(quint64 GatewayID, GatewayUploadedFileCount.keys()) - { + if (GatewayUploadedFileCount.count()) { + foreach(quint64 GatewayID, GatewayUploadedFileCount.keys()) { UpdateQuery(_processQueueParams.UploadGateways) .increament(tblUploadGateways::ugwCreatedFilesCount, GatewayUploadedFileCount[GatewayID]) .increament(tblUploadGateways::ugwCreatedFilesSize, GatewayUploadedFileSize[GatewayID]) @@ -417,16 +385,14 @@ bool ObjectStorageManager::processQueue(const stuProcessQueueParams &_processQue } //update queue - if (UploadedQueueIDs.length()) - { + if (UploadedQueueIDs.length()) { UpdateQuery(_processQueueParams.UploadQueue) .set(tblUploadQueue::uquStatus, enuUploadQueueStatus::Stored) .where({ tblUploadQueue::uquID, enuConditionOperator::In, UploadedQueueIDs.join(',') }) .execute(_processQueueParams.CurrentUserID); ; } - if (FailedQueueIDs.length()) - { + if (FailedQueueIDs.length()) { UpdateQuery(_processQueueParams.UploadQueue) .set(tblUploadQueue::uquStatus, enuUploadQueueStatus::New) .where({ tblUploadQueue::uquID, enuConditionOperator::In, FailedQueueIDs.join(',') }) @@ -450,8 +416,7 @@ bool ObjectStorageManager::storeFile( const QString &_fullFileName ) { - switch (_storageType) - { + switch (_storageType) { case enuUploadGatewayType::NFS: return Gateways::gtwNFS::storeFile( _metaInfo, diff --git a/Interfaces/ObjectStorage/ObjectStorageManager.h b/Interfaces/ObjectStorage/ObjectStorageManager.h index 189093f6..3eb1ccf5 100644 --- a/Interfaces/ObjectStorage/ObjectStorageManager.h +++ b/Interfaces/ObjectStorage/ObjectStorageManager.h @@ -119,7 +119,7 @@ class ObjectStorageManager UploadGateways(_uploadGateways), UploadedFileID(_uploadedFileID), MaxItemsCount(_maxItemsCount) - {} + { ; } }; static bool processQueue(const stuProcessQueueParams &_processQueueParams); diff --git a/Interfaces/Server/QJWT.cpp b/Interfaces/Server/QJWT.cpp index 1bb0cedb..889ea083 100644 --- a/Interfaces/Server/QJWT.cpp +++ b/Interfaces/Server/QJWT.cpp @@ -100,10 +100,8 @@ tmplConfigurable QJWT::RememberLoginTTL( thread_local static clsSimpleCrypt* SimpleCryptInstance = nullptr; -static clsSimpleCrypt* simpleCryptInstance() -{ - if (Q_UNLIKELY(!SimpleCryptInstance)) - { +static clsSimpleCrypt* simpleCryptInstance() { + if (Q_UNLIKELY(!SimpleCryptInstance)) { SimpleCryptInstance = new clsSimpleCrypt(QJWT::SimpleCryptKey.value()); SimpleCryptInstance->setIntegrityProtectionMode(clsSimpleCrypt::ProtectionHash); } @@ -181,8 +179,7 @@ void QJWT::extractAndDecryptPayload( if (_jWTPayload.empty()) throw exHTTPForbidden("Invalid JWT payload: empty object"); - if (_jWTPayload.contains("prv")) - { + if (_jWTPayload.contains("prv")) { QString Decrypted = simpleCryptInstance()->decryptToString(_jWTPayload.value("prv").toString()); if (Decrypted.isEmpty()) @@ -208,8 +205,7 @@ void QJWT::verifyJWT( QJWT::extractAndDecryptPayload(_jwt, _jWTPayload); // check client ip --------------- - if (_jWTPayload.contains("prv")) - { + if (_jWTPayload.contains("prv")) { QJsonObject PrivateObject = _jWTPayload["prv"].toObject(); if (PrivateObject.contains("cip") && (PrivateObject["cip"].toString() != _remoteIP)) @@ -227,10 +223,8 @@ void QJWT::verifyJWT( throw exJWTExpired("JWT expired"); } -QByteArray QJWT::hash(const QByteArray& _data) -{ - switch (QJWT::HashAlgorithm.value()) - { +QByteArray QJWT::hash(const QByteArray& _data) { + switch (QJWT::HashAlgorithm.value()) { case enuJWTHashAlgs::HS256: return QMessageAuthenticationCode::hash(_data, QJWT::Secret.value().toUtf8(), QCryptographicHash::Sha256); diff --git a/Interfaces/Server/clsSimpleCrypt.cpp b/Interfaces/Server/clsSimpleCrypt.cpp index 9305273b..07a89563 100644 --- a/Interfaces/Server/clsSimpleCrypt.cpp +++ b/Interfaces/Server/clsSimpleCrypt.cpp @@ -31,7 +31,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -clsSimpleCrypt::clsSimpleCrypt(): +clsSimpleCrypt::clsSimpleCrypt() : m_key(0), m_compressionMode(CompressionAuto), m_protectionMode(ProtectionChecksum), @@ -40,7 +40,7 @@ clsSimpleCrypt::clsSimpleCrypt(): qsrand(uint(QDateTime::currentMSecsSinceEpoch() & 0xFFFF)); } -clsSimpleCrypt::clsSimpleCrypt(quint64 key): +clsSimpleCrypt::clsSimpleCrypt(quint64 key) : m_key(key), m_compressionMode(CompressionAuto), m_protectionMode(ProtectionChecksum), @@ -50,14 +50,12 @@ clsSimpleCrypt::clsSimpleCrypt(quint64 key): splitKey(); } -void clsSimpleCrypt::setKey(quint64 key) -{ +void clsSimpleCrypt::setKey(quint64 key) { m_key = key; splitKey(); } -void clsSimpleCrypt::splitKey() -{ +void clsSimpleCrypt::splitKey() { m_keyParts.clear(); m_keyParts.resize(8); for (int i=0;i<8;i++) { @@ -69,21 +67,18 @@ void clsSimpleCrypt::splitKey() } } -QByteArray clsSimpleCrypt::encryptToByteArray(const QString& _plaintext) -{ +QByteArray clsSimpleCrypt::encryptToByteArray(const QString& _plaintext) { QByteArray plaintextArray = _plaintext.toUtf8(); return encryptToByteArray(plaintextArray); } -QByteArray clsSimpleCrypt::encryptToByteArray(QByteArray _plaintext) -{ +QByteArray clsSimpleCrypt::encryptToByteArray(QByteArray _plaintext) { if (m_keyParts.isEmpty()) { qWarning() << "No key set."; m_lastError = ErrorNoKeySet; return QByteArray(); } - QByteArray ba = _plaintext; CryptoFlags flags = CryptoFlagNone; @@ -135,23 +130,20 @@ QByteArray clsSimpleCrypt::encryptToByteArray(QByteArray _plaintext) return resultArray; } -QString clsSimpleCrypt::encryptToString(const QString& _plaintext) -{ +QString clsSimpleCrypt::encryptToString(const QString& _plaintext) { QByteArray plaintextArray = _plaintext.toUtf8(); QByteArray cypher = encryptToByteArray(plaintextArray); QString cypherString = QString::fromLatin1(cypher.toBase64()); return cypherString; } -QString clsSimpleCrypt::encryptToString(QByteArray plaintext) -{ +QString clsSimpleCrypt::encryptToString(QByteArray plaintext) { QByteArray cypher = encryptToByteArray(plaintext); QString cypherString = QString::fromLatin1(cypher.toBase64()); return cypherString; } -QString clsSimpleCrypt::decryptToString(const QString& _cyphertext) -{ +QString clsSimpleCrypt::decryptToString(const QString& _cyphertext) { QByteArray cyphertextArray = QByteArray::fromBase64(_cyphertext.toLatin1()); QByteArray plaintextArray = decryptToByteArray(cyphertextArray); QString plaintext = QString::fromUtf8(plaintextArray, plaintextArray.size()); @@ -159,24 +151,21 @@ QString clsSimpleCrypt::decryptToString(const QString& _cyphertext) return plaintext; } -QString clsSimpleCrypt::decryptToString(QByteArray cypher) -{ +QString clsSimpleCrypt::decryptToString(QByteArray cypher) { QByteArray ba = decryptToByteArray(cypher); QString plaintext = QString::fromUtf8(ba, ba.size()); return plaintext; } -QByteArray clsSimpleCrypt::decryptToByteArray(const QString& _cyphertext) -{ +QByteArray clsSimpleCrypt::decryptToByteArray(const QString& _cyphertext) { QByteArray cyphertextArray = QByteArray::fromBase64(_cyphertext.toLatin1()); QByteArray ba = decryptToByteArray(cyphertextArray); return ba; } -QByteArray clsSimpleCrypt::decryptToByteArray(QByteArray _cypher) -{ +QByteArray clsSimpleCrypt::decryptToByteArray(QByteArray _cypher) { if (m_keyParts.isEmpty()) { qWarning() << "No key set."; m_lastError = ErrorNoKeySet; diff --git a/Interfaces/Test/testBase.hpp b/Interfaces/Test/testBase.hpp index b76b0724..a16a2747 100644 --- a/Interfaces/Test/testBase.hpp +++ b/Interfaces/Test/testBase.hpp @@ -30,12 +30,12 @@ class testBase: public clsBaseTest Q_OBJECT public: - testBase(const QString &_dbPrefix) : clsBaseTest(_dbPrefix) {} + testBase(const QString &_dbPrefix) : clsBaseTest(_dbPrefix) { ; } private slots: - void initTestCase() {} - void cleanupTestCase() {} - void openAPI() {} + void initTestCase() { ; } + void cleanupTestCase() { ; } + void openAPI() { ; } }; #endif // TESTBASE_HPP diff --git a/Interfaces/Test/testCommon.hpp b/Interfaces/Test/testCommon.hpp index 55ef991a..c01c5e20 100644 --- a/Interfaces/Test/testCommon.hpp +++ b/Interfaces/Test/testCommon.hpp @@ -73,26 +73,20 @@ extern quint64 gUserID; extern quint64 gAdminUserID; extern QVariant gInvalid; -inline char **findDBPrefixFromArguments(int argc, char *argv[], QString &_dbPrefix, int &_outArgsCount) -{ +inline char **findDBPrefixFromArguments(int argc, char *argv[], QString &_dbPrefix, int &_outArgsCount) { std::list commandList; commandList.push_back(argv[0]); - if (argc > 1) - { - for (int idx=1; idx 1) { + for (int idx=1; idx idx) - { + ) { + if (argc-1 > idx) { _dbPrefix = argv[idx+1]; ++idx; } - } - else + } else commandList.push_back(argv[idx]); } } @@ -100,8 +94,7 @@ inline char **findDBPrefixFromArguments(int argc, char *argv[], QString &_dbPref char **OutArgs = (char**)malloc(sizeof(char*) * commandList.size()); _outArgsCount = 0; - for(std::list::iterator it=commandList.begin(); it!=commandList.end(); ++it) - { + for (std::list::iterator it=commandList.begin(); it!=commandList.end(); ++it) { char *item = new char[strlen((*it).c_str()) + 1]; strcpy(item, (*it).c_str()); OutArgs[_outArgsCount] = item; @@ -114,12 +107,11 @@ inline char **findDBPrefixFromArguments(int argc, char *argv[], QString &_dbPref class clsBaseTest : public QObject { public: - clsBaseTest(const QString &_dbPrefix) : DBPrefix(_dbPrefix) {} + clsBaseTest(const QString &_dbPrefix) : DBPrefix(_dbPrefix) { ; } QString DBPrefix; protected: - void initUnitTestData(bool _createUsers = true, bool _deleteOldTestData = true) - { + void initUnitTestData(bool _createUsers = true, bool _deleteOldTestData = true) { if (_deleteOldTestData) cleanupUnitTestData(); // deleteOldTestData(); @@ -193,8 +185,7 @@ class clsBaseTest : public QObject const QVariantMap& _postOrFormFields = {}, const QVariantMap& _formFiles = {}, QVariantMap *_outResponseHeaders = nullptr - ) - { + ) { QVariantMap ResponseHeaders; QVariant Result = RESTClientHelper::callAPI( @@ -212,8 +203,7 @@ class clsBaseTest : public QObject << " Response Headers:" << ResponseHeaders << endl << " Result:" << Result; - if (ResponseHeaders.contains("x-auth-new-token")) - { + if (ResponseHeaders.contains("x-auth-new-token")) { // QString NewJWT = ResponseHeaders.value("x-auth-new-token").toString(); // qDebug() << ">>>>>>>>>>>>>>>> JWT CHANGED TO" << endl << NewJWT; @@ -237,8 +227,7 @@ class clsBaseTest : public QObject const QVariantMap& _postOrFormFields = {}, const QVariantMap& _formFiles = {}, QVariantMap *_outResponseHeaders = nullptr - ) - { + ) { return callAPI( false, _method, @@ -257,8 +246,7 @@ class clsBaseTest : public QObject const QVariantMap& _postOrFormFields = {}, const QVariantMap& _formFiles = {}, QVariantMap *_outResponseHeaders = nullptr - ) - { + ) { return callAPI( true, _method, @@ -271,8 +259,7 @@ class clsBaseTest : public QObject } private: - void deleteOldTestData() //bool _createUsers=false) - { + void deleteOldTestData() { //bool _createUsers=false) clsDAC DAC("AAA"); DAC.execQuery("", QString("DELETE FROM %1AAA.tblAPITokens WHERE aptToken IN(?,?)").arg(this->DBPrefix), { UT_NormalToken, UT_AdminToken }); diff --git a/ModuleHelpers/NLP/FormalityChecker.cpp b/ModuleHelpers/NLP/FormalityChecker.cpp index 6076b42b..05f433d1 100644 --- a/ModuleHelpers/NLP/FormalityChecker.cpp +++ b/ModuleHelpers/NLP/FormalityChecker.cpp @@ -29,8 +29,7 @@ namespace Apps { using namespace Common; using namespace Targoman::Common::Configuration; -QString gConfigs::Classifier::makeConfig(const QString& _name) -{ +QString gConfigs::Classifier::makeConfig(const QString& _name) { return "/Classifier/" + _name; } diff --git a/ModuleHelpers/NLP/FormalityChecker.h b/ModuleHelpers/NLP/FormalityChecker.h index 9eb14bdd..3fdb4d4d 100644 --- a/ModuleHelpers/NLP/FormalityChecker.h +++ b/ModuleHelpers/NLP/FormalityChecker.h @@ -49,10 +49,10 @@ class Q_DECL_EXPORT FormalityChecker { public: instanceGetter(FormalityChecker) - inline QString check(const QString _lang, QString _text){return this->FCInstance->check(_lang, _text);} + inline QString check(const QString _lang, QString _text) {return this->FCInstance->check(_lang, _text);} private: - FormalityChecker() : FCInstance(new Targoman::Apps::clsFormalityChecker) {} + FormalityChecker() : FCInstance(new Targoman::Apps::clsFormalityChecker) { ; } TAPI_DISABLE_COPY(FormalityChecker) private: diff --git a/ModuleHelpers/NLP/TextProcessor.hpp b/ModuleHelpers/NLP/TextProcessor.hpp index 2a5c9a5e..76739485 100644 --- a/ModuleHelpers/NLP/TextProcessor.hpp +++ b/ModuleHelpers/NLP/TextProcessor.hpp @@ -39,7 +39,7 @@ class TextProcessor public: instanceGetter (TextProcessor) - inline void init() { //QSharedPointer _configSettings = QSharedPointer()){ + inline void init() { //QSharedPointer _configSettings = QSharedPointer()) { NLPLibs::TargomanTextProcessor::instance().init( Targoman::Common::Configuration::ConfigManager::instance().configSettings()); } @@ -74,7 +74,7 @@ class TextProcessor } private: - TextProcessor(){} + TextProcessor() { ; } TAPI_DISABLE_COPY(TextProcessor) }; diff --git a/Modules/Account/functionalTest/ORM/actionLogs.hpp b/Modules/Account/functionalTest/ORM/actionLogs.hpp index 2e2184bc..abcb5fa2 100644 --- a/Modules/Account/functionalTest/ORM/actionLogs.hpp +++ b/Modules/Account/functionalTest/ORM/actionLogs.hpp @@ -32,7 +32,7 @@ class testActionLogs: public clsBaseTest Q_OBJECT private slots: - void unprivActionLogs(){ + void unprivActionLogs() { QVERIFY(callUserAPI(RESTClientHelper::GET, "Account/ActionLogs").toString().isEmpty()); } }; diff --git a/Modules/Account/functionalTest/ORM/activeSessions.hpp b/Modules/Account/functionalTest/ORM/activeSessions.hpp index 29872979..30a1e3f4 100644 --- a/Modules/Account/functionalTest/ORM/activeSessions.hpp +++ b/Modules/Account/functionalTest/ORM/activeSessions.hpp @@ -32,7 +32,7 @@ class testActiveSessions: public clsBaseTest Q_OBJECT private slots: - void ActiveSessions_GET_Unpriviledged(){ + void ActiveSessions_GET_Unpriviledged() { QVERIFY(callUserAPI(RESTClientHelper::GET, QString("Account/ActiveSessions/")).toString().isEmpty()); QVERIFY(callUserAPI(RESTClientHelper::GET, QString("Account/ActiveSessions/%1").arg(clsJWT(gJWT).session()), { @@ -46,7 +46,7 @@ private slots: QVERIFY(callUserAPI(RESTClientHelper::DELETE, QString("Account/ActiveSessions/%1").arg(clsJWT(gJWT).session())).toBool() == false); } - void ActiveSessions_GET_Admin(){ + void ActiveSessions_GET_Admin() { QVERIFY(callAdminAPI(RESTClientHelper::GET, QString("Account/ActiveSessions/")).toMap().value("rows").toList().size() > 0); QVERIFY(callAdminAPI(RESTClientHelper::DELETE, QString("Account/ActiveSessions/%1").arg(clsJWT(gJWT).session())).toBool()); } diff --git a/Modules/Account/functionalTest/ORM/roles.hpp b/Modules/Account/functionalTest/ORM/roles.hpp index 600dd3bb..92cede8a 100644 --- a/Modules/Account/functionalTest/ORM/roles.hpp +++ b/Modules/Account/functionalTest/ORM/roles.hpp @@ -32,13 +32,13 @@ class testRoles: public clsBaseTest Q_OBJECT private slots: - void Roles_CREATE_Unprivileged(){ + void Roles_CREATE_Unprivileged() { QVERIFY(callUserAPI(RESTClientHelper::PUT, QString("Account/Roles/"),{},{ {"rolName", UT_ServiceRoleName}, }) == gInvalid); } - void Roles_CREATE_Admin(){ + void Roles_CREATE_Admin() { QVERIFY(callAdminAPI(RESTClientHelper::PUT, QString("Account/Roles/"),{},{ {"rolName", UT_ServiceRoleName}, }) == gInvalid); @@ -60,13 +60,13 @@ private slots: }).toUInt()) > 0); } - void Roles_UPDATE_Unprivileged(){ + void Roles_UPDATE_Unprivileged() { QVERIFY(callUserAPI(RESTClientHelper::PATCH, QString("Account/Roles/%1").arg(gServiceRoleID),{},{ {"rolPrivileges", QJsonObject({{UT_ServiceName,QJsonObject({{"All", 1}})}})} }) == gInvalid); } - void Roles_UPDATE_Admin(){ + void Roles_UPDATE_Admin() { QVERIFY(callAdminAPI(RESTClientHelper::PATCH, QString("Account/Roles/%1").arg(gServiceRoleID),{},{ }) == gInvalid); QVERIFY(callAdminAPI(RESTClientHelper::PATCH, QString("Account/Roles/%1").arg(gServiceRoleID),{},{ @@ -83,16 +83,16 @@ private slots: }).toBool()); } - void Roles_DELETE_Unprivileged(){ + void Roles_DELETE_Unprivileged() { QVERIFY(callUserAPI(RESTClientHelper::DELETE, QString("Account/Roles/%1").arg(gServiceRoleID)) == gInvalid); } - void Roles_DELETE_Admin(){ + void Roles_DELETE_Admin() { QVERIFY(callAdminAPI(RESTClientHelper::DELETE, QString("Account/Roles/")) == gInvalid); QVERIFY(callAdminAPI(RESTClientHelper::DELETE, QString("Account/Roles/%1").arg(gServiceRoleID)).toBool()); } - void Roles_GET_Unpriviledged(){ + void Roles_GET_Unpriviledged() { QVERIFY(callUserAPI(RESTClientHelper::GET, QString("Account/Roles/")) == gInvalid); QVERIFY(callUserAPI(RESTClientHelper::GET, QString("Account/Roles/%1").arg(gServiceRoleID), { @@ -100,7 +100,7 @@ private slots: }) == gInvalid); } - void Roles_GET_Admin(){ + void Roles_GET_Admin() { QVERIFY(callAdminAPI(RESTClientHelper::GET, QString("Account/Roles/"),{{"cols", "rolName"}}).toMap().size()); QVERIFY(callAdminAPI(RESTClientHelper::GET, QString("Account/Roles/%1").arg(gServiceRoleID), { diff --git a/Modules/Account/functionalTest/ORM/service.hpp b/Modules/Account/functionalTest/ORM/service.hpp index bf1c94d3..3739f436 100644 --- a/Modules/Account/functionalTest/ORM/service.hpp +++ b/Modules/Account/functionalTest/ORM/service.hpp @@ -31,13 +31,13 @@ class testService: public clsBaseTest Q_OBJECT private slots: - void Service_CREATE_Unpriviledged(){ + void Service_CREATE_Unpriviledged() { QVERIFY(callUserAPI(RESTClientHelper::PUT, QString("Account/Service/"),{},{ {"svcName", UT_ServiceName}, }) == gInvalid); } - void Service_CREATE_Admin(){ + void Service_CREATE_Admin() { QVERIFY(callAdminAPI(RESTClientHelper::PUT, QString("Account/Service/"),{},{ {"svcName", UT_ServiceName}, }) == gInvalid); @@ -51,23 +51,23 @@ private slots: }).toUInt()) > 0); } - void Service_UPDATE_Unprivileged(){ + void Service_UPDATE_Unprivileged() { QVERIFY(callUserAPI(RESTClientHelper::PATCH, QString("Account/Service/%1").arg(gServiceID),{},{ {"svcStatus", "Removed"} }) == gInvalid); } - void Service_UPDATE_Admin(){ + void Service_UPDATE_Admin() { QVERIFY(callAdminAPI(RESTClientHelper::PATCH, QString("Account/Service/%1").arg(gServiceID),{},{ {"svcStatus", "Removed"} }).toBool()); } - void Service_DELETE_Unprivileged(){ + void Service_DELETE_Unprivileged() { QVERIFY(callUserAPI(RESTClientHelper::DELETE, QString("Account/Service/%1").arg(gServiceID)) == gInvalid); } - void Service_DELETE_Admin(){ + void Service_DELETE_Admin() { QVERIFY(callAdminAPI(RESTClientHelper::DELETE, QString("Account/Service/")) == gInvalid); QVERIFY(callAdminAPI(RESTClientHelper::DELETE, QString("Account/Service/%1").arg(gServiceID)).toBool() == false); QVERIFY(callAdminAPI(RESTClientHelper::PATCH, QString("Account/Service/%1").arg(gServiceID),{},{ @@ -79,14 +79,14 @@ private slots: }).toBool()); } - void Service_CREATE_recreate(){ + void Service_CREATE_recreate() { QVERIFY(callAdminAPI(RESTClientHelper::PUT, QString("Account/Service/"),{},{ {"svcName", UT_ServiceName}, {"svc_rolID", gServiceRoleID}, }) == gInvalid); } - void Service_GET_Unpriviledged(){ + void Service_GET_Unpriviledged() { QVERIFY(callUserAPI(RESTClientHelper::GET, QString("Account/Service/")).toMap().isEmpty()); QVERIFY(callUserAPI(RESTClientHelper::GET, QString("Account/Service/%1").arg(gServiceID), { @@ -94,7 +94,7 @@ private slots: }) == gInvalid); } - void Service_GET_Admin(){ + void Service_GET_Admin() { QVERIFY(callAdminAPI(RESTClientHelper::GET, QString("Account/Service/"),{{"cols", "svcName"}}).toMap().size()); QVERIFY(callAdminAPI(RESTClientHelper::GET, QString("Account/Service/%1").arg(gServiceID), { diff --git a/Modules/Account/functionalTest/ORM/tokens.hpp b/Modules/Account/functionalTest/ORM/tokens.hpp index 269f05ba..b0b029fd 100644 --- a/Modules/Account/functionalTest/ORM/tokens.hpp +++ b/Modules/Account/functionalTest/ORM/tokens.hpp @@ -31,13 +31,13 @@ class testAPITokens: public clsBaseTest Q_OBJECT private slots: - void APITokens_CREATE_Unpriviledged(){ + void APITokens_CREATE_Unpriviledged() { QVERIFY(callUserAPI(RESTClientHelper::PUT, QString("Account/APITokens/"),{},{ {"aptToken", UT_NormalToken}, }) == gInvalid); } - void APITokens_CREATE_Admin(){ + void APITokens_CREATE_Admin() { QVERIFY(callAdminAPI(RESTClientHelper::PUT, QString("Account/APITokens/"),{},{ {"aptToken", UT_NormalToken}, }) == gInvalid); @@ -76,7 +76,7 @@ private slots: }).toUInt()) > 0); } - void APITokens_UPDATE_Unprivileged(){ + void APITokens_UPDATE_Unprivileged() { QVERIFY(callUserAPI(RESTClientHelper::PATCH, QString("Account/APITokens/%1").arg(gAPITokenID),{},{ {"aptStatus", "Removed"} })== gInvalid); @@ -85,18 +85,18 @@ private slots: })== gInvalid); } - void APITokens_UPDATE_Admin(){ + void APITokens_UPDATE_Admin() { QVERIFY(callAdminAPI(RESTClientHelper::PATCH, QString("Account/APITokens/%1").arg(gAPIAdminTokenID),{},{ {"aptStatus", "Removed"} }).toBool()); } - void APITokens_DELETE_Unprivileged(){ + void APITokens_DELETE_Unprivileged() { QVERIFY(callUserAPI(RESTClientHelper::DELETE, QString("Account/APITokens/%1").arg(gAPIAdminTokenID)).toBool() == false); QVERIFY(callUserAPI(RESTClientHelper::DELETE, QString("Account/APITokens/%1").arg(gAPITokenID)).toBool()); } - void APITokens_DELETE_Admin(){ + void APITokens_DELETE_Admin() { QVERIFY(callAdminAPI(RESTClientHelper::DELETE, QString("Account/APITokens/")) == gInvalid); QVERIFY(callAdminAPI(RESTClientHelper::DELETE, QString("Account/APITokens/%1").arg(gAPITokenID)).toBool() == false); QVERIFY(callAdminAPI(RESTClientHelper::PATCH, QString("Account/APITokens/%1").arg(gAPITokenID),{},{ @@ -108,7 +108,7 @@ private slots: }).toBool()); } - void APITokens_CREATE_recreate(){ + void APITokens_CREATE_recreate() { QVERIFY(callAdminAPI(RESTClientHelper::PUT, QString("Account/APITokens/"),{},{ {"aptToken", UT_NormalToken}, {"apt_svcID", gServiceID}, @@ -116,13 +116,13 @@ private slots: }) == gInvalid); } - void APITokens_GET_Unpriviledged(){ + void APITokens_GET_Unpriviledged() { QVERIFY(callUserAPI(RESTClientHelper::GET, QString("Account/APITokens/")).toMap().size() == 1); QVERIFY(callUserAPI(RESTClientHelper::GET, QString("Account/APITokens/%1").arg(gAPITokenID), {{"cols", "aptToken"}}).toMap().value("aptToken") == UT_NormalToken); QVERIFY(callUserAPI(RESTClientHelper::GET, QString("Account/APITokens/%1").arg(gAPIAdminTokenID), {{"cols", "aptToken"}}).toMap().isEmpty()); } - void APITokens_GET_Admin(){ + void APITokens_GET_Admin() { QVERIFY(callAdminAPI(RESTClientHelper::GET, QString("Account/APITokens/"),{{"cols", "aptToken"}}).toMap().size()); QVERIFY(callUserAPI(RESTClientHelper::GET, QString("Account/APITokens/%1").arg(gAPITokenID), {{"cols", "aptToken"}}).toMap().value("aptToken") == UT_NormalToken); QVERIFY(callUserAPI(RESTClientHelper::GET, QString("Account/APITokens/%1").arg(gAPIAdminTokenID), {{"cols", "aptToken"}}).toMap().value("aptToken") == UT_AdminToken); diff --git a/Modules/Account/functionalTest/main.cpp b/Modules/Account/functionalTest/main.cpp index 06ae4d77..7252aa8d 100644 --- a/Modules/Account/functionalTest/main.cpp +++ b/Modules/Account/functionalTest/main.cpp @@ -33,8 +33,7 @@ TAPI_MARSHAL_TEST_VARIABLES /* //https://cpp.hotexamples.com/examples/-/QString/toLongLong/cpp-qstring-tolonglong-method-examples.html -QVariant readNumber(const QString& _str, bool *ok) -{ +QVariant readNumber(const QString& _str, bool *ok) { //m_settings->locale() QString negativeSign = "-"; QString decimalSymbol = "."; @@ -118,18 +117,15 @@ QVariant readNumber(const QString& _str, bool *ok) return isInt ? QVariant(tot.toLongLong(ok)) : QVariant(tot.toDouble(ok)); } -QGenericArgument makeGenericArgument(const QVariant& _val, const QByteArray& _paramName, void** _argStorage) -{ +QGenericArgument makeGenericArgument(const QVariant& _val, const QByteArray& _paramName, void** _argStorage) { bool Result = true; *_argStorage = new quint32; quint32 ConvertedVal; - if (_val.userType() == QMetaType::QString) - { + if (_val.userType() == QMetaType::QString) { QString StrVal = _val.toString(); ConvertedVal = static_cast(readNumber(StrVal, &Result).toUInt(&Result)); - } - else + } else ConvertedVal = static_cast(_val.toUInt(&Result)); *(reinterpret_cast(*_argStorage)) = ConvertedVal; @@ -140,8 +136,7 @@ QGenericArgument makeGenericArgument(const QVariant& _val, const QByteArray& _pa return QGenericArgument("quint32", *_argStorage); } -QGenericArgument makeGenericArgument_NULLABLE(const QVariant& _val, const QByteArray& _paramName, void** _argStorage) -{ +QGenericArgument makeGenericArgument_NULLABLE(const QVariant& _val, const QByteArray& _paramName, void** _argStorage) { bool Result = true; *_argStorage = new NULLABLE_TYPE(quint32); @@ -154,8 +149,7 @@ QGenericArgument makeGenericArgument_NULLABLE(const QVariant& _val, const QByteA return QGenericArgument("quint32", *_argStorage); } -void testMakeGenericArgument() -{ +void testMakeGenericArgument() { QVariant _val0 = "2.05762e+09"; QByteArray _paramName0 = "hello 1"; @@ -170,9 +164,9 @@ void testMakeGenericArgument() void* _argStorage1; QGenericArgument aaa1 = makeGenericArgument_NULLABLE(_val1, _paramName1, &_argStorage1); } -/**/ -int main(int _argc, char *_argv[]) -{ +*/ + +int main(int _argc, char *_argv[]) { // testMakeGenericArgument(); return 0; qDebug() << "--------------------------------------------------"; qDebug() << "-- test module: Account --------------------------"; @@ -209,8 +203,7 @@ int main(int _argc, char *_argv[]) // if (BreakOnFirstFail && !FailedTests) FailedTests += QTest::qExec(new testRoles(DBPrefix), progArgsCount, progArgs); // if (BreakOnFirstFail && !FailedTests) FailedTests += QTest::qExec(new testService(DBPrefix), progArgsCount, progArgs); // if (BreakOnFirstFail && !FailedTests) FailedTests += QTest::qExec(new testAPITokens(DBPrefix), progArgsCount, progArgs); - } - catch(std::exception &e) { + } catch (std::exception &e) { qDebug()< 0); } - void ApproveMobile_And_Login_0999_888_1010() - { + void ApproveMobile_And_Login_0999_888_1010() { clsDAC DAC; QJsonObject AprInfo = DAC.execQuery("", "SELECT aprID" @@ -150,8 +147,7 @@ private slots: QVERIFY(clsJWT(gJWT).usrStatus() == TAPI::enuUserStatus::Active); } - void Logout__0999_888_1010() - { + void Logout__0999_888_1010() { QVERIFY(callUserAPI(RESTClientHelper::POST, "Account/logout").toBool()); gEncodedJWT = ""; @@ -159,8 +155,7 @@ private slots: } //------------------------------------------------------- - void Signup() - { + void Signup() { //df6d2338b2b8fce1ec2f6dda0a630eb0 # 987 QVERIFY((gUserID = callUserAPI(RESTClientHelper::PUT, "Account/signup", {}, { @@ -193,8 +188,7 @@ private slots: DAC.execQuery("", "UPDATE tblUser SET tblUser.usr_rolID=? WHERE tblUser.usrID=?", {UT_AdminRoleID, gAdminUserID}); } - void ResendEmailApproveCode() - { + void ResendEmailApproveCode() { QVariant Result = callUserAPI(RESTClientHelper::POST, "Account/resendApprovalCode", {}, @@ -204,8 +198,7 @@ private slots: QVERIFY(Result.toBool()); } - void ApprovalRequest_timerInfo_before_send() - { + void ApprovalRequest_timerInfo_before_send() { QVariant Result = callUserAPI(RESTClientHelper::POST, "Account/ApprovalRequest/timerInfo", {}, @@ -216,8 +209,7 @@ private slots: QVERIFY(Result.isValid() == false); } - void ApprovalRequest_timerInfo_after_send() - { + void ApprovalRequest_timerInfo_after_send() { clsDAC DAC; DAC.execQuery("", "UPDATE tblApprovalRequest SET aprStatus = 'S', aprSentDate = DATE_SUB(NOW(), INTERVAL 10 SECOND) WHERE apr_usrID=?", {gUserID}); @@ -231,9 +223,8 @@ private slots: qDebug() << Result; QVERIFY(Result.isValid()); } -//private: - void ApproveEmail() - { + + void ApproveEmail() { clsDAC DAC; QString Code = DAC.execQuery("", "SELECT aprApprovalCode" @@ -260,8 +251,7 @@ private slots: }); } - void ApproveAdminEmail() - { + void ApproveAdminEmail() { clsDAC DAC; QString Code = DAC.execQuery("", "SELECT aprApprovalCode FROM tblApprovalRequest WHERE apr_usrID=?", {gAdminUserID}).toJson(true).object().value("aprApprovalCode").toString(); @@ -278,8 +268,7 @@ private slots: }); } - void Login() - { + void Login() { //5d12d36cd5f66fe3e72f7b03cbb75333 = MD5(1234 + df6d2338b2b8fce1ec2f6dda0a630eb0 # 987) QVariant Result = callUserAPI(RESTClientHelper::POST, "Account/login",{}, { @@ -297,21 +286,21 @@ private slots: QVERIFY(clsJWT(gJWT).usrStatus() == TAPI::enuUserStatus::Active); } - void Logout(){ + void Logout() { QVERIFY(callUserAPI(RESTClientHelper::POST, "Account/logout").toBool()); gEncodedJWT = ""; gJWT = {}; } -// void loginAsGuest(){ +// void loginAsGuest() { // QVERIFY((callUserAPI(RESTClientHelper::POST, // "Account/loginAsGuest",{}, { // {"sessionInfo", "{\"a\":1}"}, // }).toString()).size()); // } - void LoginAgain(){ + void LoginAgain() { //5d12d36cd5f66fe3e72f7b03cbb75333 = MD5(1234 + df6d2338b2b8fce1ec2f6dda0a630eb0 # 987) QVariant Result = callUserAPI(RESTClientHelper::POST, "Account/login",{}, { @@ -337,14 +326,14 @@ private slots: gAdminJWT = QJsonDocument::fromJson(QByteArray::fromBase64(gEncodedAdminJWT.split('.').at(1).toLatin1())).object(); } -// void RefreshJWT(){ +// void RefreshJWT() { // QJsonObject MultiJWT; // QVERIFY((MultiJWT = callRefreshAPI().toJsonObject()).size()); // gEncodedJWT = MultiJWT.value("ssn").toString(); // } - void CreateForgotPasswordLink(){ + void CreateForgotPasswordLink() { QVERIFY(callUserAPI(RESTClientHelper::POST, "Account/createForgotPasswordLink",{}, { {"emailOrMobile", UT_UserEmail}, @@ -352,7 +341,7 @@ private slots: }).toBool()); } - void ChangePassByUUID(){ + void ChangePassByUUID() { clsDAC DAC; QString Code = DAC.execQuery("", "SELECT fprUUID FROM tblForgotPassRequest WHERE fpr_usrID=?", {gUserID}).toJson(true).object().value("fprUUID").toString(); @@ -371,7 +360,7 @@ private slots: //d769dd673f86addfe039dc2d2dab4f73 = MD5(1234 + 827ccb0eea8a706c4c34a16891f84e7b # 12345) //df6d2338b2b8fce1ec2f6dda0a630eb0 # 987 - void ChangePass(){ + void ChangePass() { QVERIFY(callUserAPI(RESTClientHelper::POST, "Account/changePass", {}, { { "oldPass", "d769dd673f86addfe039dc2d2dab4f73" }, @@ -380,8 +369,7 @@ private slots: }).toBool()); } - void ResendMobileApproveCode() - { + void ResendMobileApproveCode() { clsDAC DAC; try { @@ -408,13 +396,12 @@ private slots: { "emailOrMobile", "+989998882020" }, }); QVERIFY(Result.toBool()); - } - catch(std::exception &e) { + } catch (std::exception &e) { QFAIL (e.what()); } } - void ApproveMobile(){ + void ApproveMobile() { clsDAC DAC; try { @@ -445,7 +432,7 @@ private slots: {gUserID}).toJson(true).object().value("usrMobile").toString(); QVERIFY(Mobile == "+989998882020"); - }catch(std::exception &e){ + } catch (std::exception &e) { QFAIL (e.what()); } } @@ -567,18 +554,15 @@ private slots: } private slots: -//private: /***************************************************************************************/ /* cleanup *****************************************************************************/ /***************************************************************************************/ - void cleanupAll() - { + void cleanupAll() { QVariantMap Result; clsDAC DAC; - try - { + try { QString QueryString = R"( DELETE wb FROM tblWalletBalances wb @@ -593,13 +577,9 @@ private slots: ;)"; clsDACResult DACResult = DAC.execQuery("", QueryString); Result.insert("tblWalletBalances", QVariantMap({{ "numRowsAffected", DACResult.numRowsAffected() }})); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString QueryString = R"( DELETE wt FROM tblWalletsTransactions wt @@ -612,13 +592,9 @@ private slots: ;)"; clsDACResult DACResult = DAC.execQuery("", QueryString); Result.insert("tblWalletsTransactions", QVariantMap({{ "numRowsAffected", DACResult.numRowsAffected() }})); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString QueryString = R"( DELETE uw FROM tblUserWallets uw @@ -629,13 +605,9 @@ private slots: ;)"; clsDACResult DACResult = DAC.execQuery("", QueryString); Result.insert("tblUserWallets", QVariantMap({{ "numRowsAffected", DACResult.numRowsAffected() }})); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString QueryString = R"( DELETE op FROM tblOnlinePayments op @@ -648,13 +620,9 @@ private slots: ;)"; clsDACResult DACResult = DAC.execQuery("", QueryString); Result.insert("tblOnlinePayments", QVariantMap({{ "numRowsAffected", DACResult.numRowsAffected() }})); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString QueryString = R"( DELETE fp FROM tblOfflinePayments fp @@ -667,13 +635,9 @@ private slots: ;)"; clsDACResult DACResult = DAC.execQuery("", QueryString); Result.insert("tblOfflinePayments", QVariantMap({{ "numRowsAffected", DACResult.numRowsAffected() }})); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString QueryString = R"( DELETE vch FROM tblVoucher vch @@ -684,13 +648,9 @@ private slots: ;)"; clsDACResult DACResult = DAC.execQuery("", QueryString); Result.insert("tblVoucher", QVariantMap({{ "numRowsAffected", DACResult.numRowsAffected() }})); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString QueryString = R"( DELETE apr FROM tblApprovalRequest apr @@ -701,13 +661,9 @@ private slots: ;)"; clsDACResult DACResult = DAC.execQuery("", QueryString); Result.insert("tblApprovalRequest", QVariantMap({{ "numRowsAffected", DACResult.numRowsAffected() }})); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString QueryString = R"( DELETE sn FROM tblActiveSessions sn @@ -718,13 +674,9 @@ private slots: ;)"; clsDACResult DACResult = DAC.execQuery("", QueryString); Result.insert("tblActiveSessions", QVariantMap({{ "numRowsAffected", DACResult.numRowsAffected() }})); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString QueryString = R"( DELETE u FROM tblUser u @@ -733,13 +685,9 @@ private slots: ;)"; clsDACResult DACResult = DAC.execQuery("", QueryString); Result.insert("tblUser", QVariantMap({{ "numRowsAffected", DACResult.numRowsAffected() }})); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString QueryString = R"( DELETE r FROM tblRoles r @@ -747,10 +695,7 @@ private slots: ;)"; clsDACResult DACResult = DAC.execQuery("", QueryString); Result.insert("tblRoles", QVariantMap({{ "numRowsAffected", DACResult.numRowsAffected() }})); - } - catch(...) - { - } + } catch (...) { ; } qDebug() << Result; } diff --git a/Modules/Account/functionalTest/testAccountFixture.hpp b/Modules/Account/functionalTest/testAccountFixture.hpp index 17248258..627f2869 100644 --- a/Modules/Account/functionalTest/testAccountFixture.hpp +++ b/Modules/Account/functionalTest/testAccountFixture.hpp @@ -53,10 +53,9 @@ class testAccountFixture : public clsBaseTest Q_OBJECT public: - testAccountFixture(const QString &_dbPrefix) : clsBaseTest(_dbPrefix) {} + testAccountFixture(const QString &_dbPrefix) : clsBaseTest(_dbPrefix) { ; } - void cleanupUnitTestData() - { + void cleanupUnitTestData() { clsDAC DAC; DAC.execQuery("", QString("UPDATE %1AAA.tblUser SET usrStatus='R' WHERE usrEmail IN(?,?)").arg(this->DBPrefix), { UT_UserEmail, UT_AdminUserEmail }); } @@ -79,13 +78,11 @@ class testAccountFixture : public clsBaseTest // Targoman::API::AAA::stuVoucher ApproveOnlinePaymentVoucher; private slots: - void initTestCase() - { + void initTestCase() { initUnitTestData(false); } - void cleanupTestCase() - { + void cleanupTestCase() { gEncodedAdminJWT = ""; gEncodedJWT = ""; cleanupUnitTestData(); @@ -94,8 +91,7 @@ private slots: /***************************************************************************************/ /***************************************************************************************/ /***************************************************************************************/ - void setupAccountFixture_no_random() - { + void setupAccountFixture_no_random() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::POST, @@ -108,8 +104,7 @@ private slots: } } - void cleanupAccountFixture_no_random() - { + void cleanupAccountFixture_no_random() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::POST, @@ -127,8 +122,7 @@ private slots: } } - void setupAccountFixture_random() - { + void setupAccountFixture_random() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::POST, @@ -147,8 +141,7 @@ private slots: } } - void cleanupAccountFixture_random() - { + void cleanupAccountFixture_random() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::POST, diff --git a/Modules/Account/moduleSrc/Account.cpp b/Modules/Account/moduleSrc/Account.cpp index 446607cb..9434179b 100644 --- a/Modules/Account/moduleSrc/Account.cpp +++ b/Modules/Account/moduleSrc/Account.cpp @@ -130,10 +130,8 @@ tmplConfigurable Account::InvalidPasswordsFile ( enuConfigSource::Arg | enuConfigSource::File ); -QString ValidateAndNormalizeEmailOrPhoneNumber(QString &_emailOrMobile) -{ - if (QFV.email().isValid(_emailOrMobile)) - { +QString ValidateAndNormalizeEmailOrPhoneNumber(QString &_emailOrMobile) { + if (QFV.email().isValid(_emailOrMobile)) { if (QFV.emailNotFake().isValid(_emailOrMobile) == false) throw exHTTPBadRequest("Email domain is suspicious. Please use a real email."); @@ -141,8 +139,7 @@ QString ValidateAndNormalizeEmailOrPhoneNumber(QString &_emailOrMobile) return "E"; } - if (QFV.mobile().isValid(_emailOrMobile)) - { + if (QFV.mobile().isValid(_emailOrMobile)) { _emailOrMobile = PhoneHelper::NormalizePhoneNumber(_emailOrMobile); return "M"; } @@ -157,8 +154,7 @@ TARGOMAN_IMPL_API_MODULE(Account) TARGOMAN_API_MODULE_DB_CONFIG_IMPL(Account, AAASchema); Account::Account() : - intfSQLBasedWithActionLogsModule(AccountDomain, AAASchema) -{ + intfSQLBasedWithActionLogsModule(AccountDomain, AAASchema) { TARGOMAN_API_IMPLEMENT_ACTIONLOG(Account, AAASchema) this->addSubModule(&ActiveSessions::instance()); @@ -198,8 +194,7 @@ Account::Account() : // return clsJWT::createSignedLogin(_remember, { { JWTItems::usrLogin, _login } }, QJsonObject({ { "svc", _services } }), _ssid); //} -TAPI::EncodedJWT_t Account::createJWT(const QString _login, const stuActiveAccount& _activeAccount, const QString& _services) -{ +TAPI::EncodedJWT_t Account::createJWT(const QString _login, const stuActiveAccount& _activeAccount, const QString& _services) { return clsJWT::createSigned({ { JWTItems::usrLogin, _login }, { JWTItems::usrID, _activeAccount.Privs["usrID"] }, @@ -528,8 +523,7 @@ TAPI::EncodedJWT_t Account::apiloginByOAuth( Authentication::stuOAuthInfo OAuthInfo; ///TODO: validate _oAuthToken - switch(_type) - { + switch (_type) { case TAPI::enuOAuthType::Google: OAuthInfo = Authentication::retrieveGoogleUserInfo(_oAuthToken); break; @@ -579,7 +573,7 @@ TAPI::EncodedJWT_t Account::apiloginByOAuth( // clsJWT LoginJWT(_loginJWT); // QString Services = _services; -// if(_services.isEmpty()) +// if (_services.isEmpty()) // Services = LoginJWT.privatePart().value("svc").toString(); // auto NewPrivs = Authentication::updatePrivs(_REMOTE_IP, LoginJWT.session(), Services); @@ -589,8 +583,7 @@ TAPI::EncodedJWT_t Account::apiloginByOAuth( // }); //} -bool Account::apilogout(TAPI::JWT_t _JWT) -{ +bool Account::apilogout(TAPI::JWT_t _JWT) { clsJWT JWT(_JWT); this->callSP("spLogout", { @@ -644,8 +637,7 @@ QString Account::apiPOSTfixtureGetLastForgotPasswordUUIDAndMakeAsSent( throw exHTTPNotFound("No UUID could be found"); QString fprStatus = Data.value(tblForgotPassRequest::fprStatus).toString(); - if (fprStatus != "Sent") - { + if (fprStatus != "Sent") { quint64 RowsCount = UpdateQuery(ForgotPassRequest::instance()) .set(tblForgotPassRequest::fprStatus, enuFPRStatus::Sent) .where({ tblForgotPassRequest::fprUUID, enuConditionOperator::Equal, UUID }) @@ -709,8 +701,7 @@ Targoman::API::AAA::stuVoucher Account::processVoucher( quint64 _voucherID ) { - try - { + try { QVariant VoucherDesc = SelectQuery(Voucher::instance()) .addCol(tblVoucher::vchDesc) .where({ tblVoucher::vchID, enuConditionOperator::Equal, _voucherID }) @@ -738,21 +729,17 @@ Targoman::API::AAA::stuVoucher Account::processVoucher( throw exHTTPInternalServerError("There is no services registered."); //1: process voucher items - foreach(Targoman::API::AAA::stuVoucherItem VoucherItem, PreVoucher.Items) - { + foreach(Targoman::API::AAA::stuVoucherItem VoucherItem, PreVoucher.Items) { //lookup services - foreach (QVariant Service, Services) - { + foreach (QVariant Service, Services) { QVariantMap ServiceInfo = Service.toMap(); - if (ServiceInfo.value(tblService::svcName) == VoucherItem.Service) - { + if (ServiceInfo.value(tblService::svcName) == VoucherItem.Service) { NULLABLE_TYPE(QString) ProcessVoucherItemEndPoint; TAPI::setFromVariant(ProcessVoucherItemEndPoint, ServiceInfo.value(tblService::svcProcessVoucherItemEndPoint)); //bypass process by end point? - if (NULLABLE_HAS_VALUE(ProcessVoucherItemEndPoint)) - { + if (NULLABLE_HAS_VALUE(ProcessVoucherItemEndPoint)) { QString OldEncodedJWT = _JWT["encodedJWT"].toString(); QVariant Result = RESTClientHelper::callAPI( @@ -798,9 +785,7 @@ Targoman::API::AAA::stuVoucher Account::processVoucher( QString(), Targoman::API::AAA::enuVoucherStatus::Finished ); - } - catch (...) - { + } catch (...) { Account::tryCancelVoucher(_JWT, _voucherID); throw; } @@ -813,8 +798,7 @@ void Account::tryCancelVoucher( ) { //1: cancel voucher items - try - { + try { QVariant VoucherDesc = SelectQuery(Voucher::instance()) .addCol(tblVoucher::vchDesc) .where({ tblVoucher::vchID, enuConditionOperator::Equal, _voucherID }) @@ -828,33 +812,26 @@ void Account::tryCancelVoucher( else if (VoucherDesc.canConvert()) PreVoucher.fromJson(QJsonObject::fromVariantMap(VoucherDesc.toMap())); - if (PreVoucher.Items.length()) - { + if (PreVoucher.Items.length()) { QVariantList Services = SelectQuery(Service::instance()) .addCol(tblService::svcID) .addCol(tblService::svcName) .addCol(tblService::svcCancelVoucherItemEndPoint) .all(); - if (Services.isEmpty() == false) - { - foreach(Targoman::API::AAA::stuVoucherItem VoucherItem, PreVoucher.Items) - { + if (Services.isEmpty() == false) { + foreach(Targoman::API::AAA::stuVoucherItem VoucherItem, PreVoucher.Items) { //lookup services - foreach (QVariant Service, Services) - { + foreach (QVariant Service, Services) { QVariantMap ServiceInfo = Service.toMap(); - if (ServiceInfo.value(tblService::svcName) == VoucherItem.Service) - { + if (ServiceInfo.value(tblService::svcName) == VoucherItem.Service) { NULLABLE_TYPE(QString) CancelVoucherItemEndPoint; TAPI::setFromVariant(CancelVoucherItemEndPoint, ServiceInfo.value(tblService::svcCancelVoucherItemEndPoint)); //bypass process by end point? - if (NULLABLE_HAS_VALUE(CancelVoucherItemEndPoint)) - { - try - { + if (NULLABLE_HAS_VALUE(CancelVoucherItemEndPoint)) { + try { QString OldEncodedJWT = _JWT["encodedJWT"].toString(); QVariant Result = RESTClientHelper::callAPI( @@ -869,10 +846,8 @@ void Account::tryCancelVoucher( if (OldEncodedJWT != _JWT["encodedJWT"].toString()) Account::instance()->addResponseHeader("x-auth-new-token", _JWT["encodedJWT"].toString()); - } - catch (...) - { - } + } catch (...) + { ; } } break; @@ -881,10 +856,8 @@ void Account::tryCancelVoucher( } } //if (Services.isEmpty() == false) } //if (PreVoucher.Items.length()) - } - catch (...) - { - } + } catch (...) + { ; } //2: cancel voucher @@ -924,8 +897,7 @@ Targoman::API::AAA::stuVoucher Account::apiPOSTfinalizeBasket( ///2.1: process voucher ///2.2: create online/offline payment - if (_gatewayType != Targoman::API::AccountModule::enuPaymentGatewayType::COD) - { + if (_gatewayType != Targoman::API::AccountModule::enuPaymentGatewayType::COD) { if (_paymentVerifyCallback.isEmpty()) throw exHTTPBadRequest("callback for non COD is mandatory"); QFV.url().validate(_paymentVerifyCallback, "callBack"); @@ -958,12 +930,10 @@ Targoman::API::AAA::stuVoucher Account::apiPOSTfinalizeBasket( }) ); - try - { + try { //2: compute wallet remaining qint64 RemainingAfterWallet = static_cast(_preVoucher.ToPay); - if ((_walletID >= 0) && (RemainingAfterWallet > 0)) - { + if ((_walletID >= 0) && (RemainingAfterWallet > 0)) { clsDACResult Result = this->callSP("spWalletTransaction_Create", { { "iWalletID", _walletID }, { "iVoucherID", Voucher.ID }, @@ -978,12 +948,9 @@ Targoman::API::AAA::stuVoucher Account::apiPOSTfinalizeBasket( return Account::processVoucher(_JWT, Voucher.ID); //2.2: create online/offline payment - if (_gatewayType == Targoman::API::AccountModule::enuPaymentGatewayType::COD) - { + if (_gatewayType == Targoman::API::AccountModule::enuPaymentGatewayType::COD) { //Do nothing as it will be created after information upload. - } - else - { + } else { TAPI::MD5_t PaymentMD5; Voucher.PaymentLink = PaymentLogic::createOnlinePaymentLink( _gatewayType, @@ -996,8 +963,7 @@ Targoman::API::AAA::stuVoucher Account::apiPOSTfinalizeBasket( ); Voucher.PaymentMD5 = PaymentMD5; } - } - catch (std::exception &exp) { + } catch (std::exception &exp) { qDebug() << "**********************************" << exp.what(); Account::tryCancelVoucher(_JWT, Voucher.ID, true); @@ -1033,16 +999,13 @@ Targoman::API::AAA::stuVoucher Account::apiPOSTapproveOnlinePayment( { quint64 VoucherID = PaymentLogic::approveOnlinePayment(_paymentMD5, _pgResponse, _domain); - try - { + try { this->callSP("spWalletTransactionOnPayment_Create", { { "iVoucherID", VoucherID }, { "iPaymentType", QChar(enuPaymentType::Online) } }); return Account::processVoucher(_JWT, VoucherID); - } - catch(...) - { + } catch (...) { /*Targoman::API::Query::*/this->Update(Voucher::instance(), SYSTEM_USER_ID, {}, @@ -1069,7 +1032,7 @@ Targoman::API::AAA::stuVoucher Account::apiPOSTapproveOfflinePayment( ) { qint64 ApprovalLimit = Authorization::getPrivValue(_JWT, "AAA:approveOffline:maxAmount").toLongLong(); - if(ApprovalLimit == 0) + if (ApprovalLimit == 0) throw exAuthorization("Not enough access for offline approval"); if (ApprovalLimit > 0) { @@ -1133,10 +1096,10 @@ bool Account::apiPOSTaddPrizeTo( ) { qint64 Limit = Authorization::getPrivValue(_JWT, "AAA:addPrizeTo:maxAmount").toLongLong(); - if(Limit == 0) + if (Limit == 0) throw exAuthorization("Not enough access to add prize"); - if(Limit > 0 && _amount > static_cast(Limit)) + if (Limit > 0 && _amount > static_cast(Limit)) throw exAuthorization("Prize amount is greater than your limits"); QFV.hasKey("desc").validate(_desc, "desc"); @@ -1231,15 +1194,12 @@ QVariant Account::apiPOSTfixtureSetup( UserEmail }); - if (UserDACResult.isValid()) - { + if (UserDACResult.isValid()) { Result.insert("User", QVariantMap({ { "usrID", UserDACResult.value("usrID") }, { "email", UserEmail }, })); - } - else - { + } else { //-- create user -------------------------------------- //df6d2338b2b8fce1ec2f6dda0a630eb0 # 987 QVariantMap SignupUserResult = this->apiPUTsignup( @@ -1291,15 +1251,12 @@ QVariant Account::apiPOSTfixtureSetup( AdminUserEmail }); - if (AdminDACResult.isValid()) - { + if (AdminDACResult.isValid()) { Result.insert("Admin", QVariantMap({ { "usrID", AdminDACResult.value("usrID") }, { "email", AdminUserEmail }, })); - } - else - { + } else { //-- create admin -------------------------------------- //df6d2338b2b8fce1ec2f6dda0a630eb0 # 987 QVariantMap SignupAdminUserResult = this->apiPUTsignup( @@ -1370,14 +1327,11 @@ QVariant Account::apiPOSTfixtureSetup( { "RowsCount", pgwTotalRows } }; - if (pgwTotalRows < 3) - { + if (pgwTotalRows < 3) { // QVariantMap CreatedPaymentGateways; - for (int i=pgwTotalRows; i<3; ++i) - { - try - { + for (int i=pgwTotalRows; i<3; ++i) { + try { QVariantMap PaymentGatewayValues = { { tblPaymentGateways::pgwName, FixtureHelper::MakeRandomizeName(_random, " ", "fixture.devtest") }, { tblPaymentGateways::pgwType, enuPaymentGatewayType::toStr(enuPaymentGatewayType::_DeveloperTest) }, @@ -1414,9 +1368,7 @@ QVariant Account::apiPOSTfixtureSetup( PaymentGatewayValues.insert(tblPaymentGateways::pgwID, PaymentGatewayID); // CreatedPaymentGateways.in(PaymentGatewayValues); - } - catch(std::exception &exp) - { + } catch (std::exception &exp) { qDebug() << exp.what(); } } @@ -1446,8 +1398,7 @@ QVariant Account::apiPOSTfixtureCleanup( // OR u.usrMobile LIKE '+98999887%' - try - { + try { QString QueryString = R"( DELETE wb FROM tblWalletBalances wb @@ -1467,13 +1418,9 @@ QVariant Account::apiPOSTfixtureCleanup( Result.insert("tblWalletBalances", QVariantMap({ { "numRowsAffected", DACResult.numRowsAffected() }, })); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString QueryString = R"( DELETE wt FROM tblWalletsTransactions wt @@ -1491,13 +1438,9 @@ QVariant Account::apiPOSTfixtureCleanup( Result.insert("tblWalletsTransactions", QVariantMap({ { "numRowsAffected", DACResult.numRowsAffected() }, })); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString QueryString = R"( DELETE uw FROM tblUserWallets uw @@ -1513,13 +1456,9 @@ QVariant Account::apiPOSTfixtureCleanup( Result.insert("tblUserWallets", QVariantMap({ { "numRowsAffected", DACResult.numRowsAffected() }, })); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString QueryString = R"( DELETE op FROM tblOnlinePayments op @@ -1537,13 +1476,9 @@ QVariant Account::apiPOSTfixtureCleanup( Result.insert("tblOnlinePayments", QVariantMap({ { "numRowsAffected", DACResult.numRowsAffected() }, })); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString QueryString = R"( DELETE fp FROM tblOfflinePayments fp @@ -1561,13 +1496,9 @@ QVariant Account::apiPOSTfixtureCleanup( Result.insert("tblOfflinePayments", QVariantMap({ { "numRowsAffected", DACResult.numRowsAffected() }, })); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString QueryString = R"( DELETE vch FROM tblVoucher vch @@ -1583,13 +1514,9 @@ QVariant Account::apiPOSTfixtureCleanup( Result.insert("tblVoucher", QVariantMap({ { "numRowsAffected", DACResult.numRowsAffected() }, })); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString QueryString = R"( DELETE apr FROM tblApprovalRequest apr @@ -1605,13 +1532,9 @@ QVariant Account::apiPOSTfixtureCleanup( Result.insert("tblApprovalRequest", QVariantMap({ { "numRowsAffected", DACResult.numRowsAffected() }, })); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString QueryString = R"( DELETE sn FROM tblActiveSessions sn @@ -1627,13 +1550,9 @@ QVariant Account::apiPOSTfixtureCleanup( Result.insert("tblActiveSessions", QVariantMap({ { "numRowsAffected", DACResult.numRowsAffected() }, })); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString QueryString = R"( DELETE u FROM tblUser u @@ -1648,13 +1567,9 @@ QVariant Account::apiPOSTfixtureCleanup( { "items", QStringList({ UserEmail, AdminUserEmail }).join(",") }, { "numRowsAffected", DACResult.numRowsAffected() }, })); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString RoleName = FixtureHelper::MakeRandomizeName(_random, "-", "fixture", "role"); QString QueryString = R"( DELETE r @@ -1668,10 +1583,7 @@ QVariant Account::apiPOSTfixtureCleanup( { "items", RoleName }, { "numRowsAffected", DACResult.numRowsAffected() }, })); - } - catch(...) - { - } + } catch (...) { ; } return Result; } diff --git a/Modules/Account/moduleSrc/ORM/APITokenValidIPs.cpp b/Modules/Account/moduleSrc/ORM/APITokenValidIPs.cpp index 3d923e39..cd5da787 100644 --- a/Modules/Account/moduleSrc/ORM/APITokenValidIPs.cpp +++ b/Modules/Account/moduleSrc/ORM/APITokenValidIPs.cpp @@ -29,8 +29,7 @@ namespace Targoman::API::AccountModule::ORM { -QVariant APITokenValidIPs::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant APITokenValidIPs::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())) == false) this->setSelfFilters({{tblAPITokens::apt_usrID, clsJWT(_JWT).usrID()}}, _filters); @@ -41,15 +40,13 @@ QVariant APITokenValidIPs::apiGET(GET_METHOD_ARGS_IMPL_APICALL) return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL, {}, 0, QueryLambda); } -quint64 APITokenValidIPs::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) -{ +quint64 APITokenValidIPs::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PUT, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Create(*this, CREATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool APITokenValidIPs::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool APITokenValidIPs::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { TAPI::ORMFields_t ExtraFilters; if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_PATCH,this->moduleBaseName())) == false) ExtraFilters.insert(tblAPITokens::apt_usrID, clsJWT(_JWT).usrID()); @@ -59,8 +56,7 @@ bool APITokenValidIPs::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL, ExtraFilters); } -bool APITokenValidIPs::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool APITokenValidIPs::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { TAPI::ORMFields_t ExtraFilters; if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())) == false) @@ -99,6 +95,6 @@ APITokenValidIPs::APITokenValidIPs() : }, enuDBIndex::Unique }, } ) -{} +{ ; } } //namespace Targoman::API::AccountModule::ORM diff --git a/Modules/Account/moduleSrc/ORM/APITokens.cpp b/Modules/Account/moduleSrc/ORM/APITokens.cpp index ed0ac259..60e3ae12 100644 --- a/Modules/Account/moduleSrc/ORM/APITokens.cpp +++ b/Modules/Account/moduleSrc/ORM/APITokens.cpp @@ -65,32 +65,28 @@ APITokens::APITokens() : }, enuDBIndex::Unique }, } ) -{} +{ ; } -QVariant APITokens::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant APITokens::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())) == false) this->setSelfFilters({{tblAPITokens::apt_usrID, clsJWT(_JWT).usrID()}}, _filters); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); } -quint64 APITokens::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) -{ +quint64 APITokens::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PUT, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Create(*this, CREATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool APITokens::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool APITokens::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PATCH, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool APITokens::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool APITokens::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { TAPI::ORMFields_t ExtraFilters; if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())) == false) ExtraFilters.insert(tblAPITokens::apt_usrID, clsJWT(_JWT).usrID()); diff --git a/Modules/Account/moduleSrc/ORM/ActiveSessions.cpp b/Modules/Account/moduleSrc/ORM/ActiveSessions.cpp index fd8224c8..579a8323 100644 --- a/Modules/Account/moduleSrc/ORM/ActiveSessions.cpp +++ b/Modules/Account/moduleSrc/ORM/ActiveSessions.cpp @@ -53,10 +53,9 @@ ActiveSessions::ActiveSessions() : { tblActiveSessions::ssnUpdatedBy_usrID, R(AAASchema, tblUser::Name), tblUser::usrID, "Updater_", true } } ) -{} +{ ; } -QVariant ActiveSessions::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant ActiveSessions::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { // QVariantMap ExtraFilters; if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())) == false) @@ -69,8 +68,7 @@ QVariant ActiveSessions::apiGET(GET_METHOD_ARGS_IMPL_APICALL) // return this->selectFromTable({}, {}, GET_METHOD_CALL_ARGS_APICALL); } -bool ActiveSessions::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool ActiveSessions::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { TAPI::ORMFields_t ExtraFilters; if (_pksByPath.trimmed() == clsJWT(_JWT).session()) diff --git a/Modules/Account/moduleSrc/ORM/ApprovalRequest.cpp b/Modules/Account/moduleSrc/ORM/ApprovalRequest.cpp index 033f8d6b..e5a35bc5 100644 --- a/Modules/Account/moduleSrc/ORM/ApprovalRequest.cpp +++ b/Modules/Account/moduleSrc/ORM/ApprovalRequest.cpp @@ -83,10 +83,9 @@ ApprovalRequest::ApprovalRequest() : }, enuDBIndex::Unique }, } ) -{} +{ ; } -QVariant ApprovalRequest::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant ApprovalRequest::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); @@ -96,8 +95,7 @@ QVariant ApprovalRequest::apiGET(GET_METHOD_ARGS_IMPL_APICALL) // return this->selectFromTable({}, {}, GET_METHOD_CALL_ARGS_APICALL); } -bool ApprovalRequest::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool ApprovalRequest::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())); return /*Targoman::API::Query::*/this->DeleteByPks(*this, DELETE_METHOD_CALL_ARGS_INTERNAL_CALL, {}, true); @@ -113,19 +111,15 @@ QVariant ApprovalRequest::apitimerInfo( enuApprovalType::Type Type; - if (QFV.email().isValid(_emailOrMobile)) - { + if (QFV.email().isValid(_emailOrMobile)) { if (QFV.emailNotFake().isValid(_emailOrMobile)) Type = enuApprovalType::Email; else throw exHTTPBadRequest("Email domain is suspicious. Please use a real email."); - } - else if (QFV.mobile().isValid(_emailOrMobile)) - { + } else if (QFV.mobile().isValid(_emailOrMobile)) { Type = enuApprovalType::Mobile; _emailOrMobile = PhoneHelper::NormalizePhoneNumber(_emailOrMobile); - } - else + } else throw exHTTPBadRequest("emailOrMobile must be a valid email or mobile"); QVariantMap Info = SelectQuery(*this) diff --git a/Modules/Account/moduleSrc/ORM/Auth.cpp b/Modules/Account/moduleSrc/ORM/Auth.cpp index 340d7eb8..b5e91e8e 100644 --- a/Modules/Account/moduleSrc/ORM/Auth.cpp +++ b/Modules/Account/moduleSrc/ORM/Auth.cpp @@ -29,7 +29,7 @@ Auth::Auth() : intfPureModule( "Account" ) -{} +{ ; } bool Auth::apivalidateJWT( TAPI::JWT_t _JWT diff --git a/Modules/Account/moduleSrc/ORM/BlockingRules.cpp b/Modules/Account/moduleSrc/ORM/BlockingRules.cpp index 2f110669..2833bc7e 100644 --- a/Modules/Account/moduleSrc/ORM/BlockingRules.cpp +++ b/Modules/Account/moduleSrc/ORM/BlockingRules.cpp @@ -49,11 +49,9 @@ BlockingRules::BlockingRules() : ORM_RELATION_OF_UPDATER(tblBlockingRules::blrUpdatedBy_usrID), } ) -{ -} +{ ; } -QVariant BlockingRules::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant BlockingRules::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); @@ -63,22 +61,19 @@ QVariant BlockingRules::apiGET(GET_METHOD_ARGS_IMPL_APICALL) // return this->selectFromTable({}, {}, GET_METHOD_CALL_ARGS_APICALL); } -quint64 BlockingRules::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) -{ +quint64 BlockingRules::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PUT, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Create(*this, CREATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool BlockingRules::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool BlockingRules::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PATCH, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool BlockingRules::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool BlockingRules::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())); return /*Targoman::API::Query::*/this->DeleteByPks(*this, DELETE_METHOD_CALL_ARGS_INTERNAL_CALL); diff --git a/Modules/Account/moduleSrc/ORM/ForgotPassRequest.cpp b/Modules/Account/moduleSrc/ORM/ForgotPassRequest.cpp index 915ce0e9..7571c7eb 100644 --- a/Modules/Account/moduleSrc/ORM/ForgotPassRequest.cpp +++ b/Modules/Account/moduleSrc/ORM/ForgotPassRequest.cpp @@ -47,10 +47,9 @@ ForgotPassRequest::ForgotPassRequest() : { tblForgotPassRequest::Relation::User, { tblForgotPassRequest::fpr_usrID, R(AAASchema,tblUser::Name), tblUser::usrID } }, } ) -{} +{ ; } -QVariant ForgotPassRequest::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant ForgotPassRequest::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); @@ -60,8 +59,7 @@ QVariant ForgotPassRequest::apiGET(GET_METHOD_ARGS_IMPL_APICALL) // return this->selectFromTable({}, {}, GET_METHOD_CALL_ARGS_APICALL); } -bool ForgotPassRequest::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool ForgotPassRequest::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())); return /*Targoman::API::Query::*/this->DeleteByPks(*this, DELETE_METHOD_CALL_ARGS_INTERNAL_CALL, {}, true); diff --git a/Modules/Account/moduleSrc/ORM/IPBin.cpp b/Modules/Account/moduleSrc/ORM/IPBin.cpp index 539c9808..940292d6 100644 --- a/Modules/Account/moduleSrc/ORM/IPBin.cpp +++ b/Modules/Account/moduleSrc/ORM/IPBin.cpp @@ -55,10 +55,9 @@ IPBin::IPBin() : }, enuDBIndex::Unique }, } ) -{} +{ ; } -QVariant IPBin::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant IPBin::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); diff --git a/Modules/Account/moduleSrc/ORM/IPStats.cpp b/Modules/Account/moduleSrc/ORM/IPStats.cpp index 430edaef..ac84d9d8 100644 --- a/Modules/Account/moduleSrc/ORM/IPStats.cpp +++ b/Modules/Account/moduleSrc/ORM/IPStats.cpp @@ -28,8 +28,7 @@ namespace Targoman::API::AccountModule::ORM { -QVariant IPStats::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant IPStats::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); @@ -50,7 +49,6 @@ IPStats::IPStats() : { ///< Col Reference Table ForeignCol {tblIPStats::ips_ipbIP, R(AAASchema,tblIPBin::Name), tblIPBin::ipbIP }, }) -{ -} +{ ; } } //namespace Targoman::API::AccountModule::ORM diff --git a/Modules/Account/moduleSrc/ORM/PaymentGateways.cpp b/Modules/Account/moduleSrc/ORM/PaymentGateways.cpp index 66e56562..fcad6c3f 100644 --- a/Modules/Account/moduleSrc/ORM/PaymentGateways.cpp +++ b/Modules/Account/moduleSrc/ORM/PaymentGateways.cpp @@ -34,8 +34,7 @@ TAPI_REGISTER_TARGOMAN_ENUM(Targoman::API::AccountModule, enuPaymentGatewayTrans namespace Targoman::API::AccountModule { -void stuPaymentGateway::fromVariantMap(const QVariantMap& _info) -{ +void stuPaymentGateway::fromVariantMap(const QVariantMap& _info) { SET_FIELD_FROM_VARIANT_MAP(this->pgwID, _info, ORM::tblPaymentGateways, pgwID); SET_FIELD_FROM_VARIANT_MAP(this->pgwName, _info, ORM::tblPaymentGateways, pgwName); SET_FIELD_FROM_VARIANT_MAP(this->pgwType, _info, ORM::tblPaymentGateways, pgwType); @@ -96,16 +95,14 @@ PaymentGateways::PaymentGateways() : ORM_RELATION_OF_UPDATER(tblPaymentGateways::pgwUpdatedBy_usrID), } ) -{} +{ ; } -QVariant PaymentGateways::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant PaymentGateways::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); } -quint32 PaymentGateways::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) -{ +quint32 PaymentGateways::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PUT, this->moduleBaseName())); if (_createInfo.contains(tblPaymentGateways::pgwAllowedDomainName)) @@ -114,14 +111,12 @@ quint32 PaymentGateways::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) return /*Targoman::API::Query::*/this->Create(*this, CREATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool PaymentGateways::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool PaymentGateways::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PATCH, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool PaymentGateways::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool PaymentGateways::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())); return /*Targoman::API::Query::*/this->DeleteByPks(*this, DELETE_METHOD_CALL_ARGS_INTERNAL_CALL); } diff --git a/Modules/Account/moduleSrc/ORM/Payments.cpp b/Modules/Account/moduleSrc/ORM/Payments.cpp index aa493d19..9860b03f 100644 --- a/Modules/Account/moduleSrc/ORM/Payments.cpp +++ b/Modules/Account/moduleSrc/ORM/Payments.cpp @@ -30,8 +30,7 @@ TAPI_REGISTER_TARGOMAN_ENUM(Targoman::API::AccountModule, enuPaymentStatus); namespace Targoman::API::AccountModule { -void stuOnlinePayment::fromVariantMap(const QVariantMap& _info) -{ +void stuOnlinePayment::fromVariantMap(const QVariantMap& _info) { SET_FIELD_FROM_VARIANT_MAP(this->onpID, _info, ORM::tblOnlinePayments, onpID); SET_FIELD_FROM_VARIANT_MAP(this->onpMD5, _info, ORM::tblOnlinePayments, onpMD5); SET_FIELD_FROM_VARIANT_MAP(this->onp_vchID, _info, ORM::tblOnlinePayments, onp_vchID); @@ -70,10 +69,9 @@ OnlinePayments::OnlinePayments() : { "paymentGateway", { tblOnlinePayments::onp_pgwID, R(AAASchema, tblPaymentGateways::Name), tblPaymentGateways::pgwID } }, } ) -{} +{ ; } -QVariant OnlinePayments::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant OnlinePayments::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())) == false) this->setSelfFilters({{tblVoucher::vch_usrID, clsJWT(_JWT).usrID()}}, _filters); @@ -110,10 +108,9 @@ OfflinePayments::OfflinePayments() : ORM_RELATION_OF_UPDATER(tblOfflinePayments::ofpUpdatedBy_usrID), } ) -{} +{ ; } -QVariant OfflinePayments::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant OfflinePayments::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())) == false) this->setSelfFilters({{tblVoucher::vch_usrID, clsJWT(_JWT).usrID()}}, _filters); @@ -124,8 +121,7 @@ QVariant OfflinePayments::apiGET(GET_METHOD_ARGS_IMPL_APICALL) return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL, {}, 0, QueryLambda); } -bool OfflinePayments::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool OfflinePayments::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PATCH, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL); } diff --git a/Modules/Account/moduleSrc/ORM/Roles.cpp b/Modules/Account/moduleSrc/ORM/Roles.cpp index f583ce67..fe329961 100644 --- a/Modules/Account/moduleSrc/ORM/Roles.cpp +++ b/Modules/Account/moduleSrc/ORM/Roles.cpp @@ -58,10 +58,9 @@ Roles::Roles() : }, enuDBIndex::Unique }, } ) -{} +{ ; } -QVariant Roles::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant Roles::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); @@ -71,22 +70,19 @@ QVariant Roles::apiGET(GET_METHOD_ARGS_IMPL_APICALL) // return this->selectFromTable({}, {}, GET_METHOD_CALL_ARGS_APICALL); } -quint32 Roles::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) -{ +quint32 Roles::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PUT, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Create(*this, CREATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool Roles::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool Roles::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PATCH, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool Roles::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool Roles::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())); return /*Targoman::API::Query::*/this->DeleteByPks(*this, DELETE_METHOD_CALL_ARGS_INTERNAL_CALL); diff --git a/Modules/Account/moduleSrc/ORM/Service.cpp b/Modules/Account/moduleSrc/ORM/Service.cpp index 3f7fc52f..dd849376 100644 --- a/Modules/Account/moduleSrc/ORM/Service.cpp +++ b/Modules/Account/moduleSrc/ORM/Service.cpp @@ -57,28 +57,24 @@ Service::Service() : }, enuDBIndex::Unique }, } ) -{} +{ ; } -QVariant Service::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant Service::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); } -quint64 Service::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) -{ +quint64 Service::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PUT, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Create(*this, CREATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool Service::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool Service::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PATCH, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool Service::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool Service::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())); return /*Targoman::API::Query::*/this->DeleteByPks(*this, DELETE_METHOD_CALL_ARGS_INTERNAL_CALL); } diff --git a/Modules/Account/moduleSrc/ORM/User.cpp b/Modules/Account/moduleSrc/ORM/User.cpp index 9c08c2b8..2f30c2ac 100644 --- a/Modules/Account/moduleSrc/ORM/User.cpp +++ b/Modules/Account/moduleSrc/ORM/User.cpp @@ -95,8 +95,7 @@ User::User() : ; } -QVariant User::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant User::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { if (clsJWT(_JWT).usrID() != _pksByPath.toULongLong()) Authorization::checkPriv(_JWT, { "Account:User:CRUD~0100" }); @@ -145,8 +144,7 @@ QVariant User::apiGET(GET_METHOD_ARGS_IMPL_APICALL) // return this->selectFromTable({},{}, GET_METHOD_CALL_ARGS_APICALL); } -quint64 User::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) -{ +quint64 User::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PUT, this->moduleBaseName())); if (_createInfo.value(tblUser::usrEmail).toString().isEmpty() && _createInfo.value(tblUser::usrMobile).toString().isEmpty()) throw exHTTPBadRequest("Either email or mobile must be provided to create user"); @@ -157,22 +155,19 @@ quint64 User::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) /* * this method only can call by admin user */ -bool User::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool User::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PATCH, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool User::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool User::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())); return /*Targoman::API::Query::*/this->DeleteByPks(*this, DELETE_METHOD_CALL_ARGS_INTERNAL_CALL); } -TAPI::Base64Image_t User::apiGETphoto(TAPI::JWT_t _JWT, quint64 _usrID) -{ +TAPI::Base64Image_t User::apiGETphoto(TAPI::JWT_t _JWT, quint64 _usrID) { quint64 CurrentUserID = clsJWT(_JWT).usrID(); if (CurrentUserID != _usrID) @@ -190,8 +185,7 @@ TAPI::Base64Image_t User::apiGETphoto(TAPI::JWT_t _JWT, quint64 _usrID) return TAPI::Base64Image_t(Photo); } -bool User::apiUPDATEphoto(TAPI::JWT_t _JWT, TAPI::Base64Image_t _image) -{ +bool User::apiUPDATEphoto(TAPI::JWT_t _JWT, TAPI::Base64Image_t _image) { quint64 CurrentUserID = clsJWT(_JWT).usrID(); QString qry = QString() @@ -216,8 +210,7 @@ bool User::apiUPDATEphoto(TAPI::JWT_t _JWT, TAPI::Base64Image_t _image) return Result.numRowsAffected() > 0; } -bool User::apiPOSTdeletePhoto(TAPI::JWT_t _JWT) -{ +bool User::apiPOSTdeletePhoto(TAPI::JWT_t _JWT) { quint64 CurrentUserID = clsJWT(_JWT).usrID(); QString qry = QString() @@ -341,20 +334,17 @@ bool User::apiUPDATEfinancialInfo( QStringList ToUpdate; QVariantList Params; - if (_iban.isNull() == false) - { + if (_iban.isNull() == false) { ToUpdate.append(tblUserExtraInfo::ueiIBAN); Params.append(_iban); } - if (_ether.isNull() == false) - { + if (_ether.isNull() == false) { ToUpdate.append(tblUserExtraInfo::ueiEther); Params.append(_ether); } - if (ToUpdate.size()) - { + if (ToUpdate.size()) { QString qry = QString() + "INSERT INTO" + " " + tblUserExtraInfo::Name @@ -394,22 +384,19 @@ bool User::apiUPDATEextraInfo( QStringList ToRemoveJson; //userExtra info json field - if (_job.isNull() == false) - { + if (_job.isNull() == false) { if (_job.isEmpty()) ToRemoveJson.append(enuUserExtraInfoJsonKey::toStr(enuUserExtraInfoJsonKey::Job)); else ToUpdateJson.insert(enuUserExtraInfoJsonKey::toStr(enuUserExtraInfoJsonKey::Job), _job); } - if (_education.isNull() == false) - { + if (_education.isNull() == false) { if (_education.isEmpty()) ToRemoveJson.append(enuUserExtraInfoJsonKey::toStr(enuUserExtraInfoJsonKey::Education)); else ToUpdateJson.insert(enuUserExtraInfoJsonKey::toStr(enuUserExtraInfoJsonKey::Education), _education); } - if (_fieldOfStudy.isNull() == false) - { + if (_fieldOfStudy.isNull() == false) { if (_fieldOfStudy.isEmpty()) ToRemoveJson.append(enuUserExtraInfoJsonKey::toStr(enuUserExtraInfoJsonKey::FieldOfStudy)); else @@ -422,8 +409,7 @@ bool User::apiUPDATEextraInfo( // else // ToUpdateJson.insert(enuUserExtraInfoJsonKey::toStr(enuUserExtraInfoJsonKey::Language), _language); // } - if (_theme.isNull() == false) - { + if (_theme.isNull() == false) { if (_theme.isEmpty()) ToRemoveJson.append(enuUserExtraInfoJsonKey::toStr(enuUserExtraInfoJsonKey::Theme)); else @@ -435,24 +421,18 @@ bool User::apiUPDATEextraInfo( if (ToUpdateJson.size()) updateQuery = "'" + QJsonDocument(QJsonObject().fromVariantMap(ToUpdateJson)).toJson(QJsonDocument::Compact) + "'"; - if (ToRemoveJson.length()) - { - if (ToUpdateJson.size()) - { + if (ToRemoveJson.length()) { + if (ToUpdateJson.size()) { jsonQry = QString() + "JSON_MERGE_PATCH(" + "JSON_REMOVE(COALESCE(ueiExtraInfo, '{}'), '$." + ToRemoveJson.join("', '$.") + "')," + updateQuery + ")"; - } - else - { + } else { jsonQry = "JSON_REMOVE(COALESCE(ueiExtraInfo, '{}'), '$." + ToRemoveJson.join("', '$.") + "')"; } - } - else if (ToUpdateJson.size()) - { + } else if (ToUpdateJson.size()) { jsonQry = QString() + "JSON_MERGE_PATCH(COALESCE(ueiExtraInfo, '{}')," + updateQuery @@ -470,20 +450,17 @@ bool User::apiUPDATEextraInfo( // ToUpdate.append(tblUserExtraInfo::ueiBirthDate); // Params.append(_birthDate); // } - if (NULLABLE_HAS_VALUE(_birthDate)) - { + if (NULLABLE_HAS_VALUE(_birthDate)) { ToUpdate.append(tblUserExtraInfo::ueiBirthDate); Params.append(NULLABLE_GET(_birthDate)); } //-------------------------------------- Params.append(CurrentUserID); - if ((ToUpdate.isEmpty() == false) || (jsonQry.isEmpty() == false)) - { + if ((ToUpdate.isEmpty() == false) || (jsonQry.isEmpty() == false)) { QString qry = QString("INSERT INTO %1 SET").arg(tblUserExtraInfo::Name); - if (ToUpdate.isEmpty() == false) - { + if (ToUpdate.isEmpty() == false) { qry += " " + ToUpdate.join("=? ,") + "=?"; if (jsonQry.isEmpty() == false) qry += ","; @@ -495,8 +472,7 @@ bool User::apiUPDATEextraInfo( + ", uei_usrID=?" + " ON DUPLICATE KEY UPDATE"; - if (ToUpdate.isEmpty() == false) - { + if (ToUpdate.isEmpty() == false) { qry += " " + ToUpdate.join("=? ,") + "=?"; if (jsonQry.isEmpty() == false) qry += ","; @@ -540,7 +516,7 @@ UserExtraInfo::UserExtraInfo() : ORM_RELATION_OF_UPDATER(tblUserExtraInfo::ueiUpdatedBy_usrID), } ) -{} +{ ; } //bool UserExtraInfo::apiUPDATEsheba(TAPI::JWT_t _JWT, TAPI::Sheba_t _sheba) //{ diff --git a/Modules/Account/moduleSrc/ORM/UserWallets.cpp b/Modules/Account/moduleSrc/ORM/UserWallets.cpp index dabeed6b..aa9b5bfb 100644 --- a/Modules/Account/moduleSrc/ORM/UserWallets.cpp +++ b/Modules/Account/moduleSrc/ORM/UserWallets.cpp @@ -68,21 +68,17 @@ UserWallets::UserWallets() : }, enuDBIndex::Unique }, } ) -{ -} +{ ; } -QVariant UserWallets::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant UserWallets::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())) == false) this->setSelfFilters({ { tblUserWallets::wal_usrID, clsJWT(_JWT).usrID() } }, _filters); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); } -quint64 UserWallets::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) -{ - if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())) == false) - { +quint64 UserWallets::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) { + if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())) == false) { _createInfo.insert(tblUserWallets::walDefault, 0); // this->setSelfFilters({ { tblUserWallets::wal_usrID, clsJWT(_JWT).usrID() } }, _createInfo); @@ -92,19 +88,16 @@ quint64 UserWallets::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) return /*Targoman::API::Query::*/this->Create(*this, CREATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool UserWallets::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool UserWallets::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PATCH, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool UserWallets::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool UserWallets::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { TAPI::ORMFields_t ExtraFilters; - if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())) == false) - { + if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())) == false) { ExtraFilters.insert(tblUserWallets::walDefault, 0); ExtraFilters.insert(tblUserWallets::wal_usrID, clsJWT(_JWT).usrID()); } diff --git a/Modules/Account/moduleSrc/ORM/Voucher.cpp b/Modules/Account/moduleSrc/ORM/Voucher.cpp index f06941ed..90c41a41 100644 --- a/Modules/Account/moduleSrc/ORM/Voucher.cpp +++ b/Modules/Account/moduleSrc/ORM/Voucher.cpp @@ -50,21 +50,19 @@ Voucher::Voucher() : { tblVoucher::vch_usrID, R(AAASchema, tblUser::Name), tblUser::usrID }, } ) -{} +{ ; } -QVariant Voucher::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant Voucher::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())) == false) this->setSelfFilters({{tblVoucher::vch_usrID, clsJWT(_JWT).usrID()}}, _filters); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool Voucher::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool Voucher::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { TAPI::ORMFields_t ExtraFilters; - if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())) == false){ + if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())) == false) { ExtraFilters.insert(tblVoucher::vchType, Targoman::API::AccountModule::enuVoucherType::toStr(Targoman::API::AccountModule::enuVoucherType::Withdrawal)); ExtraFilters.insert(tblVoucher::vch_usrID, clsJWT(_JWT).usrID()); @@ -97,14 +95,10 @@ Targoman::API::AAA::stuVoucher Voucher::apiCREATErequestIncrease( { tblVoucher::vchTotalAmount, Voucher.Info.ToPay } })); - try - { - if (_gatewayType == Targoman::API::AccountModule::enuPaymentGatewayType::COD) - { + try { + if (_gatewayType == Targoman::API::AccountModule::enuPaymentGatewayType::COD) { //Do nothing as it will be created after information upload. - } - else - { + } else { TAPI::MD5_t PaymentMD5; Voucher.PaymentLink = Targoman::API::AccountModule::Payment::PaymentLogic::createOnlinePaymentLink( _gatewayType, @@ -117,9 +111,7 @@ Targoman::API::AAA::stuVoucher Voucher::apiCREATErequestIncrease( ); Voucher.PaymentMD5 = PaymentMD5; } - } - catch (...) - { + } catch (...) { /*Targoman::API::Query::*/this->Update(Voucher::instance(), SYSTEM_USER_ID, {}, @@ -135,8 +127,7 @@ Targoman::API::AAA::stuVoucher Voucher::apiCREATErequestIncrease( return Voucher; } -quint64 Voucher::apiCREATErequestWithdraw(TAPI::JWT_t _JWT, quint64 _amount, quint64 _walID, const QString& _desc) -{ +quint64 Voucher::apiCREATErequestWithdraw(TAPI::JWT_t _JWT, quint64 _amount, quint64 _walID, const QString& _desc) { return this->callSP("spWithdrawal_Request", { {"iWalletID",_walID}, {"iForUsrID", clsJWT(_JWT).usrID()}, @@ -146,8 +137,7 @@ quint64 Voucher::apiCREATErequestWithdraw(TAPI::JWT_t _JWT, quint64 _amount, qui }).spDirectOutputs().value("oVoucherID").toULongLong(); } -quint64 Voucher::apiCREATErequestWithdrawFor(TAPI::JWT_t _JWT, quint64 _targetUsrID, quint64 _amount, TAPI::JSON_t _desc) -{ +quint64 Voucher::apiCREATErequestWithdrawFor(TAPI::JWT_t _JWT, quint64 _targetUsrID, quint64 _amount, TAPI::JSON_t _desc) { Authorization::checkPriv(_JWT, {"AAA:RequestWithdraw"}); return this->callSP("spWithdrawal_Request", { diff --git a/Modules/Account/moduleSrc/ORM/WalletTransactions.cpp b/Modules/Account/moduleSrc/ORM/WalletTransactions.cpp index 3c7d4282..c71be708 100644 --- a/Modules/Account/moduleSrc/ORM/WalletTransactions.cpp +++ b/Modules/Account/moduleSrc/ORM/WalletTransactions.cpp @@ -51,10 +51,9 @@ WalletTransactions::WalletTransactions() : { tblWalletsTransactions::wltID, R(AAASchema,tblWalletBalances::Name), tblWalletBalances::wbl_wltID }, } ) -{} +{ ; } -QVariant WalletTransactions::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant WalletTransactions::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())) == false) this->setSelfFilters({{tblUserWallets::wal_usrID, clsJWT(_JWT).usrID()}}, _filters); @@ -78,6 +77,6 @@ WalletBalances::WalletBalances() : { tblWalletBalances::wblSumExpense, S(qint64), QFV.allwaysInvalid(), QInvalid, UPNone, false, false }, } ) -{} +{ ; } } //namespace Targoman::API::AccountModule::ORM diff --git a/Modules/Account/moduleSrc/Payment/Gateways/gtwMellatBank.cpp b/Modules/Account/moduleSrc/Payment/Gateways/gtwMellatBank.cpp index 77201bac..0d336830 100644 --- a/Modules/Account/moduleSrc/Payment/Gateways/gtwMellatBank.cpp +++ b/Modules/Account/moduleSrc/Payment/Gateways/gtwMellatBank.cpp @@ -60,8 +60,9 @@ stuPaymentResponse gtwMellatBank::verify( return {}; } -QString gtwMellatBank::errorString(int _errCode) -{ +QString gtwMellatBank::errorString(int _errCode) { + Q_UNUSED(_errCode); + return "UNKNOWN"; } diff --git a/Modules/Account/moduleSrc/Payment/Gateways/gtwZibal.cpp b/Modules/Account/moduleSrc/Payment/Gateways/gtwZibal.cpp index 233e77d7..816789c2 100644 --- a/Modules/Account/moduleSrc/Payment/Gateways/gtwZibal.cpp +++ b/Modules/Account/moduleSrc/Payment/Gateways/gtwZibal.cpp @@ -42,8 +42,7 @@ stuPaymentResponse gtwZibal::request( PaymentLogic::log(gtwZibal::Name, __FUNCTION__, __LINE__, { _orderMD5, _amount, _callback, _desc }); - try - { + try { QJsonDocument Json = intfPaymentGateway::postJsonWithCurl( gtwZibal::URL_GTW_REQUEST, QJsonDocument(QJsonObject({ @@ -78,9 +77,7 @@ stuPaymentResponse gtwZibal::request( QString(URL_GTW_PAY).replace("{{track_id}}", Response.value("trackId").toString()) ); - } - catch(std::exception &e) - { + } catch (std::exception &e) { PaymentLogic::log(gtwZibal::Name, __FUNCTION__, __LINE__, { e.what() }); throw; } @@ -96,8 +93,7 @@ stuPaymentResponse gtwZibal::verify( QString MerchantID = MetaInfo[gtwZibal::METAINFO_KEY_MERCHANT_ID].toString(); PaymentLogic::log(gtwZibal::Name, __FUNCTION__, __LINE__, { _pgResponse, _domain }); - try - { + try { QString OrderMD5 = _pgResponse.object().value("orderId").toString(); QString TrackID = _pgResponse.object().value("trackId").toString(); @@ -139,17 +135,14 @@ stuPaymentResponse gtwZibal::verify( ); return {}; - } - catch (std::exception &e) { + } catch (std::exception &e) { PaymentLogic::log(gtwZibal::Name, __FUNCTION__, __LINE__, { e.what() }); throw; } } -QString gtwZibal::errorString(int _errCode) -{ - switch (_errCode) - { +QString gtwZibal::errorString(int _errCode) { + switch (_errCode) { case 100 : return "Ok"; case 102 : return "Invalid API Key"; case 103 : return "Erroneous API Key"; diff --git a/Modules/Account/moduleSrc/Payment/PaymentLogic.cpp b/Modules/Account/moduleSrc/Payment/PaymentLogic.cpp index 82c1bfd3..21882f94 100644 --- a/Modules/Account/moduleSrc/Payment/PaymentLogic.cpp +++ b/Modules/Account/moduleSrc/Payment/PaymentLogic.cpp @@ -51,16 +51,14 @@ tmplConfigurable PaymentLogic::TransactionLogFile( enuConfigSource::Arg | enuConfigSource::File ); -void PaymentLogic::registerDriver(const QString& _driverName, intfPaymentGateway* _driver) -{ +void PaymentLogic::registerDriver(const QString& _driverName, intfPaymentGateway* _driver) { if (PaymentLogic::RegisteredDrivers.contains(_driverName)) throw Targoman::Common::exTargomanBase(QString("The class for driver name `%1` has been already registered").arg(_driverName)); qDebug() << "registering payment gateway driver:" << _driverName; PaymentLogic::RegisteredDrivers.insert(_driverName, _driver); } -intfPaymentGateway* PaymentLogic::getDriver(const QString& _driverName) -{ +intfPaymentGateway* PaymentLogic::getDriver(const QString& _driverName) { if (PaymentLogic::RegisteredDrivers.contains(_driverName) == false) throw Targoman::Common::exTargomanBase(QString("The class with driver name `%1` has not been registered").arg(_driverName)); @@ -200,10 +198,8 @@ QString PaymentLogic::createOnlinePaymentLink( //3: create payment TAPI::MD5_t onpMD5; quint8 Retries = 0; - while (true) - { - try - { + while (true) { + try { onpMD5 = OnlinePayments::instance() .callSP("spOnlinePayment_Create", { { "iVoucherID", _vchID }, @@ -215,16 +211,13 @@ QString PaymentLogic::createOnlinePaymentLink( .toString() ; break; - } - catch (...) - { + } catch (...) { if (++Retries > 3) throw; } } - try - { + try { _outPaymentMD5 = onpMD5; QString Callback = URLHelper::addParameter(_paymentVerifyCallback, "paymentMD5", onpMD5); @@ -238,8 +231,7 @@ QString PaymentLogic::createOnlinePaymentLink( _invDesc ); - if (PaymentResponse.ErrorCode) - { + if (PaymentResponse.ErrorCode) { /*Targoman::API::Query::*/OnlinePayments::instance().Update( OnlinePayments::instance(), SYSTEM_USER_ID, @@ -268,32 +260,23 @@ QString PaymentLogic::createOnlinePaymentLink( }); //increase pgwSumRequestCount and pgwSumRequestAmount - try - { + try { Targoman::API::AccountModule::ORM::PaymentGateways::instance() .callSP("spPaymentGateway_UpdateRequestCounters", { { "iPgwID", PaymentGateway.pgwID }, { "iAmount", _toPay }, }) ; - } - catch (...) - { - } + } catch (...) + { ; } //5: return result for client redirecting return PaymentResponse.PaymentLink; - } - catch(exPayment&) - { + } catch (exPayment&) { throw; - } - catch(exHTTPBadRequest&) - { + } catch (exHTTPBadRequest&) { throw; - } - catch(std::exception &e) - { + } catch (std::exception &e) { /*Targoman::API::Query::*/OnlinePayments::instance().Update( OnlinePayments::instance(), SYSTEM_USER_ID, @@ -391,18 +374,15 @@ quint64 PaymentLogic::approveOnlinePayment( //update pgwLastPaymentDateTime and pgwSumTodayPaidAmount //increase pgwSumOkCount and pgwSumPaidAmount - try - { + try { Targoman::API::AccountModule::ORM::PaymentGateways::instance() .callSP("spPaymentGateway_UpdateOkCounters", { { "iPgwID", OnlinePayment.onp_pgwID }, { "iAmount", OnlinePayment.onpAmount }, }) ; - } - catch (...) - { - } + } catch (...) + { ; } /*Targoman::API::Query::*/Targoman::API::AccountModule::ORM::PaymentGateways::instance().Update( Targoman::API::AccountModule::ORM::PaymentGateways::instance(), diff --git a/Modules/Account/moduleSrc/Payment/intfPaymentGateway.h b/Modules/Account/moduleSrc/Payment/intfPaymentGateway.h index 3a9f7f2c..c82cbc7c 100644 --- a/Modules/Account/moduleSrc/Payment/intfPaymentGateway.h +++ b/Modules/Account/moduleSrc/Payment/intfPaymentGateway.h @@ -67,20 +67,20 @@ struct stuPaymentResponse { ///TODO: why -1???? // ErrorCode(-1) ErrorCode(0) - {} + { ; } stuPaymentResponse(const QString& _trackID, const QString& _paymentLink) : ErrorCode(0), TrackID(_trackID), PaymentLink(_paymentLink) - {} + { ; } stuPaymentResponse(const QString _orderMD5, const QString& _result, int _errorCode, const QString& _errStr) : ErrorCode(_errorCode), ErrorString(_errStr), Result(_result), OrderMD5(_orderMD5) - {} + { ; } }; namespace Payment { @@ -127,7 +127,7 @@ private: \ //PaymentLogic::registerDriver<_gatewayClassName>(_gatewayClassName::Name); #define TARGOMAN_IMPL_API_PAYMENT_GATEWAY(_gatewayClassName) \ - _gatewayClassName::_gatewayClassName() {} + _gatewayClassName::_gatewayClassName() { ; } /** * @brief The intfPaymentGateway class is base class of gateway drivers @@ -153,8 +153,7 @@ class intfPaymentGateway ) = 0; virtual QString errorString(int _errCode) { return QString("unknown error %1").arg(_errCode); } - static QJsonDocument postJsonWithCurl(const QString _url, const QJsonDocument& _json, bool _jsonDecode = true) - { + static QJsonDocument postJsonWithCurl(const QString _url, const QJsonDocument& _json, bool _jsonDecode = true) { QtCUrl CUrl; CUrl.setTextCodec("UTF-8"); @@ -174,9 +173,9 @@ class intfPaymentGateway if (CUrl.lastError().code() == CURLE_OPERATION_TIMEDOUT) throw exPayment("Connection to <" + _url +"> timed out."); - else if(CUrl.lastError().code() == CURLE_COULDNT_CONNECT) + else if (CUrl.lastError().code() == CURLE_COULDNT_CONNECT) throw exPayment("Connection to <" + _url +"> failed."); - else if(CUrl.lastError().isOk() == false) + else if (CUrl.lastError().isOk() == false) throw exPayment("Connection to <" + _url + "> error: " + CUrl.lastError().text()); if (_jsonDecode) { @@ -201,8 +200,7 @@ class intfPaymentGateway CallBackDomain(_basePath + "CallBackdomain", "Domain used for callback"), Gateway(_basePath + "Gateway", "Gateway to be used for this callback"), CustomerID(_basePath + "Gateway", "Customer ID on the gateway"), - PrivateToken(_basePath + "Gateway", "PrivateToken for gateway if required") - {} + PrivateToken(_basePath + "Gateway", "PrivateToken for gateway if required") { ; } Targoman::Common::Configuration::tmplConfigurable CallBackDomain; Targoman::Common::Configuration::tmplConfigurable Gateway; diff --git a/Modules/Advert/functionalTest/ORM/actionLogs.hpp b/Modules/Advert/functionalTest/ORM/actionLogs.hpp index 99309072..840182f2 100644 --- a/Modules/Advert/functionalTest/ORM/actionLogs.hpp +++ b/Modules/Advert/functionalTest/ORM/actionLogs.hpp @@ -33,13 +33,13 @@ class testActionLogs: public clsBaseTest Q_OBJECT public: - testActionLogs(const QString &_dbPrefix) : clsBaseTest(_dbPrefix) {} + testActionLogs(const QString &_dbPrefix) : clsBaseTest(_dbPrefix) { ; } private slots: - void unprivActionLogs(){ + void unprivActionLogs() { QVERIFY(callUserAPI(RESTClientHelper::GET, "Advert/ActionLogs").toString().isEmpty()); } - void privActionLogs(){ + void privActionLogs() { QVERIFY(callAdminAPI(RESTClientHelper::GET, "Advert/ActionLogs").toString().isEmpty()); } }; diff --git a/Modules/Advert/functionalTest/main.cpp b/Modules/Advert/functionalTest/main.cpp index f56fb51f..85632d1b 100644 --- a/Modules/Advert/functionalTest/main.cpp +++ b/Modules/Advert/functionalTest/main.cpp @@ -28,8 +28,7 @@ TAPI_MARSHAL_TEST_VARIABLES -int main(int _argc, char *_argv[]) -{ +int main(int _argc, char *_argv[]) { qDebug() << "--------------------------------------------------"; qDebug() << "-- test module: Advert ---------------------------"; qDebug() << "--------------------------------------------------"; @@ -56,15 +55,12 @@ int main(int _argc, char *_argv[]) bool BreakOnFirstFail = true; int FailedTests = 0; - try - { + try { FailedTests += QTest::qExec(new testBase(DBPrefix), progArgsCount, progArgs); if (BreakOnFirstFail && !FailedTests) FailedTests += QTest::qExec(new testAdvert(DBPrefix), progArgsCount, progArgs); if (BreakOnFirstFail && !FailedTests) FailedTests += QTest::qExec(new testAdvertFixture(DBPrefix), progArgsCount, progArgs); if (BreakOnFirstFail && !FailedTests) FailedTests += QTest::qExec(new testActionLogs(DBPrefix), progArgsCount, progArgs); - } - catch(std::exception &e) - { + } catch (std::exception &e) { qDebug() << e.what(); } diff --git a/Modules/Advert/functionalTest/testAdvert.hpp b/Modules/Advert/functionalTest/testAdvert.hpp index 73a90c5d..b97d83bf 100644 --- a/Modules/Advert/functionalTest/testAdvert.hpp +++ b/Modules/Advert/functionalTest/testAdvert.hpp @@ -53,7 +53,7 @@ class testAdvert : public clsBaseTest Q_OBJECT public: - testAdvert(const QString &_dbPrefix) : clsBaseTest(_dbPrefix) {} + testAdvert(const QString &_dbPrefix) : clsBaseTest(_dbPrefix) { ; } QString LastRandomNumber; QString CreatedUserEmail; @@ -71,20 +71,17 @@ class testAdvert : public clsBaseTest Targoman::API::AAA::stuVoucher Voucher; Targoman::API::AAA::stuVoucher ApproveOnlinePaymentVoucher; - void cleanupUnitTestData() - { + void cleanupUnitTestData() { clsDAC DAC; DAC.execQuery("", QString("UPDATE %1AAA.tblUser SET usrStatus='R' WHERE usrEmail IN(?,?)").arg(this->DBPrefix), { UT_UserEmail, UT_AdminUserEmail }); } private slots: - void initTestCase() - { + void initTestCase() { initUnitTestData(false); } - void cleanupTestCase() - { + void cleanupTestCase() { gEncodedAdminJWT = ""; gEncodedJWT = ""; cleanupUnitTestData(); @@ -93,8 +90,7 @@ private slots: /***************************************************************************************/ /***************************************************************************************/ /***************************************************************************************/ - void setupAccountFixture() - { + void setupAccountFixture() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::POST, @@ -121,8 +117,7 @@ private slots: } } - void login_user() - { + void login_user() { //5d12d36cd5f66fe3e72f7b03cbb75333 = MD5(1234 + df6d2338b2b8fce1ec2f6dda0a630eb0 # 987) QVariant Result = callUserAPI(RESTClientHelper::POST, "Account/login",{},{ @@ -139,8 +134,7 @@ private slots: QVERIFY(clsJWT(gJWT).usrStatus() == TAPI::enuUserStatus::Active); } - void login_admin() - { + void login_admin() { //5d12d36cd5f66fe3e72f7b03cbb75333 = MD5(1234 + df6d2338b2b8fce1ec2f6dda0a630eb0 # 987) QVariant Result = callUserAPI(RESTClientHelper::POST, "Account/login",{},{ @@ -157,8 +151,7 @@ private slots: QVERIFY(clsJWT(gAdminJWT).usrStatus() == TAPI::enuUserStatus::Active); } - void createLocation() - { + void createLocation() { QString url = QString("http://www.%1.com").arg(SecurityHelper::UUIDtoMD5()); QT_TRY { @@ -181,8 +174,7 @@ private slots: } } - void createProduct_banner() - { + void createProduct_banner() { this->BannerProductCode = QString("p%1").arg(QRandomGenerator::global()->generate()); QT_TRY { @@ -208,8 +200,7 @@ private slots: } } - void createSaleable_banner() - { + void createSaleable_banner() { this->BannerSaleableCode = QString("%1-s%2").arg(this->BannerProductCode).arg(QRandomGenerator::global()->generate()); QT_TRY { @@ -239,8 +230,7 @@ private slots: } } /* - void createPaymentGateway_devtest() - { + void createPaymentGateway_devtest() { auto ret = callAdminAPI( RESTClientHelper::GET, "Account/PaymentGateways", @@ -256,10 +246,8 @@ private slots: // qDebug() << "--------- PaymentGateways: " << ret; auto totalRows = ret["totalRows"].toUInt(); - if (totalRows < 3) - { - for (int i=totalRows; i<3; ++i) - { + if (totalRows < 3) { + for (int i=totalRows; i<3; ++i) { QT_TRY { auto paymentGatewayID = callAdminAPI( RESTClientHelper::PUT, @@ -305,8 +293,7 @@ private slots: } } //*/ - void addToBasket_invalid_saleable_code() - { + void addToBasket_invalid_saleable_code() { QT_TRY { // QVERIFY_EXCEPTION_THROWN QVariant result = callAdminAPI( @@ -335,8 +322,7 @@ private slots: } } - void addToBasket_invalid_coupon_qty_not_available() - { + void addToBasket_invalid_coupon_qty_not_available() { QT_TRY { QVariant result = callAdminAPI( RESTClientHelper::POST, @@ -360,8 +346,7 @@ private slots: } } - void addToBasket_invalid_coupon_code() - { + void addToBasket_invalid_coupon_code() { QT_TRY { QVariant result = callAdminAPI( RESTClientHelper::POST, @@ -385,8 +370,7 @@ private slots: } } - void createDiscount() - { + void createDiscount() { this->CouponCode = QString("cpn-code-%1").arg(QRandomGenerator::global()->generate()); QT_TRY { @@ -429,8 +413,7 @@ private slots: } } - void addToBasket_valid_coupon_code_1() - { + void addToBasket_valid_coupon_code_1() { QT_TRY { int ItemsCount = this->LastPreVoucher.Items.length(); @@ -462,8 +445,7 @@ private slots: ///TODO: removeBasketItem - void addToBasket_valid_coupon_code_2() - { + void addToBasket_valid_coupon_code_2() { QT_TRY { int ItemsCount = this->LastPreVoucher.Items.length(); @@ -495,8 +477,7 @@ private slots: ///TODO: updateBasketItem - void addToBasket_valid_coupon_code_3() - { + void addToBasket_valid_coupon_code_3() { QT_TRY { int ItemsCount = this->LastPreVoucher.Items.length(); @@ -526,8 +507,7 @@ private slots: } } - void finalizeBasket_empty_items() - { + void finalizeBasket_empty_items() { QT_TRY { QVariant result = callAdminAPI( RESTClientHelper::POST, @@ -549,8 +529,7 @@ private slots: } } - void finalizeBasket() - { + void finalizeBasket() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::POST, @@ -576,10 +555,8 @@ private slots: } } - void approveOnlinePayment() - { - if (this->Voucher.PaymentMD5.isEmpty() == false) - { + void approveOnlinePayment() { + if (this->Voucher.PaymentMD5.isEmpty() == false) { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::POST, @@ -638,8 +615,7 @@ private slots: // Targoman::API::AAA::stuVoucher voucher; // Targoman::API::AAA::stuPreVoucher lastPreVoucher; - void deleteDiscount() - { + void deleteDiscount() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::DELETE, @@ -675,10 +651,8 @@ private slots: // } // } - void deleteSaleable_banner() - { - if (this->BannerSaleableID > 0) - { + void deleteSaleable_banner() { + if (this->BannerSaleableID > 0) { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::DELETE, @@ -695,10 +669,8 @@ private slots: } } - void deleteProduct_banner() - { - if (this->BannerProductID > 0) - { + void deleteProduct_banner() { + if (this->BannerProductID > 0) { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::DELETE, @@ -715,10 +687,8 @@ private slots: } } - void deleteLocation() - { - if (this->LocationID > 0) - { + void deleteLocation() { + if (this->LocationID > 0) { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::DELETE, @@ -736,8 +706,7 @@ private slots: } /***************************************************************************************/ - void cleanupAccountFixture() - { + void cleanupAccountFixture() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::POST, diff --git a/Modules/Advert/functionalTest/testAdvertFixture.hpp b/Modules/Advert/functionalTest/testAdvertFixture.hpp index 2e213703..3fad0852 100644 --- a/Modules/Advert/functionalTest/testAdvertFixture.hpp +++ b/Modules/Advert/functionalTest/testAdvertFixture.hpp @@ -53,7 +53,7 @@ class testAdvertFixture : public clsBaseTest Q_OBJECT public: - testAdvertFixture(const QString &_dbPrefix) : clsBaseTest(_dbPrefix) {} + testAdvertFixture(const QString &_dbPrefix) : clsBaseTest(_dbPrefix) { ; } QString LastRandomNumber; QString CreatedUserEmail; @@ -71,20 +71,17 @@ class testAdvertFixture : public clsBaseTest // Targoman::API::AAA::stuVoucher Voucher; // Targoman::API::AAA::stuVoucher ApproveOnlinePaymentVoucher; - void cleanupUnitTestData() - { + void cleanupUnitTestData() { clsDAC DAC; DAC.execQuery("", QString("UPDATE %1AAA.tblUser SET usrStatus='R' WHERE usrEmail IN(?,?)").arg(this->DBPrefix), { UT_UserEmail, UT_AdminUserEmail }); } private slots: - void initTestCase() - { + void initTestCase() { initUnitTestData(false); } - void cleanupTestCase() - { + void cleanupTestCase() { gEncodedAdminJWT = ""; gEncodedJWT = ""; cleanupUnitTestData(); @@ -93,8 +90,7 @@ private slots: /***************************************************************************************/ /***************************************************************************************/ /***************************************************************************************/ - void setupAccountFixture() - { + void setupAccountFixture() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::POST, @@ -121,8 +117,7 @@ private slots: } } - void login_user() - { + void login_user() { //5d12d36cd5f66fe3e72f7b03cbb75333 = MD5(1234 + df6d2338b2b8fce1ec2f6dda0a630eb0 # 987) QVariant Result = callUserAPI(RESTClientHelper::POST, "Account/login",{},{ @@ -139,8 +134,7 @@ private slots: QVERIFY(clsJWT(gJWT).usrStatus() == TAPI::enuUserStatus::Active); } - void login_admin() - { + void login_admin() { //5d12d36cd5f66fe3e72f7b03cbb75333 = MD5(1234 + df6d2338b2b8fce1ec2f6dda0a630eb0 # 987) QVariant Result = callUserAPI(RESTClientHelper::POST, "Account/login",{},{ @@ -157,8 +151,7 @@ private slots: QVERIFY(clsJWT(gAdminJWT).usrStatus() == TAPI::enuUserStatus::Active); } - void setupAdvertFixture() - { + void setupAdvertFixture() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::POST, @@ -182,8 +175,7 @@ private slots: /***************************************************************************************/ /* cleanup *****************************************************************************/ /***************************************************************************************/ - void cleanupAdvertFixture() - { + void cleanupAdvertFixture() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::POST, @@ -202,8 +194,7 @@ private slots: } } - void cleanupAccountFixture() - { + void cleanupAccountFixture() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::POST, diff --git a/Modules/Advert/moduleSrc/Advert.cpp b/Modules/Advert/moduleSrc/Advert.cpp index 738ebfb3..c7c065e5 100644 --- a/Modules/Advert/moduleSrc/Advert.cpp +++ b/Modules/Advert/moduleSrc/Advert.cpp @@ -114,8 +114,7 @@ stuServiceCreditsInfo Advert::retrieveServiceCreditsInfo(quint64 _usrID) ); } -void Advert::breakCredit(quint64 _slbID) -{ +void Advert::breakCredit(quint64 _slbID) { } bool Advert::isUnlimited(const UsageLimits_t& _limits) const @@ -126,9 +125,11 @@ bool Advert::isEmpty(const UsageLimits_t& _limits) const { } -void Advert::applyAssetAdditives(TAPI::JWT_t _JWT, - INOUT stuAssetItem& _assetItem, - const OrderAdditives_t& _orderAdditives) +void Advert::applyAssetAdditives( + TAPI::JWT_t _JWT, + INOUT stuAssetItem& _assetItem, + const OrderAdditives_t& _orderAdditives + ) { // qDebug() << "----------" << "_orderAdditives:" << _orderAdditives; @@ -169,7 +170,8 @@ Targoman::API::AdvertModule::stuAdvert Advert::apiGETnewBanner( QString _location, Targoman::API::AdvertModule::enuAdvertOrder::Type _order ) -{} +{ +} Targoman::API::AdvertModule::stuAdvert Advert::apiGETnewText( TAPI::RemoteIP_t _REMOTE_IP, @@ -177,7 +179,8 @@ Targoman::API::AdvertModule::stuAdvert Advert::apiGETnewText( Targoman::API::AdvertModule::enuAdvertOrder::Type _order, const QString _keywords ) -{} +{ +} QString Advert::apiGETretrieveURL( TAPI::RemoteIP_t _REMOTE_IP, @@ -185,7 +188,8 @@ QString Advert::apiGETretrieveURL( TAPI::IPv4_t _clientIP, QString _agent ) -{} +{ +} /****************************************************************\ |** fixture *****************************************************| @@ -397,8 +401,7 @@ QVariant Advert::apiPOSTfixtureSetup( Result.insert("Voucher", Voucher.toJson()); //-- approve online payment -------------------------------------- - if (Voucher.PaymentMD5.isEmpty() == false) - { + if (Voucher.PaymentMD5.isEmpty() == false) { QVariant res = RESTClientHelper::callAPI( _JWT, RESTClientHelper::POST, @@ -441,8 +444,7 @@ QVariant Advert::apiPOSTfixtureCleanup( //online payment //voucher - try - { + try { QString CouponCode = FixtureHelper::MakeRandomizeName(_random, ".", "fixture", "cpn"); QString QueryString = R"( DELETE c @@ -456,13 +458,9 @@ QVariant Advert::apiPOSTfixtureCleanup( { "items", CouponCode }, { "numRowsAffected", DACResult.numRowsAffected() }, })); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString SaleableCode = (_random.isEmpty() ? "0-0" : QString("%1-%1").arg(_random)); QString QueryString = R"( DELETE s @@ -476,13 +474,9 @@ QVariant Advert::apiPOSTfixtureCleanup( { "items", SaleableCode }, { "numRowsAffected", DACResult.numRowsAffected() }, })); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString ProductCode = FixtureHelper::MakeRandomizeName(_random, ".", "fixture", "product"); QString QueryString = R"( DELETE p @@ -496,13 +490,9 @@ QVariant Advert::apiPOSTfixtureCleanup( { "items", ProductCode }, { "numRowsAffected", DACResult.numRowsAffected() }, })); - } - catch(...) - { - } + } catch (...) { ; } - try - { + try { QString LocationUrl = FixtureHelper::MakeRandomizeName(_random, ".", "http://fixture", "com"); QString QueryString = R"( DELETE l @@ -516,10 +506,7 @@ QVariant Advert::apiPOSTfixtureCleanup( { "items", LocationUrl }, { "numRowsAffected", DACResult.numRowsAffected() }, })); - } - catch(...) - { - } + } catch (...) { ; } return Result; } diff --git a/Modules/Advert/moduleSrc/ORM/Accounting.cpp b/Modules/Advert/moduleSrc/ORM/Accounting.cpp index 6ada7cfd..8473a75f 100644 --- a/Modules/Advert/moduleSrc/ORM/Accounting.cpp +++ b/Modules/Advert/moduleSrc/ORM/Accounting.cpp @@ -52,7 +52,7 @@ AccountProducts::AccountProducts() { tblAccountProducts::prd_locID, R(AdvertSchema, tblLocations::Name), tblLocations::locID }, } ) -{} +{ ; } /******************************************************/ AccountSaleables::AccountSaleables() @@ -65,7 +65,7 @@ AccountSaleables::AccountSaleables() { tblAccountSaleables::slbClicksTotal, S(quint64), QFV.integer().minValue(-1), -1, UPOwner }, } ) -{} +{ ; } /******************************************************/ AccountUserAssets::AccountUserAssets() @@ -73,7 +73,7 @@ AccountUserAssets::AccountUserAssets() {///< ColName Type Validation Default UpBy Sort Filter Self Virt PK ADVERT_DEFINE_ASSET_FIELDS("uas") }) -{} +{ ; } /******************************************************/ AccountAssetUsage::AccountAssetUsage() @@ -82,11 +82,11 @@ AccountAssetUsage::AccountAssetUsage() ADVERT_DEFINE_ASSET_FIELDS("usg") } ) -{} +{ ; } /******************************************************/ AccountCoupons::AccountCoupons() : intfAccountCoupons(AdvertSchema) -{} +{ ; } } // namespace Targoman::API::AdvertModule::ORM diff --git a/Modules/Advert/moduleSrc/ORM/ActiveAds.cpp b/Modules/Advert/moduleSrc/ORM/ActiveAds.cpp index 02756956..7c37fee2 100644 --- a/Modules/Advert/moduleSrc/ORM/ActiveAds.cpp +++ b/Modules/Advert/moduleSrc/ORM/ActiveAds.cpp @@ -32,8 +32,7 @@ namespace Targoman::API::AdvertModule::ORM { //using namespace ORM; -QVariant ActiveAds::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant ActiveAds::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); @@ -43,8 +42,7 @@ QVariant ActiveAds::apiGET(GET_METHOD_ARGS_IMPL_APICALL) // return this->selectFromTable({}, {}, GET_METHOD_CALL_ARGS_APICALL); } -bool ActiveAds::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool ActiveAds::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())); return /*Targoman::API::Query::*/this->DeleteByPks(*this, DELETE_METHOD_CALL_ARGS_INTERNAL_CALL); @@ -63,7 +61,6 @@ ActiveAds::ActiveAds() : {tblActiveAds::act_binID, R(AdvertSchema,tblBin::Name), tblBin::binID}, {tblActiveAds::act_locID, R(AdvertSchema,tblLocations::Name), tblLocations::locID }, }) -{ -} +{ ; } } //namespace Targoman::API::AdvertModule::ORM diff --git a/Modules/Advert/moduleSrc/ORM/Bin.cpp b/Modules/Advert/moduleSrc/ORM/Bin.cpp index ce752d32..ab0a0eb2 100644 --- a/Modules/Advert/moduleSrc/ORM/Bin.cpp +++ b/Modules/Advert/moduleSrc/ORM/Bin.cpp @@ -52,10 +52,9 @@ Bin::Bin() : ORM_RELATION_OF_CREATOR(tblBin::binCreatedBy_usrID), ORM_RELATION_OF_UPDATER(tblBin::binUpdatedBy_usrID), }) -{} +{ ; } -QVariant Bin::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant Bin::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); @@ -77,7 +76,6 @@ Banners::Banners() : ORM_RELATION_OF_UPDATER(tblBanners::bnrUpdatedBy_usrID), } ) -{ -} +{ ; } } //namespace Targoman::API::AdvertModule::ORM diff --git a/Modules/Advert/moduleSrc/ORM/Clicks.cpp b/Modules/Advert/moduleSrc/ORM/Clicks.cpp index 466cf8ce..839d5a80 100644 --- a/Modules/Advert/moduleSrc/ORM/Clicks.cpp +++ b/Modules/Advert/moduleSrc/ORM/Clicks.cpp @@ -32,8 +32,7 @@ namespace Targoman::API::AdvertModule::ORM { //using namespace ORM; -QVariant Clicks::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant Clicks::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())) == false) this->setSelfFilters({{tblBin::binID, clsJWT(_JWT).usrID()}}, _filters); @@ -62,7 +61,6 @@ Clicks::Clicks() : {tblClicks::clk_binID, R(AdvertSchema,tblBin::Name), tblBin::binID}, {tblClicks::clk_locID, R(AdvertSchema,tblLocations::Name), tblLocations::locID }, }) -{ -} +{ ; } } //namespace Targoman::API::AdvertModule::ORM diff --git a/Modules/Advert/moduleSrc/ORM/Locations.cpp b/Modules/Advert/moduleSrc/ORM/Locations.cpp index 7647816b..ba6d66e6 100644 --- a/Modules/Advert/moduleSrc/ORM/Locations.cpp +++ b/Modules/Advert/moduleSrc/ORM/Locations.cpp @@ -60,31 +60,27 @@ Locations::Locations() : { tblLocations::locUpdatedBy_usrID }, } ) -{} +{ ; } -QVariant Locations::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant Locations::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); } -quint32 Locations::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) -{ +quint32 Locations::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PUT, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Create(*this, CREATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool Locations::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool Locations::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PATCH, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool Locations::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool Locations::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())); return /*Targoman::API::Query::*/this->DeleteByPks(*this, DELETE_METHOD_CALL_ARGS_INTERNAL_CALL); diff --git a/Modules/Advert/moduleSrc/ORM/Props.cpp b/Modules/Advert/moduleSrc/ORM/Props.cpp index 651b6efd..fa06fa5d 100644 --- a/Modules/Advert/moduleSrc/ORM/Props.cpp +++ b/Modules/Advert/moduleSrc/ORM/Props.cpp @@ -31,8 +31,7 @@ namespace Targoman::API::AdvertModule::ORM { //using namespace ORM; -QVariant Props::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant Props::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())) == false) this->setSelfFilters({{tblBin::binID, clsJWT(_JWT).usrID()}}, _filters); @@ -43,8 +42,7 @@ QVariant Props::apiGET(GET_METHOD_ARGS_IMPL_APICALL) return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL, {}, 0, QueryLambda); } -quint64 Props::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) -{ +quint64 Props::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) { if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())) == false) _createInfo.insert(tblBin::binID, clsJWT(_JWT).usrID()); // this->setSelfFilters({{tblBin::binID, clsJWT(_JWT).usrID()}}, _createInfo); @@ -52,8 +50,7 @@ quint64 Props::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) return /*Targoman::API::Query::*/this->Create(*this, CREATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool Props::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool Props::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { QVariantMap ExtraFilters; if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_PATCH,this->moduleBaseName()))) @@ -63,8 +60,7 @@ bool Props::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL, ExtraFilters); } -bool Props::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool Props::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { QVariantMap ExtraFilters; if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())) == false) ExtraFilters.insert(tblBin::binID, clsJWT(_JWT).usrID()); @@ -93,7 +89,6 @@ Props::Props() : ORM_RELATION_OF_CREATOR(tblProps::prpCreatedBy_usrID), ORM_RELATION_OF_UPDATER(tblProps::prpUpdatedBy_usrID), }) -{ -} +{ ; } } //namespace Targoman::API::AdvertModule::ORM diff --git a/Modules/Common/functionalTest/main.cpp b/Modules/Common/functionalTest/main.cpp index 86c688a3..4c4812da 100644 --- a/Modules/Common/functionalTest/main.cpp +++ b/Modules/Common/functionalTest/main.cpp @@ -27,8 +27,7 @@ TAPI_MARSHAL_TEST_VARIABLES -int main(int _argc, char *_argv[]) -{ +int main(int _argc, char *_argv[]) { qDebug() << "--------------------------------------------------"; qDebug() << "-- test module: Common ---------------------------"; qDebug() << "--------------------------------------------------"; @@ -57,7 +56,7 @@ int main(int _argc, char *_argv[]) try { FailedTests += QTest::qExec(new testBase(DBPrefix), progArgsCount, progArgs); if (BreakOnFirstFail && !FailedTests) FailedTests += QTest::qExec(new testCommon(DBPrefix), progArgsCount, progArgs); - } catch(std::exception &e) { + } catch (std::exception &e) { qDebug()< 0) { diff --git a/Modules/Common/functionalTest/testCommon.hpp b/Modules/Common/functionalTest/testCommon.hpp index c0f6e087..13bd5963 100644 --- a/Modules/Common/functionalTest/testCommon.hpp +++ b/Modules/Common/functionalTest/testCommon.hpp @@ -52,22 +52,19 @@ class testCommon : public clsBaseTest Q_OBJECT public: - testCommon(const QString &_dbPrefix) : clsBaseTest(_dbPrefix) {} + testCommon(const QString &_dbPrefix) : clsBaseTest(_dbPrefix) { ; } - void cleanupUnitTestData() - { + void cleanupUnitTestData() { clsDAC DAC; DAC.execQuery("", QString("UPDATE %1AAA.tblUser SET usrStatus='R' WHERE usrEmail IN(?,?)").arg(this->DBPrefix), { UT_UserEmail, UT_AdminUserEmail }); } private slots: - void initTestCase() - { + void initTestCase() { initUnitTestData(false); } - void cleanupTestCase() - { + void cleanupTestCase() { gEncodedAdminJWT = ""; gEncodedJWT = ""; cleanupUnitTestData(); diff --git a/Modules/Common/moduleSrc/ORM/Alerts.cpp b/Modules/Common/moduleSrc/ORM/Alerts.cpp index 506b8f6d..0d0a92f1 100644 --- a/Modules/Common/moduleSrc/ORM/Alerts.cpp +++ b/Modules/Common/moduleSrc/ORM/Alerts.cpp @@ -38,10 +38,9 @@ Alerts::Alerts() : // "" ), intfAlerts() -{} +{ ; } -QVariant Alerts::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant Alerts::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); // return this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); diff --git a/Modules/FormalityChecker/FormalityChecker.cpp b/Modules/FormalityChecker/FormalityChecker.cpp index 7d9dc09d..41c780ae 100644 --- a/Modules/FormalityChecker/FormalityChecker.cpp +++ b/Modules/FormalityChecker/FormalityChecker.cpp @@ -32,17 +32,15 @@ TARGOMAN_IMPL_API_MODULE(FormalityChecker) FormalityChecker::FormalityChecker() : intfPureModule("Targoman") -{} +{ ; } -bool FormalityChecker::init() -{ +bool FormalityChecker::init() { NLP::FormalityChecker::instance(); return true; } -QString FormalityChecker::apiCheck(const QString _text, const TAPI::ISO639_2_t& _lang) -{ +QString FormalityChecker::apiCheck(const QString _text, const TAPI::ISO639_2_t& _lang) { return NLP::FormalityChecker::instance().check(_lang, _text); } diff --git a/Modules/FormalityChecker/FormalityChecker.h b/Modules/FormalityChecker/FormalityChecker.h index 65d3aa30..ae645836 100644 --- a/Modules/FormalityChecker/FormalityChecker.h +++ b/Modules/FormalityChecker/FormalityChecker.h @@ -29,7 +29,7 @@ namespace Targoman { namespace API { #ifndef API -#define API(_method, _name, _sig, _doc) api##_method##_name _sig; QString signOf##_method##_name(){ return #_sig; } QString docOf##_method##_name(){ return _doc; } +#define API(_method, _name, _sig, _doc) api##_method##_name _sig; QString signOf##_method##_name() { return #_sig; } QString docOf##_method##_name() { return _doc; } #endif class FormalityChecker : public intfPureModule diff --git a/Modules/MT/Classes/TranslationDispatcher.cpp b/Modules/MT/Classes/TranslationDispatcher.cpp index 19e265ff..0aa56758 100644 --- a/Modules/MT/Classes/TranslationDispatcher.cpp +++ b/Modules/MT/Classes/TranslationDispatcher.cpp @@ -43,8 +43,7 @@ using namespace Common::Configuration; using namespace AAA; using namespace NLP; -TranslationDispatcher::~TranslationDispatcher() -{ ; } +TranslationDispatcher::~TranslationDispatcher() {/*KZ*/ ; } QVariantMap TranslationDispatcher::doTranslation(const QJsonObject& _privInfo, QString _text, @@ -54,44 +53,43 @@ QVariantMap TranslationDispatcher::doTranslation(const QJsonObject& _privInfo, bool _detailed, bool _detokenize, int& _preprocessTime, - int& _translationTime) -{ - if(_detailed && Authorization::hasPriv(_privInfo, {TARGOMAN_PRIV_PREFIX + "Detailed"}) == false) + int& _translationTime) {/*KZ*/ + if (_detailed && Authorization::hasPriv(_privInfo, {TARGOMAN_PRIV_PREFIX + "Detailed"}) == false) throw exAuthorization("Not enought priviledges to get detailed translation response."); QTime CacheLookupTime; CacheLookupTime.start(); QString CacheKey = QCryptographicHash::hash(QString("%1:%2:%3:%4:%5").arg(_useSpecialClass).arg(_engine, _dir.first, _dir.second, _text).toUtf8(),QCryptographicHash::Md4).toHex(); QVariantMap CachedTranslation = this->TranslationCache[CacheKey]; - if(CachedTranslation.isEmpty()){ + if (CachedTranslation.isEmpty()) { QTime Timer;Timer.start(); QString Class; intfTranslatorEngine* TranslationEngine = nullptr; - if(_useSpecialClass){ + if (_useSpecialClass) { Class = this->detectClass(_engine, _text, _dir.first); TranslationEngine = this->RegisteredEngines.value(stuEngineSpecs::makeFullName(_engine, _dir.first, _dir.second, Class)); } - if(TranslationEngine == nullptr) + if (TranslationEngine == nullptr) TranslationEngine = this->RegisteredEngines.value(stuEngineSpecs::makeFullName(_engine, _dir.first, _dir.second)); - if(TranslationEngine == nullptr) + if (TranslationEngine == nullptr) throw exHTTPInternalServerError("Unable to find generic translator engine"); _text = this->preprocessText(_text, _dir.first); _preprocessTime = Timer.elapsed();Timer.restart(); - if(TranslationEngine->specs().SupportsIXML == false) + if (TranslationEngine->specs().SupportsIXML == false) _text = TargomanTextProcessor::instance().ixml2Text(_text, false, false,false); CachedTranslation = TranslationEngine->doTranslation(_text, _detailed, _detokenize); _translationTime = Timer.elapsed(); - if(Class.size() && Authorization::hasPriv(_privInfo, {TARGOMAN_PRIV_PREFIX + "ReportClass"})) + if (Class.size() && Authorization::hasPriv(_privInfo, {TARGOMAN_PRIV_PREFIX + "ReportClass"})) CachedTranslation[RESULTItems::CLASS] = Class; - if(CachedTranslation.value(RESULTItems::ERRNO, 0).toInt() == 0) + if (CachedTranslation.value(RESULTItems::ERRNO, 0).toInt() == 0) this->TranslationCache.insert(CacheKey, CachedTranslation); - else{ - switch(CachedTranslation.value(RESULTItems::ERRNO, 0).toInt()){ + else { + switch (CachedTranslation.value(RESULTItems::ERRNO, 0).toInt()) { case enuTranslationError::Ok: break; case enuTranslationError::OperationTimedOut: @@ -105,28 +103,26 @@ QVariantMap TranslationDispatcher::doTranslation(const QJsonObject& _privInfo, throw exHTTPExpectationFailed(CachedTranslation.value(RESULTItems::MESSAGE).toString()); } } - }else{ + } else { CachedTranslation[RESULTItems::CACHE] = CacheLookupTime.elapsed(); } return CachedTranslation; } -QString TranslationDispatcher::detectClass(const QString& _engine, const QString& _text, const QString& _lang) -{ +QString TranslationDispatcher::detectClass(const QString& _engine, const QString& _text, const QString& _lang) {/*KZ*/ Q_UNUSED(_engine); - if(gConfigs::Classifier::SupportsIXML.value()== false) + if (gConfigs::Classifier::SupportsIXML.value()== false) return FormalityChecker::instance().check(_lang, TargomanTextProcessor::instance().ixml2Text(_text, false, false,false)); else return FormalityChecker::instance().check(_lang, _text); } -QString TranslationDispatcher::preprocessText(const QString& _text, const QString& _lang) -{ +QString TranslationDispatcher::preprocessText(const QString& _text, const QString& _lang) {/*KZ*/ Q_UNUSED (_lang) clsDAC DAC;//TODO find moduleName - if(this->CorrectionRule.isEmpty() || this->LastCorrectionRuleUpdateTime.elapsed() > 3600){ + if (this->CorrectionRule.isEmpty() || this->LastCorrectionRuleUpdateTime.elapsed() > 3600) { clsDACResult Result = DAC.execQueryCacheable(3600,QString(), "SELECT crlPattern, crlReplacement FROM MT.tblCorrectionRules WHERE crlType = 'R'"); - if(Result.isValid()){ + if (Result.isValid()) { this->CorrectionRule.clear(); while(Result.next()) this->CorrectionRule.append( @@ -146,8 +142,7 @@ QString TranslationDispatcher::preprocessText(const QString& _text, const QStrin return Text; } -QString TranslationDispatcher::tokenize(const QString& _text, const QString& _lang) -{ +QString TranslationDispatcher::tokenize(const QString& _text, const QString& _lang) {/*KZ*/ bool SpellCorrected; QList SentenceBreakReplacements; SentenceBreakReplacements.append( @@ -167,44 +162,38 @@ QString TranslationDispatcher::tokenize(const QString& _text, const QString& _la ); } -QString TranslationDispatcher::detokenize(const QString& _text, const QString& _lang) -{ +QString TranslationDispatcher::detokenize(const QString& _text, const QString& _lang) {/*KZ*/ return TargomanTextProcessor::instance().ixml2Text(_text, true, _lang=="fa" || _lang=="ar", false); } -QVariantMap TranslationDispatcher::retrieveDicResponse(const QString& _text, const QString& _lang) -{ +QVariantMap TranslationDispatcher::retrieveDicResponse(const QString& _text, const QString& _lang) {/*KZ*/ Q_UNUSED(_text); Q_UNUSED (_lang); return QVariantMap(); } -void TranslationDispatcher::addDicLog(const QString& _lang, quint64 _wordCount, const QString& _text) -{ +void TranslationDispatcher::addDicLog(const QString& _lang, quint64 _wordCount, const QString& _text) {/*KZ*/ Q_UNUSED(_text); Q_UNUSED (_lang); Q_UNUSED (_wordCount) } -void TranslationDispatcher::addErrorLog(quint64 _aptID, const QString& _engine, const QString& _dir, quint64 _wordCount, const QString& _text, qint32 _errorCode) -{ +void TranslationDispatcher::addErrorLog(quint64 _aptID, const QString& _engine, const QString& _dir, quint64 _wordCount, const QString& _text, qint32 _errorCode) {/*KZ*/ Q_UNUSED(_text); Q_UNUSED (_dir); Q_UNUSED (_wordCount);Q_UNUSED (_aptID); Q_UNUSED (_errorCode);Q_UNUSED (_engine) } -void TranslationDispatcher::addTranslationLog(quint64 _aptID, const QString& _engine, const QString& _dir, quint64 _wordCount, const QString& _text, int _trTime) -{ +void TranslationDispatcher::addTranslationLog(quint64 _aptID, const QString& _engine, const QString& _dir, quint64 _wordCount, const QString& _text, int _trTime) {/*KZ*/ Q_UNUSED(_text); Q_UNUSED (_dir); Q_UNUSED (_wordCount);Q_UNUSED (_aptID);Q_UNUSED (_engine); Q_UNUSED (_trTime) } -void TranslationDispatcher::registerEngines() -{ - foreach (const QString& Key, this->TranslationServers.keys()){ +void TranslationDispatcher::registerEngines() {/*KZ*/ + foreach (const QString& Key, this->TranslationServers.keys()) { const tmplConfigurableArray& ServersConfig = this->TranslationServers.values(Key); - for(size_t i=0; iRegisteredEngines.insert(stuEngineSpecs::makeFullName(Key, Server.SourceLang.value(), Server.DestLang.value(), Server.Class.value()), Engine ); @@ -228,14 +217,12 @@ void TranslationDispatcher::registerEngines() } } -TranslationDispatcher::TranslationDispatcher() -{ +TranslationDispatcher::TranslationDispatcher() {/*KZ*/ FormalityChecker::instance(); } /********************************************/ -intfTranslatorEngine::~intfTranslatorEngine() -{;} +intfTranslatorEngine::~intfTranslatorEngine() {/*KZ*/;} } } diff --git a/Modules/MT/Classes/TranslationDispatcher.h b/Modules/MT/Classes/TranslationDispatcher.h index 6bc50ec5..583f3c45 100644 --- a/Modules/MT/Classes/TranslationDispatcher.h +++ b/Modules/MT/Classes/TranslationDispatcher.h @@ -68,7 +68,7 @@ class TranslationDispatcher static Common::Configuration::tmplConfigurableMultiMap TranslationServers; public: - static TranslationDispatcher& instance(){static TranslationDispatcher* Instance = nullptr; return *(Q_LIKELY(Instance) ? Instance : (Instance = new TranslationDispatcher));} + static TranslationDispatcher& instance() {static TranslationDispatcher* Instance = nullptr; return *(Q_LIKELY(Instance) ? Instance : (Instance = new TranslationDispatcher));} ~TranslationDispatcher(); QVariantMap doTranslation(const QJsonObject& _privInfo, @@ -91,14 +91,14 @@ class TranslationDispatcher void addTranslationLog(quint64 _aptID, const QString& _engine, const QString& _dir, quint64 _worcCount, const QString& _text, int _trTime); void registerEngines(); - inline bool isValidEngine(const QString& _engine, const TranslationDir_t& _dir){ + inline bool isValidEngine(const QString& _engine, const TranslationDir_t& _dir) { return this->RegisteredEngines.contains(stuEngineSpecs::makeFullName(_engine, _dir.first, _dir.second)); } - static inline TranslationDir_t dirLangs(const QString& _dir){ - if(_dir.contains("2")) + static inline TranslationDir_t dirLangs(const QString& _dir) { + if (_dir.contains("2")) return qMakePair(_dir.split("2").first(), _dir.split("2").last()); - else if(_dir.contains("_")) + else if (_dir.contains("_")) return qMakePair(_dir.split("_").first(), _dir.split("_").last()); return qMakePair(QString(),QString()); } diff --git a/Modules/MT/Classes/intfTranslatorEngine.hpp b/Modules/MT/Classes/intfTranslatorEngine.hpp index a2151734..cbc96544 100644 --- a/Modules/MT/Classes/intfTranslatorEngine.hpp +++ b/Modules/MT/Classes/intfTranslatorEngine.hpp @@ -58,17 +58,16 @@ struct stuEngineSpecs{ DestLang(_destLang), Class(_class), SupportsIXML(_supportsIXML), - URL(_url) - {;} + URL(_url) {/*KZ*/;} - inline QString fullName(){ + inline QString fullName() { return this->makeFullName(enuEngine::toStr(this->Engine), this->SourceLang, this->DestLang, this->Class); } static inline QString makeFullName(const QString& _engine, const QString& _sourceLang = QString(), const QString& _destLang = QString(), - const QString& _class = QString()){ + const QString& _class = QString()) { return _class.isNull() ? QString("%1;%2_%3").arg(_engine).arg(_sourceLang).arg(_destLang) : @@ -80,14 +79,14 @@ class intfTranslatorEngine{ public: explicit intfTranslatorEngine(const stuEngineSpecs& _specs) : EngineSpecs(_specs) - {} + {/*KZ*/;/*KZ*/} virtual ~intfTranslatorEngine(); virtual QVariantMap doTranslation(const QString& _text, bool _detailed, bool _detokinize) = 0; - QString fullName(){return this->EngineSpecs.fullName();} + QString fullName() {return this->EngineSpecs.fullName();} - inline const stuEngineSpecs& specs(){return this->EngineSpecs;} + inline const stuEngineSpecs& specs() {return this->EngineSpecs;} protected: stuEngineSpecs EngineSpecs; diff --git a/Modules/MT/Engines/clsNMT.cpp b/Modules/MT/Engines/clsNMT.cpp index 7fb99d0b..287b4a74 100644 --- a/Modules/MT/Engines/clsNMT.cpp +++ b/Modules/MT/Engines/clsNMT.cpp @@ -47,22 +47,20 @@ namespace NMTResponse{ } clsBaseNMT::clsBaseNMT(const Classes::stuEngineSpecs& _specs) : - Classes::intfTranslatorEngine(_specs) -{ ; } + Classes::intfTranslatorEngine(_specs) {/*KZ*/ ; } -QVariantMap clsBaseNMT::doTranslation(const QString& _text, bool _detailed, bool _detokenize) -{ +QVariantMap clsBaseNMT::doTranslation(const QString& _text, bool _detailed, bool _detokenize) {/*KZ*/ int Retries = 0; QVariantMap Result; - auto makeSourceArray = [](const QString& _text){ + auto makeSourceArray = [](const QString& _text) { QVariantList List; foreach(auto Line, _text.split("\n", QString::SkipEmptyParts)) List.append(QVariantMap({{"src", Line}})); return List; }; - while(Retries < 5){ + while(Retries < 5) { QtCUrl CUrl; CUrl.setTextCodec("UTF-8"); @@ -77,22 +75,22 @@ QVariantMap clsBaseNMT::doTranslation(const QString& _text, bool _detailed, bool Opt[CURLOPT_POSTFIELDS] = QJsonDocument::fromVariant(makeSourceArray(_text)).toJson(QJsonDocument::Compact); QString CUrlResult = CUrl.exec(Opt); - if (CUrl.lastError().code() == CURLE_OPERATION_TIMEDOUT){ + if (CUrl.lastError().code() == CURLE_OPERATION_TIMEDOUT) { Result[RESULTItems::ERRNO] = enuTranslationError::OperationTimedOut; Result[RESULTItems::MESSAGE] = "Unable to translate with NMT after 5 retries."; ++Retries; - }else if(CUrl.lastError().code() == CURLE_COULDNT_CONNECT){ + } else if (CUrl.lastError().code() == CURLE_COULDNT_CONNECT) { Result[RESULTItems::ERRNO] = enuTranslationError::ConnectionRefused; Result[RESULTItems::MESSAGE] = "Unable to translate with NMT after 5 retries."; ++Retries; - }else if(CUrl.lastError().isOk() == false){ + } else if (CUrl.lastError().isOk() == false) { Result[RESULTItems::ERRNO] = enuTranslationError::CURLError + CUrl.lastError().code(); Result[RESULTItems::MESSAGE] = CUrl.lastError().text(); return Result; - }else{ + } else { QJsonParseError JsonError; QJsonDocument Doc = QJsonDocument::fromJson(CUrlResult.toUtf8(),& JsonError); - if(JsonError.error != QJsonParseError::NoError){ + if (JsonError.error != QJsonParseError::NoError) { Result[RESULTItems::ERRNO] = enuTranslationError::JsonParseError; Result[RESULTItems::MESSAGE] = "Unable to parse JSON: " + JsonError.errorString() + '"' + CUrlResult + '"'; ++Retries; @@ -106,8 +104,7 @@ QVariantMap clsBaseNMT::doTranslation(const QString& _text, bool _detailed, bool return Result; } -QVariantMap clsBaseNMT::buildProperResponse(const QJsonDocument& _doc, bool _detailed, bool _detok) -{ +QVariantMap clsBaseNMT::buildProperResponse(const QJsonDocument& _doc, bool _detailed, bool _detok) {/*KZ*/ Q_UNUSED(_detailed) auto invalidResponse = [_doc]() -> QVariantMap{ @@ -117,37 +114,37 @@ QVariantMap clsBaseNMT::buildProperResponse(const QJsonDocument& _doc, bool _det }; }; - if(_doc.isObject() == false) + if (_doc.isObject() == false) return invalidResponse(); QVariantMap BaseMap = _doc.toVariant().toMap(); QVariantMap Result; - if(BaseMap.isEmpty()) return invalidResponse(); + if (BaseMap.isEmpty()) return invalidResponse(); - if(BaseMap.contains(NMTResponse::serverName)) + if (BaseMap.contains(NMTResponse::serverName)) Result[RESULTItems::SERVERID] = BaseMap[NMTResponse::serverName].toString(); - static auto baseTranslation = [_detok, this](const QVariantMap& SentenceResults){ + static auto baseTranslation = [_detok, this](const QVariantMap& SentenceResults) { QStringList TrTokens; - foreach(auto Phrase, SentenceResults[NMTResponse::Result::phrases].toList()){ + foreach(auto Phrase, SentenceResults[NMTResponse::Result::phrases].toList()) { TrTokens.append(Phrase.toList().at(0).toString()); } - if(_detok) + if (_detok) return TranslationDispatcher::instance().detokenize(TrTokens.join(" "), this->EngineSpecs.DestLang); else return TrTokens.join(" "); }; - if(!_detailed){ + if (!_detailed) { QStringList TrSentences; foreach(QVariant SentenceResults, BaseMap[NMTResponse::rslt].toList()) TrSentences.append (baseTranslation(SentenceResults.toMap())); Result[RESULTItems::SIMPLE] = TrSentences.join('\n'); - }else{ + } else { QVariantList ResultBaseList, ResultPhrasesList, ResultAlignmentsList; - foreach(auto SentenceResults, BaseMap[NMTResponse::rslt].toList()){ + foreach(auto SentenceResults, BaseMap[NMTResponse::rslt].toList()) { QStringList TempStringList; QVariantList TempList; QVariantMap SentenceResultMap = SentenceResults.toMap(); @@ -169,11 +166,11 @@ QVariantMap clsBaseNMT::buildProperResponse(const QJsonDocument& _doc, bool _det Index = 0; TempList.clear(); - static auto buildAlignments = [this, _detok](const QVariantList& _phrases){ + static auto buildAlignments = [this, _detok](const QVariantList& _phrases) { QVariantList Result; bool IsFirst = true; - foreach(auto Phrase, _phrases){ - if(Phrase.toString().size()) + foreach(auto Phrase, _phrases) { + if (Phrase.toString().size()) Result.push_back(QVariantList({ {_detok ? TranslationDispatcher::instance().detokenize(Phrase.toString(), this->EngineSpecs.DestLang) : @@ -185,7 +182,7 @@ QVariantMap clsBaseNMT::buildProperResponse(const QJsonDocument& _doc, bool _det return Result; }; - foreach(auto Alignment, SentenceResultMap[NMTResponse::Result::alignments].toList()){ + foreach(auto Alignment, SentenceResultMap[NMTResponse::Result::alignments].toList()) { TempStringList.clear(); foreach(auto AlignmentItem, Alignment.toList()) diff --git a/Modules/MT/MT.cpp b/Modules/MT/MT.cpp index d57195eb..7a3f7686 100644 --- a/Modules/MT/MT.cpp +++ b/Modules/MT/MT.cpp @@ -39,23 +39,22 @@ QVariantMap MT::apiTranslate(const TAPI::RemoteIP_t& _REMOTE_IP, bool _detailed, bool _detok, bool _dic, - bool _dicFull) -{ + bool _dicFull) {/*KZ*/ QTime Timer, OverallTime; int PreprocessTime = 0; Timer.start();OverallTime.start(); _text = _text.trimmed(); - if(_text.isEmpty()) + if (_text.isEmpty()) throw exHTTPBadRequest("Input text must not be empty"); _dir = _dir.replace('_', '2'); TranslationDir_t Dir = TranslationDispatcher::dirLangs(_dir); - if(Dir.first.isNull()) + if (Dir.first.isNull()) throw exHTTPBadRequest("Invalid translation direction format"); - if(!TranslationDispatcher::instance().isValidEngine(_engine, Dir) == false) + if (!TranslationDispatcher::instance().isValidEngine(_engine, Dir) == false) throw exHTTPBadRequest("Invalid engine/direction combination"); QJsonObject TokenInfo = Authorization::retrieveTokenInfo(_token, @@ -79,7 +78,7 @@ QVariantMap MT::apiTranslate(const TAPI::RemoteIP_t& _REMOTE_IP, } ).toJson(true).object (); - if(Stats.isEmpty()) + if (Stats.isEmpty()) this->execQuery("INSERT IGNORE INTO tblTokenStats (tks_tokID,tksEngine,tksDir) VALUES(?, ?, ?)", { {TokenInfo[TOKENItems::tokID]}, {_engine}, @@ -101,15 +100,15 @@ QVariantMap MT::apiTranslate(const TAPI::RemoteIP_t& _REMOTE_IP, Accounting::checkCredit(Privs, TARGOMAN_QUOTA_PREFIX+"MaxPerMonth", Stats["tksThisMonthWords"].toDouble()+ SourceWordCount); Accounting::checkCredit(Privs, TARGOMAN_QUOTA_PREFIX+"MaxTotal", Stats["tksTotalWords"].toDouble()+ SourceWordCount); */ - if(_dic){ - if(Authorization::hasPriv(Privs, {TARGOMAN_PRIV_PREFIX + "Dic"})){ - if(_dicFull && Authorization::hasPriv(Privs, {TARGOMAN_PRIV_PREFIX + "DicFull"})) + if (_dic) { + if (Authorization::hasPriv(Privs, {TARGOMAN_PRIV_PREFIX + "Dic"})) { + if (_dicFull && Authorization::hasPriv(Privs, {TARGOMAN_PRIV_PREFIX + "DicFull"})) throw exAuthorization("Not enought priviledges to retrieve dictionary full response."); PreprocessTime = Timer.elapsed();Timer.restart(); QVariantMap DicResponse = TranslationDispatcher::instance().retrieveDicResponse(_text, Dir.first); - if(DicResponse.size()){ - if(_detailed){ + if (DicResponse.size()) { + if (_detailed) { DicResponse[RESULTItems::TIMES]= QVariantMap({ {RESULTItems::TIMESItems::PRE, PreprocessTime}, {RESULTItems::TIMESItems::TR, Timer.elapsed()}, @@ -120,13 +119,13 @@ QVariantMap MT::apiTranslate(const TAPI::RemoteIP_t& _REMOTE_IP, TranslationDispatcher::instance().addDicLog(Dir.first, SourceWordCount, _text); return DicResponse; } - }else + } else throw exAuthorization("Not enought priviledges to retrieve dictionary response."); } PreprocessTime += Timer.elapsed(); - try{ + try { int InternalPreprocessTime = 0, InternalTranslationTime = 0, InternalPostprocessTime = 0; QVariantMap Translation = TranslationDispatcher::instance().doTranslation(Privs, _text, @@ -139,38 +138,36 @@ QVariantMap MT::apiTranslate(const TAPI::RemoteIP_t& _REMOTE_IP, InternalTranslationTime ); Timer.restart(); - if(_detailed){ + if (_detailed) { Translation[RESULTItems::TIMES]= QVariantMap({ {RESULTItems::TIMESItems::PRE, InternalPreprocessTime + PreprocessTime}, {RESULTItems::TIMESItems::TR, InternalTranslationTime}, {RESULTItems::TIMESItems::POST, InternalPostprocessTime + Timer.elapsed()}, {RESULTItems::TIMESItems::ALL, OverallTime.elapsed()} }); - }else + } else Translation[RESULTItems::TIME]= OverallTime.elapsed(); TranslationDispatcher::instance().addTranslationLog(static_cast(TokenInfo[TOKENItems::tokID].toInt()), _engine, _dir, SourceWordCount, _text, OverallTime.elapsed()); - if(Authorization::hasPriv(Privs, {TARGOMAN_PRIV_PREFIX + "ReportServer"}) == false) + if (Authorization::hasPriv(Privs, {TARGOMAN_PRIV_PREFIX + "ReportServer"}) == false) Translation.remove(RESULTItems::SERVERID); return Translation; - }catch(Common::exTargomanBase& ex){ + } catch (Common::exTargomanBase& ex) { TranslationDispatcher::instance().addErrorLog(static_cast(TokenInfo[TOKENItems::tokID].toInt()), _engine, _dir, SourceWordCount, _text, ex.code()); throw; } } -QVariantMap MT::apiTest(const TAPI::RemoteIP_t& _REMOTE_IP, const QString& _token, const QString& _arg) -{ +QVariantMap MT::apiTest(const TAPI::RemoteIP_t& _REMOTE_IP, const QString& _token, const QString& _arg) {/*KZ*/ return { {"inputArg", _arg}, {"info", Authorization::retrieveTokenInfo(_token, _REMOTE_IP)} }; } -MT::MT() : ORM::clsRESTAPIWithActionLogs("MT", "MT") -{ +MT::MT() : ORM::clsRESTAPIWithActionLogs("MT", "MT") {/*KZ*/ // Register translation engines TranslationDispatcher::instance().registerEngines(); } diff --git a/Modules/NGT/functionalTest/main.cpp b/Modules/NGT/functionalTest/main.cpp index 5d432433..29ce1f45 100644 --- a/Modules/NGT/functionalTest/main.cpp +++ b/Modules/NGT/functionalTest/main.cpp @@ -27,8 +27,7 @@ TAPI_MARSHAL_TEST_VARIABLES -int main(int _argc, char *_argv[]) -{ +int main(int _argc, char *_argv[]) { qDebug() << "--------------------------------------------------"; qDebug() << "-- test module: NGT ------------------------------"; qDebug() << "--------------------------------------------------"; @@ -57,7 +56,7 @@ int main(int _argc, char *_argv[]) try { FailedTests += QTest::qExec(new testBase(DBPrefix), progArgsCount, progArgs); if (BreakOnFirstFail && !FailedTests) FailedTests += QTest::qExec(new testNGT(DBPrefix), progArgsCount, progArgs); - } catch(std::exception &e) { + } catch (std::exception &e) { qDebug()< 0) { diff --git a/Modules/NGT/functionalTest/testNGT.hpp b/Modules/NGT/functionalTest/testNGT.hpp index ceabde1c..9d9d6f19 100644 --- a/Modules/NGT/functionalTest/testNGT.hpp +++ b/Modules/NGT/functionalTest/testNGT.hpp @@ -47,22 +47,19 @@ class testNGT : public clsBaseTest Q_OBJECT public: - testNGT(const QString &_dbPrefix) : clsBaseTest(_dbPrefix) {} + testNGT(const QString &_dbPrefix) : clsBaseTest(_dbPrefix) { ; } - void cleanupUnitTestData() - { + void cleanupUnitTestData() { clsDAC DAC; DAC.execQuery("", QString("UPDATE %1AAA.tblUser SET usrStatus='R' WHERE usrEmail IN(?,?)").arg(this->DBPrefix), { UT_UserEmail, UT_AdminUserEmail }); } private slots: - void initTestCase() - { + void initTestCase() { initUnitTestData(false); } - void cleanupTestCase() - { + void cleanupTestCase() { gEncodedAdminJWT = ""; gEncodedJWT = ""; cleanupUnitTestData(); diff --git a/Modules/NGT/moduleSrc/NGTv1.cpp b/Modules/NGT/moduleSrc/NGTv1.cpp index 5397dacf..0d51b25a 100644 --- a/Modules/NGT/moduleSrc/NGTv1.cpp +++ b/Modules/NGT/moduleSrc/NGTv1.cpp @@ -29,7 +29,6 @@ TARGOMAN_IMPL_API_MODULE(NGTv1) TARGOMAN_API_MODULE_DB_CONFIG_IMPL(NGTv1, NGTv1Schema); NGTv1::NGTv1() : - intfSQLBasedWithActionLogsModule(NGTv1Domain, NGTv1Schema) -{ + intfSQLBasedWithActionLogsModule(NGTv1Domain, NGTv1Schema) { TARGOMAN_API_IMPLEMENT_ACTIONLOG(NGTv1, NGTv1Schema) } diff --git a/Modules/TextProcessor/TextProcessor.cpp b/Modules/TextProcessor/TextProcessor.cpp index 134517c4..4d489f62 100644 --- a/Modules/TextProcessor/TextProcessor.cpp +++ b/Modules/TextProcessor/TextProcessor.cpp @@ -36,17 +36,15 @@ TARGOMAN_IMPL_API_MODULE(TextProcessor) TextProcessor::TextProcessor() : intfPureModule("Targoman") -{} +{ ; } -QString TextProcessor::apinormalize(const QString _text, const TAPI::ISO639_2_t& _lang, bool _useSpellCorrector) -{ +QString TextProcessor::apinormalize(const QString _text, const TAPI::ISO639_2_t& _lang, bool _useSpellCorrector) { return NLP::TextProcessor::instance().normalizeText(_text, _useSpellCorrector ? _lang : TAPI::ISO639_2_t()); } QString TextProcessor::apitext2IXML (const QString& _text, const TAPI::ISO639_2_t& _lang, - bool _useSpellCorrector) -{ + bool _useSpellCorrector) { bool SpellCorrected; QList SentenceBreakReplacements; SentenceBreakReplacements.append( @@ -68,8 +66,7 @@ QString TextProcessor::apiixml2Text(const QString& _ixml, bool _detokenize, bool _hinidiDigits, bool _arabicPunctuations, - bool _breakSentences) -{ + bool _breakSentences) { return NLP::TextProcessor::instance().ixml2Text(_ixml, _detokenize, _hinidiDigits, _arabicPunctuations, _breakSentences); } @@ -77,8 +74,7 @@ QString TextProcessor::apitokenize(const QString& _text, const TAPI::ISO639_2_t& _lang, bool _useSpellCorrector, bool _hindiNumerals, - bool _arabicPunctuations) -{ + bool _arabicPunctuations) { bool SpellCorrected; QList SentenceBreakReplacements; SentenceBreakReplacements.append( @@ -98,8 +94,7 @@ QString TextProcessor::apitokenize(const QString& _text, return NLP::TextProcessor::instance().ixml2Text(Tokenized, false, _hindiNumerals, _arabicPunctuations, false); } -bool TextProcessor::init() -{ +bool TextProcessor::init() { NLP::TextProcessor::instance().init(); //Targoman::Common::Configuration::ConfigManager::instance().configSettings()); diff --git a/Modules/Ticketing/functionalTest/ORM/actionLogs.hpp b/Modules/Ticketing/functionalTest/ORM/actionLogs.hpp index 96a50d9d..6591a835 100644 --- a/Modules/Ticketing/functionalTest/ORM/actionLogs.hpp +++ b/Modules/Ticketing/functionalTest/ORM/actionLogs.hpp @@ -33,7 +33,7 @@ class testActionLogs: public clsBaseTest Q_OBJECT private slots: - void unprivActionLogs(){ + void unprivActionLogs() { QVERIFY(callUserAPI(RESTClientHelper::GET, "Advert/ActionLogs").toString().isEmpty()); } }; diff --git a/Modules/Ticketing/functionalTest/main.cpp b/Modules/Ticketing/functionalTest/main.cpp index 492aa502..25237072 100644 --- a/Modules/Ticketing/functionalTest/main.cpp +++ b/Modules/Ticketing/functionalTest/main.cpp @@ -27,8 +27,7 @@ TAPI_MARSHAL_TEST_VARIABLES -int main(int _argc, char *_argv[]) -{ +int main(int _argc, char *_argv[]) { qDebug() << "--------------------------------------------------"; qDebug() << "-- test module: Ticketing ------------------------"; qDebug() << "--------------------------------------------------"; @@ -78,7 +77,7 @@ int main(int _argc, char *_argv[]) FailedTests += QTest::qExec(new testBase(DBPrefix), progArgsCount, progArgs); if (BreakOnFirstFail && !FailedTests) FailedTests += QTest::qExec(new testTicketing(DBPrefix), progArgsCount, progArgs); // if (BreakOnFirstFail && !FailedTests) FailedTests += QTest::qExec(new testActionLogs(DBPrefix), progArgsCount, progArgs); - } catch(std::exception &e) { + } catch (std::exception &e) { qDebug()< 0) { diff --git a/Modules/Ticketing/functionalTest/testTicketing.hpp b/Modules/Ticketing/functionalTest/testTicketing.hpp index e0d07408..26adc8f5 100644 --- a/Modules/Ticketing/functionalTest/testTicketing.hpp +++ b/Modules/Ticketing/functionalTest/testTicketing.hpp @@ -49,10 +49,9 @@ class testTicketing : public clsBaseTest Q_OBJECT public: - testTicketing(const QString &_dbPrefix) : clsBaseTest(_dbPrefix) {} + testTicketing(const QString &_dbPrefix) : clsBaseTest(_dbPrefix) { ; } - void cleanupUnitTestData() - { + void cleanupUnitTestData() { clsDAC DAC; DAC.execQuery("", QString("UPDATE %1AAA.tblUser SET usrStatus='R' WHERE usrEmail IN(?,?)").arg(this->DBPrefix), { UT_UserEmail, UT_AdminUserEmail }); } @@ -66,13 +65,11 @@ class testTicketing : public clsBaseTest quint64 Reply2TicketID; private slots: - void initTestCase() - { + void initTestCase() { initUnitTestData(false); } - void cleanupTestCase() - { + void cleanupTestCase() { gEncodedAdminJWT = ""; gEncodedJWT = ""; cleanupUnitTestData(); @@ -81,8 +78,7 @@ private slots: /***************************************************************************************/ /***************************************************************************************/ /***************************************************************************************/ - void setupAccountFixture() - { + void setupAccountFixture() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::POST, @@ -109,8 +105,7 @@ private slots: } } - void login_user() - { + void login_user() { //5d12d36cd5f66fe3e72f7b03cbb75333 = MD5(1234 + df6d2338b2b8fce1ec2f6dda0a630eb0 # 987) QVariant Result = callUserAPI(RESTClientHelper::POST, "Account/login",{},{ @@ -127,8 +122,7 @@ private slots: QVERIFY(clsJWT(gJWT).usrStatus() == TAPI::enuUserStatus::Active); } - void login_admin() - { + void login_admin() { //5d12d36cd5f66fe3e72f7b03cbb75333 = MD5(1234 + df6d2338b2b8fce1ec2f6dda0a630eb0 # 987) QVariant Result = callUserAPI(RESTClientHelper::POST, "Account/login",{},{ @@ -165,8 +159,7 @@ private slots: // } // } - void Ticket_newMessage() - { + void Ticket_newMessage() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::PUT, @@ -193,8 +186,7 @@ private slots: } } - void Ticket_newFeedback_1() - { + void Ticket_newFeedback_1() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::PUT, @@ -223,8 +215,7 @@ private slots: } } - void Ticket_newFeedback_2() - { + void Ticket_newFeedback_2() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::PUT, @@ -253,8 +244,7 @@ private slots: } } - void Tickets_Get() - { + void Tickets_Get() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::GET, @@ -271,9 +261,7 @@ private slots: QTest::qFail(exp.what(), __FILE__, __LINE__); } } - void Tickets_List() - - { + void Tickets_List() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::GET, @@ -291,8 +279,7 @@ private slots: } } - void Tickets_List_by_baseTicketID() - { + void Tickets_List_by_baseTicketID() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::GET, @@ -312,8 +299,7 @@ private slots: } } - void Tickets_List_by_inReplyTicketID() - { + void Tickets_List_by_inReplyTicketID() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::GET, @@ -333,8 +319,7 @@ private slots: } } - void TicketAttachments_List() - { + void TicketAttachments_List() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::GET, @@ -357,13 +342,11 @@ private slots: /***************************************************************************************/ /* cleanup *****************************************************************************/ /***************************************************************************************/ - void cleanupTickets() - { + void cleanupTickets() { return; clsDAC DAC("Ticketing"); - try - { + try { QString QueryString = R"( DELETE t FROM tblTickets t @@ -373,14 +356,11 @@ return; this->Reply2TicketID }); qDebug() << QVariantMap({{ "(2) numRowsAffected", DACResult.numRowsAffected() }}); - } - catch(std::exception &exp) - { + } catch (std::exception &exp) { qDebug() << "(2)" << exp.what(); } - try - { + try { QString QueryString = R"( DELETE t FROM tblTickets t @@ -390,14 +370,11 @@ return; this->Reply1TicketID }); qDebug() << QVariantMap({{ "(1) numRowsAffected", DACResult.numRowsAffected() }}); - } - catch(std::exception &exp) - { + } catch (std::exception &exp) { qDebug() << "(1)" << exp.what(); } - try - { + try { QString QueryString = R"( DELETE t FROM tblTickets t @@ -407,19 +384,15 @@ return; this->MainTicketID }); qDebug() << QVariantMap({{ "(MAIN) numRowsAffected", DACResult.numRowsAffected() }}); - } - catch(std::exception &exp) - { + } catch (std::exception &exp) { qDebug() << "(MAIN)" << exp.what(); } } - void cleanupOrphanUploadedFiles() - { + void cleanupOrphanUploadedFiles() { clsDAC DAC("Ticketing"); - try - { + try { QString QueryString = R"( DELETE tblUploadFiles FROM tblUploadFiles @@ -434,15 +407,12 @@ return; ;)"; clsDACResult DACResult = DAC.execQuery("", QueryString); qDebug() << QVariantMap({{ "(ORPHAN) numRowsAffected", DACResult.numRowsAffected() }}); - } - catch(std::exception &exp) - { + } catch (std::exception &exp) { qDebug() << "(ORPHAN)" << exp.what(); } } - void cleanupAccountFixture() - { + void cleanupAccountFixture() { QT_TRY { QVariant Result = callAdminAPI( RESTClientHelper::POST, diff --git a/Modules/Ticketing/moduleSrc/ORM/Departments.cpp b/Modules/Ticketing/moduleSrc/ORM/Departments.cpp index 0aed15d6..67d50d87 100644 --- a/Modules/Ticketing/moduleSrc/ORM/Departments.cpp +++ b/Modules/Ticketing/moduleSrc/ORM/Departments.cpp @@ -46,28 +46,24 @@ Departments::Departments() : ORM_RELATION_OF_CREATOR(tblDepartments::depCreatedBy_usrID), } ) -{} +{ ; } -QVariant Departments::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant Departments::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); } -quint32 Departments::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) -{ +quint32 Departments::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PUT, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Create(*this, CREATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool Departments::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool Departments::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PATCH, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool Departments::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool Departments::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())); return /*Targoman::API::Query::*/this->DeleteByPks(*this, DELETE_METHOD_CALL_ARGS_INTERNAL_CALL); } diff --git a/Modules/Ticketing/moduleSrc/ORM/TicketAttachments.cpp b/Modules/Ticketing/moduleSrc/ORM/TicketAttachments.cpp index a47e6910..058a5210 100644 --- a/Modules/Ticketing/moduleSrc/ORM/TicketAttachments.cpp +++ b/Modules/Ticketing/moduleSrc/ORM/TicketAttachments.cpp @@ -56,10 +56,9 @@ TicketAttachments::TicketAttachments() : ORM_RELATION_OF_CREATOR(tblTicketAttachments::tatCreatedBy_usrID), } ) -{} +{ ; } -QVariant TicketAttachments::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant TicketAttachments::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { // QString ExtraFilters; // if (Authorization::hasPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())) == false) // ExtraFilters = QString ("( %1=%2 | %3=%4 | ( %5=NULL + %7=%8 )") diff --git a/Modules/Ticketing/moduleSrc/ORM/Tickets.cpp b/Modules/Ticketing/moduleSrc/ORM/Tickets.cpp index 0baf3808..189dea92 100644 --- a/Modules/Ticketing/moduleSrc/ORM/Tickets.cpp +++ b/Modules/Ticketing/moduleSrc/ORM/Tickets.cpp @@ -94,7 +94,7 @@ Tickets::Tickets() : ORM_RELATION_OF_UPDATER(tblTickets::tktUpdatedBy_usrID), } ) -{} +{ ; } QVariant Tickets::apiGET( // GET_METHOD_ARGS_IMPL_APICALL, @@ -155,8 +155,7 @@ QVariant Tickets::apiGET( if (_inReplyTicketID > 0) _query.andWhere({ tblTickets::tktInReply_tktID, enuConditionOperator::Equal, _inReplyTicketID }); - else - { + else { if (_baseTicketID == 0) _query.andWhere({ tblTickets::tktBase_tktID, enuConditionOperator::Null }); else @@ -194,6 +193,6 @@ TicketRead::TicketRead() : {tblTicketRead::tkrDateTime, S(TAPI::DateTime_t), QFV.allwaysInvalid(), QInvalid, UPNone,false,false}, } ) -{} +{ ; } } //namespace Targoman::API::TicketingModule::ORM diff --git a/Modules/Ticketing/moduleSrc/ORM/Units.cpp b/Modules/Ticketing/moduleSrc/ORM/Units.cpp index 400d231d..d5f0fa56 100644 --- a/Modules/Ticketing/moduleSrc/ORM/Units.cpp +++ b/Modules/Ticketing/moduleSrc/ORM/Units.cpp @@ -49,28 +49,24 @@ Units::Units() : ORM_RELATION_OF_CREATOR(tblUnits::untCreatedBy_usrID), } ) -{} +{ ; } -QVariant Units::apiGET(GET_METHOD_ARGS_IMPL_APICALL) -{ +QVariant Units::apiGET(GET_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_GET, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Select(*this, GET_METHOD_CALL_ARGS_INTERNAL_CALL); } -quint32 Units::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) -{ +quint32 Units::apiCREATE(CREATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PUT, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Create(*this, CREATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool Units::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) -{ +bool Units::apiUPDATE(UPDATE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_PATCH, this->moduleBaseName())); return /*Targoman::API::Query::*/this->Update(*this, UPDATE_METHOD_CALL_ARGS_INTERNAL_CALL); } -bool Units::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) -{ +bool Units::apiDELETE(DELETE_METHOD_ARGS_IMPL_APICALL) { Authorization::checkPriv(_JWT, this->privOn(EHTTP_DELETE, this->moduleBaseName())); return /*Targoman::API::Query::*/this->DeleteByPks(*this, DELETE_METHOD_CALL_ARGS_INTERNAL_CALL); } diff --git a/Modules/Ticketing/moduleSrc/Ticketing.cpp b/Modules/Ticketing/moduleSrc/Ticketing.cpp index 67111fee..378a87f4 100644 --- a/Modules/Ticketing/moduleSrc/Ticketing.cpp +++ b/Modules/Ticketing/moduleSrc/Ticketing.cpp @@ -45,8 +45,7 @@ TARGOMAN_API_MODULE_DB_CONFIG_IMPL(Ticketing, TicketingSchema); TARGOMAN_API_OBJECTSTORAGE_CONFIG_IMPL(Ticketing, TicketingSchema) Ticketing::Ticketing() : - intfSQLBasedWithActionLogsModule(TicketingDomain, TicketingSchema) -{ + intfSQLBasedWithActionLogsModule(TicketingDomain, TicketingSchema) { TARGOMAN_API_IMPLEMENT_ACTIONLOG(Ticketing, TicketingSchema) TARGOMAN_API_IMPLEMENT_OBJECTSTORAGE(Ticketing, TicketingSchema) @@ -89,17 +88,14 @@ quint64 Ticketing::insertTicket( quint64 TicketID = this->Create(Tickets::instance(), _createdBy, CreateFields); - if (_files.isEmpty() == false) - { + if (_files.isEmpty() == false) { CreateQuery QueryCreateAttachments = CreateQuery(TicketAttachments::instance()) .addCol(tblTicketAttachments::tat_tktID) .addCol(tblTicketAttachments::tat_uplID) ; - foreach(auto _file, _files) - { - try - { + foreach(auto _file, _files) { + try { quint64 UploadedFileID = ObjectStorageManager::saveFile( _createdBy, UploadFiles::instance(), @@ -112,9 +108,7 @@ quint64 Ticketing::insertTicket( { tblTicketAttachments::tat_tktID, TicketID }, { tblTicketAttachments::tat_uplID, UploadedFileID }, })); - } - catch (std::exception &exp) - { + } catch (std::exception &exp) { TargomanDebug(5, "ObjectStorageManager::saveFile(" << _file.Name << "):" << exp.what()); } } diff --git a/Modules/URLProcessor/URLProcessor.cpp b/Modules/URLProcessor/URLProcessor.cpp index 5af2b7b9..40f29d1d 100644 --- a/Modules/URLProcessor/URLProcessor.cpp +++ b/Modules/URLProcessor/URLProcessor.cpp @@ -32,17 +32,15 @@ TARGOMAN_IMPL_API_MODULE(URLProcessor) URLProcessor::URLProcessor() : intfPureModule("Targoman") -{} +{ ; } -QString URLProcessor::apiGETcanonicalize(const QString _url, bool _removeWWW) -{ +QString URLProcessor::apiGETcanonicalize(const QString _url, bool _removeWWW) { char Normalized[MAX_URL_SIZE+1]; URLCanonicalizer::doJob (_url.toLatin1().constData(), Normalized, _removeWWW); return Normalized; } -QString URLProcessor::apiGETconvertHexCodes(const QString _url, bool _convertAll) -{ +QString URLProcessor::apiGETconvertHexCodes(const QString _url, bool _convertAll) { char Normalized[MAX_URL_SIZE+1]; strncpy(Normalized, _url.toLatin1().constData(), MAX_URL_SIZE); return URLCanonicalizer::convertHexCodes(Normalized, _convertAll); diff --git a/unitTest/QueryBuilders.cpp b/unitTest/QueryBuilders.cpp index dec67c5e..bf2324fc 100644 --- a/unitTest/QueryBuilders.cpp +++ b/unitTest/QueryBuilders.cpp @@ -1,40 +1 @@ #include "unitTest/QueryBuilders.hpp" -/* -QString TestSelectQuery::queryString() -{ -// this->testPrivateMember = 123; -// QSharedDataPointer a = this->Data; -// this->Data->prepare(); - return this->buildQueryString(); -} -*/ -/* -class aaa -{ -public: - aaa() { - } - aaa(int a) { - } - -private: -// Q_DISABLE_COPY(aaa); - aaa(const aaa&) Q_DECL_EQ_DELETE; - aaa &operator=(const aaa&) Q_DECL_EQ_DELETE; - aaa &operator=(aaa&) Q_DECL_EQ_DELETE; - aaa &operator=(const aaa) Q_DECL_EQ_DELETE; -// aaa &operator=(aaa) Q_DECL_EQ_DELETE; - -// TAPI_DISABLE_COPY(aaa) -}; -aaa aaa1() -{ - return aaa(); -} -aaa aaa2() -{ - return aaa(2); -} -aaa a1 = aaa1(); -aaa a2 = aaa2(); -*/ diff --git a/unitTest/main.cpp b/unitTest/main.cpp index c245ac3d..a0164d41 100644 --- a/unitTest/main.cpp +++ b/unitTest/main.cpp @@ -25,8 +25,7 @@ #include "testQueryBuilders.hpp" #include "App/Server/RESTAPIRegistry.h" -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { //--------------------- // QString DBPrefix; // int progArgsCount = 0; @@ -40,13 +39,10 @@ int main(int argc, char *argv[]) bool BreakOnFirstFail = true; int FailedTests = 0; - try - { + try { if (BreakOnFirstFail && !FailedTests) FailedTests += QTest::qExec(new testMacros, argc, argv); // if (BreakOnFirstFail && !FailedTests) FailedTests += QTest::qExec(new testQueryBuilders, argc, argv); - } - catch(std::exception &exp) - { + } catch (std::exception &exp) { qDebug()< a; a = 1234; @@ -34,22 +33,19 @@ private slots: // } } - void testQSharedPointer() - { + void testQSharedPointer() { QSharedPointer a = QSharedPointer::create(); *a = 1234; } - void testNullable() - { + void testNullable() { NULLABLE_TYPE(quint32) a; a = 1234; TAPI::setFromVariant(a, QVariant()); } - void testJSON_t() - { + void testJSON_t() { TAPI::JSON_t a; // a = 1234; diff --git a/unitTest/testQueryBuilders.hpp b/unitTest/testQueryBuilders.hpp index 1b885d55..4600ceaa 100644 --- a/unitTest/testQueryBuilders.hpp +++ b/unitTest/testQueryBuilders.hpp @@ -52,7 +52,7 @@ class TestTable1 : public clsTable { "rel_a", { "colC1", R("test", "t2"), "colA2" } }, } ) - {} + { ; } // ModuleMethods_t listOfMethods() final // { @@ -85,7 +85,7 @@ class TestTable2 : public clsTable { ORM_INVALIDATED_AT_FIELD }, } ) - {} + { ; } // ModuleMethods_t listOfMethods() final // { @@ -111,10 +111,10 @@ class TestTable2 : public clsTable /* -void f1(QVariant v) {} -// void f1(QString v) {} -void f1(const DBExpression& v) {} -void f1(const clsColSpecs& v) {} +void f1(QVariant v) { ; } +// void f1(QString v) { ; } +void f1(const DBExpression& v) { ; } +void f1(const clsColSpecs& v) { ; } void test_overloaded_function() { QString s1; @@ -184,8 +184,7 @@ private slots: .isEmpty() == false); }; - void condition_buildString_simple() - { + void condition_buildString_simple() { QT_TRY { clsCondition cnd = clsCondition({ "colA1", enuConditionOperator::Equal, 101 }) @@ -211,8 +210,7 @@ t1.colA1 = 101 } } - void condition_buildString_multi() - { + void condition_buildString_multi() { QT_TRY { clsCondition cnd = clsCondition({ "colA1", enuConditionOperator::Equal, 101 }) @@ -240,8 +238,7 @@ t1.colA1 = 101 } } - void condition_buildString_complex() - { + void condition_buildString_complex() { QT_TRY { clsCondition cnd = clsCondition({ "colA1", enuConditionOperator::Equal, 101 }) @@ -289,8 +286,7 @@ t1.colA1 = 101 } } - void condition_buildString_DBExpression() - { + void condition_buildString_DBExpression() { // auto v = QVariant::fromValue( // stuDBExpressionWithValue( // DBExpression::instance()["DATE_ADD"])