Skip to content
Snippets Groups Projects
process.js 105 KiB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
import("AttributeFilter_lib");
import("ClassificationComplexIndicatorRegistry_basic");
import("ClassificationIndicatorFieldRegistry_basic");
import("Classification_lib");
import("Context_lib");
import("JditoFilter_lib");
import("Organisation_lib");
import("Sql_lib");
import("Util_lib");
import("system.db");
import("system.eMath");
import("system.entities");
import("system.logging");
import("system.translate");
import("system.util");

/**
 * Methods to manage classifications.<br>
 * <b>Do not create an instance of this!</b>
 *
 * @class
 */
function ClassificationUpdateUtils() {}

/**
 * Refresh function that get's used by the updateClassifications_serverProcess and the openClassificationOverView Actions at Organisation and Salesproject.<br>
 * There are three ways to run this: only recalculating the outdated data (and updating if needed), only for a specific object and returning it's classification (and updating it's stored classification) or recalculating ALL the classifications (and updating if needed).<br>
 * ClassificationTypes are being flagged as Outdated accordingly, everytime someone configures something in ClassificationAdmin.<br>
 * The classificationStorageDatasets are being flagged as outdated as soon as you update anything regarding the corresponding object or insert/update 
 * anything with a dependency set to said object.<br>
 * 
 * Calling this function without any params leads to it updating only for the datasets that have been flagged as outdated.
 * <p>
 * First it checks whether outdated classificationStorages and outdated classificationTypes exist
 * and always updates the classificationStorages first before updating the for the outdated classificationTypes.
 * 
 * -In the classificationStorage runtrough it calculates the complete classification for every outdated classificationStorage, entirely 
 * from scratch and updates the classificationStorage
 * -In the classificationType runtrough it also updates the classificationStorage dataset, but this time 
 *  -for every object of said objectType
 *  -only recalculates the flagged ones and relies on the already stored values of the not flagged classificationTypes if they are from another classificationGroup
 *  <p>
 *  When recalculateAll_param is set to true: now the outdated flag is being ignored and all classificationtypes as outdated (only one runtrough needed)
 *  <p>
 *  When pSingleRefreshRowId we only update said object and return the achieved classifications (the stored classificationStorage string is also being updated if needed)
 * 
 * @param {Boolean}[pRefreshAll]                            <p>
 *                                                          Whether or not to recalculate and refresh all classifications<br>
 *                                                          
 * @param {String}[pSingleRefreshRowId]                    <p>
 *                                                          object row id of the dataset you want the classification for (also returns the 
 *                                                          classification as formatted Object for Classification_entity jDito contentprocess)<br>
 *                                                          
 * @param {String}[pObjectType]                            <p>
 *                                                          The Object type of the object row id. (Mandatory if pSingleRefreshRowId is set!)<br>
 *                                                          This is normally just the Context name<br>
 *                                                          
 * @return {Object}                                          <p>
 *                                                           If pSingleRefreshRowId is set: Formatted Object to return to Classification_entity jDito 
 *                                                           contentprocess to show the achieved classifications (the stored classificationStorage string 
 *                                                           is also being updated if needed)<br>
 *                                                           Else: Output in log how many Datasets have and have not been updated.
 */
ClassificationUtils.executeUpdating = function(pRefreshAll, pSingleRefreshRowId, pObjectType) 
{
    var outputInfo = "updateClassifications_serverProcess output is:\n";//information how much data has been modified
    var singleRefreshRowId = false;
    var recalculateAll = false;
    var objectType_param;

    if (pSingleRefreshRowId)
    {
        singleRefreshRowId = pSingleRefreshRowId;
        objectType_param = pObjectType;
    }
    else if (pRefreshAll)
    {
        recalculateAll = pRefreshAll;
    }

    var buildClassificationObjects = ClassificationUpdateHelper._buildClassificationFilterObjects(recalculateAll, singleRefreshRowId);
    var stopper = false;
    var buildOutdatedStoredClassificationObjects = ClassificationUpdateHelper._buildOutdatedStoredClassificationObject(recalculateAll, singleRefreshRowId, pObjectType);

    if (buildOutdatedStoredClassificationObjects && buildOutdatedStoredClassificationObjects["objectTypes"]
            && buildOutdatedStoredClassificationObjects["objectTypes"].length > 0)
    {
        while(buildOutdatedStoredClassificationObjects["objectTypes"].length > 0 && !stopper)
        {
            if (singleRefreshRowId)
            {
                stopper = true;
            }
            var returnAfterUpdate = ClassificationUpdateHelper._updateOutdatedDatasets(null, buildOutdatedStoredClassificationObjects, singleRefreshRowId, outputInfo);//run updating for this set of Datasets
            if(returnAfterUpdate && returnAfterUpdate["outputInfo"])
            {
                outputInfo = returnAfterUpdate["outputInfo"];
            }
            if (buildOutdatedStoredClassificationObjects["objectTypes"].length > 0 && !stopper)
            {
                buildOutdatedStoredClassificationObjects = ClassificationUpdateHelper._buildOutdatedStoredClassificationObject(recalculateAll, singleRefreshRowId, objectType_param);
            }
        }
        
    }
    if (buildClassificationObjects["objectTypesThatNeedUpdate"] && buildClassificationObjects["objectTypesThatNeedUpdate"].length > 0 && !singleRefreshRowId)
    {
        var update = ClassificationUpdateHelper._updateOutdatedDatasets(buildClassificationObjects, null, null, outputInfo);//run updating for this set of Datasets
        outputInfo = update["outputInfo"];
    }
    else if(!returnAfterUpdate || !returnAfterUpdate["outputInfo"])
    {
        outputInfo = outputInfo  + "No Data has been updated, everything already up-to-date";
    }

    if (returnAfterUpdate && !returnAfterUpdate["outputInfo"])
    {
        return ClassificationUpdateHelper._formatOutputForDisplayingValues(returnAfterUpdate, singleRefreshRowId);
    }
    logging.log(outputInfo); //return outputInformation in log instead of returning

    return null;
};

/**
* Throws an error if one of the values is configured the wrong way (more than one children, wrong condition or even wrong filterfield)<p><br>
* 
* @param {Object}pClassificationType                      <p>
*                                                         classificationType as built as from pIndicatorObj<br>
*                                                          
* @param {Boolean}[pIsAttribute]                          <p>
*                                                         Whether or not it's an attribute<br>
*                                                          
*/
ClassificationUtils.validateUserSetValues = function(pClassificationType, pIsAttribute)
{
    var errorMessage = "";
    if(pClassificationType["fieldType"] == $ClassificationFieldTypes.DROPDOWN())
    {
        for (var filterValue in pClassificationType["values"])
        {
            var parsedFilter = JSON.parse(filterValue);
            if(parsedFilter["filter"]["childs"].length != 1)
            {
                errorMessage += translate.withArguments("wrong configuration for '%0'", [pClassificationType["field"]]) + " " + translate.text("only use simple filters") +"\n";
            }
            else if((!pIsAttribute && parsedFilter["filter"]["childs"][0]["name"] != pClassificationType["field"]) || (pIsAttribute && !parsedFilter["filter"]["childs"][0]["name"].includes(pClassificationType["field"])))
            {
                errorMessage += translate.withArguments("wrong configuration for '%0'", [pClassificationType["field"]]) + " " + translate.text("only filter using the specified indicatorfield") +"\n";
            }
            else if(parsedFilter["filter"]["childs"][0]["operator"] != "EQUAL")
            {
                errorMessage += translate.withArguments("wrong configuration for '%0'", [pClassificationType["field"]]) + " " + translate.text("please only filter using 'equal'") +"\n";
            }
        }
    }
    if(errorMessage != "")
    {
        throw errorMessage;
    }
}


function ClassificationUpdateHelper() {}

/**
* Searches for pClassificationTypeId in pIndicatorObj and returns it's object<p><br>
* 
* @param {Object}pClassificationTypeId                    <p>
*                                                         condition of which classificationtypes to update<br>
*                                                          
* @param {Object}pIndicatorObj                            <p>
*                                                         return of buildindicatorObj()[objectType].<br>
*                                                          
*                                                          
* @return {Object}                                         <p> (empty Strings and Objects if not found)
*                                                          {"classificationGroupId": classificationGroupId
*                                                          , "fieldType": fieldType
*                                                          , "field": field
*                                                          , "maxPercent": maxPercent
*                                                          , "points": points
*                                                          , "values": {value: pointsForValue}}<br>
*/
ClassificationUpdateHelper._searchIndicatorObj = function(pClassificationTypeId, pIndicatorObj)
{
    for(var typeKind in pIndicatorObj)
    {
        for(var classificationTypeId in pIndicatorObj[typeKind])
        {
            if (pClassificationTypeId == classificationTypeId)
            {
                if (typeKind != $ClassificationIndicatorTypes.ATTRIBUTE())
                {
                    return pIndicatorObj[typeKind][classificationTypeId];
                }
                else
                {
                    pIndicatorObj[typeKind][classificationTypeId]["field"] = newSelect("ATTRIBUTE_NAME")
                                                        .from("AB_ATTRIBUTE")
                                                        .where("AB_ATTRIBUTE.AB_ATTRIBUTEID", AttributeSearchNameCoder.decode(pIndicatorObj[typeKind][classificationTypeId]["field"])["id"]).cell();
                    return pIndicatorObj[typeKind][classificationTypeId];
                }
            }
        }
    }
    return {"classificationGroupId": ""
            , "fieldType": ""
            , "field": ""
            , "maxPercent": ""
            , "points": ""
            , "values": {}};
};

/**
* Formats the output in an TwoDimensional array for Classification_entity and returns it (stringified!)<p><br>
* 
* @param {Object}pReturn                                  <p>
*                                                         return of ClassificationUpdateHelper._updateOutdatedDatasets()<br>
*                                                          
* @param {Object}pUid                                     <p>
*                                                         objectRowId we want to show the classifications for<br>
*                                                          
*                                                          
* @return {String}                                        <p> stringified contentProcessArray<br>
*/
ClassificationUpdateHelper._formatOutputForDisplayingValues = function(pReturn, pUid)
{
    var indicatorObj = pReturn["indicatorObj"];
    var achievedScoresObject = pReturn["achievedScoresObject"][pUid];
    var orderedGroups = pReturn["orderedGroups"];
    var classificationString = pReturn["newGradingString"];
    var groupNameObj = {};
    var contentProcessArray = [];
    var groupNames = newSelect("CLASSIFICATIONGROUP.CLASSIFICATIONGROUPID, CLASSIFICATIONGROUP.TITLE")
                        .from("CLASSIFICATIONGROUP")
                        .table();
    for (let i = 0; i < groupNames.length; i++)
    {
        groupNameObj[groupNames[i][0]] = "";
        groupNameObj[groupNames[i][0]] = groupNames[i][1];
    }
    var groupResultObj = {};
    for (var group in orderedGroups)
    {
        var groupId = orderedGroups[group]["0"];
        groupResultObj[groupId] = {};
        groupResultObj[groupId]["points"] = 0;
        groupResultObj[groupId]["maxPoints"] = 0;
        contentProcessArray.push([util.getNewUUID(), groupId, translate.text(groupNameObj[groupId]), "", "", "", "", ""]);
        for (var typeId in achievedScoresObject[groupId])
        {
            var typeInfo = ClassificationUpdateHelper._searchIndicatorObj(typeId, indicatorObj);

            if (achievedScoresObject[groupId][typeId]["key"] || achievedScoresObject[groupId][typeId]["key"] == "0")
            {
                contentProcessArray.push([util.getNewUUID(), groupId, "", typeId, achievedScoresObject[groupId][typeId]["fieldDisplay"], achievedScoresObject[groupId][typeId]["key"]
                        , achievedScoresObject[groupId][typeId]["value"], achievedScoresObject[groupId][typeId]["points"] + "/" + achievedScoresObject[groupId][typeId]["maxPoints"] + " " + translate.text("Points")]);
                groupResultObj[groupId]["points"] = eMath.addInt(parseInt(groupResultObj[groupId]["points"]), parseInt(achievedScoresObject[groupId][typeId]["points"]));
                groupResultObj[groupId]["maxPoints"] = eMath.addInt(parseInt(groupResultObj[groupId]["maxPoints"]), parseInt(achievedScoresObject[groupId][typeId]["maxPoints"]));
            }
            else
            {
                contentProcessArray.push([util.getNewUUID(), groupId, "", typeId, achievedScoresObject[groupId][typeId]["fieldDisplay"], "-"
                        , "-", "0" + "/" + typeInfo["points"] * typeInfo["maxPercent"] / 100 + " " + translate.text("Points")]);
                groupResultObj[groupId]["points"] = eMath.addInt(parseInt(groupResultObj[groupId]["points"]), parseInt(0));
                groupResultObj[groupId]["maxPoints"] = eMath.addInt(parseInt(groupResultObj[groupId]["maxPoints"]), parseInt(typeInfo["points"] * typeInfo["maxPercent"] / 100));
            }
        }
    }
    var position = 0;
    for (let i = 0; i < contentProcessArray.length; i++)
    {
        if (contentProcessArray[i][2] && contentProcessArray[i][2] != "")
        {
            contentProcessArray[i][2] = ClassificationUtils.formatDisplaySummaryForGroup(groupResultObj[contentProcessArray[i][1]]["points"], groupResultObj[contentProcessArray[i][1]]["maxPoints"], contentProcessArray[i][2], classificationString.substring(position, position + 1))
            position++;
        } 
    }

    return JSON.stringify(contentProcessArray);
};

/**
* Helper function, this get's used in ClassificationUpdateHelper._handleEntityFields, ClassificationUpdateHelper._handleAttributes an ClassificationUpdateHelper._handleComplex to get the correct value of the numbervalue<p><br>
* 
* @param {Array}pAttributeValues                          <p>
*                                                         All values this object has for this attribute<br>
*                                                          
* @param {Object}pClassificationType                      <p>
*                                                         as returned by buildindicatorObj()<br>
*                                                          
* @param {Object}pColumns                                 <p>
*                                                         columns of the objectType<br>
*                                                          
* @param {Object}pRows                                    <p>
*                                                         rows of the dataset<br>
*                                                         
* @param {String}pValue                                   <p>
*                                                         the valeu depending on the indicatortype<br>
*                                                         
* @param {boolean}pIsDate                                 <p>
*                                                         true if date, since we handle those a little different<br>
*                                                          
* @return {Object}                                        <p>{"key": 0
*                                                           , "percent": 0
*                                                           , "value": "-"} <- if none, else the actual values;
*/
ClassificationUpdateHelper._getCorrectNumberValue = function(pAttributeValues, pClassificationType, pColumns, pRows, pValue, pIsDate)
{
    var storedValues;
    if (pAttributeValues == undefined)//this record doesn't have a value for that attribute
    {
        storedValues = "ignoreThis";
    }
    else if (pAttributeValues)//atleast one value exists for this attribute
    {
        storedValues = pAttributeValues;
    }
    else if (pColumns)//fieldValue -> get from pRows
    {
        storedValues = [pRows[pColumns.indexOf(pClassificationType["field"], 0)]];
    }
    else
    {
        storedValues = [pValue];
    }
    var achievedPercent = {};
    achievedPercent = {"key": 0
                        , "percent": 0
                        , "value": "-"};

    if (pIsDate)
    {
        var orderedObject = {};
        Object.keys(pClassificationType["values"])
                    .sort()
                    .forEach(function(v, i) {
                        orderedObject[v] = pClassificationType["values"][v];
                     });
        pClassificationType["values"] = orderedObject;
    }

    for(var value in pClassificationType["values"])
    {
        if (storedValues != "ignoreThis")
        {
            for (var val in storedValues)
            {
                if (parseInt(storedValues[val]) >= parseInt(value) && parseInt(storedValues[val]) > parseInt(achievedPercent["key"]))
                {

                    achievedPercent = {};
                    achievedPercent["key"] = value;
                    achievedPercent["value"] = storedValues[val];
                    achievedPercent["percent"] = pClassificationType["values"][value];
                }
            }
        }
    }

    return{"key": achievedPercent["key"]
            , "value": achievedPercent["value"]
            , "maxPoints": pClassificationType["maxPercent"]/100*pClassificationType["points"]
            , "points": achievedPercent["percent"]/100*pClassificationType["points"]
            };
};

/**
* Builds the updateStatments.<p><br>
* 
* @param {Object}pAchievedScores                          <p>
*                                                         AchievedScoresObject built by handlEntityFields(), handleAttributes() and handleComplex()<br>
*                                                          
* @param {Object}pGradingObject                           <p>
*                                                         gradingObject as returned by ClassificationUpdateHelper._buildGradingObject()<br>
*                                                          
* @param {Object}pOrderedGroups                           <p>
*                                                         classificationGroups in the correct order (so we can update at the correct positions)<br>
*                                                          
* @param {Object}pCurrentValue                            <p>
*                                                         current classificationStorage string<br>
*                                                         
* @param {String}pRowId                                   <p>
*                                                         row Id of the current dataset<br>
*                                                         
* @param {boolean}pRowType                                <p>
*                                                         true if date, since we handle those a little different<br>
*                                                          
* @param {boolean}pUpdateStatements                       <p>
*                                                         the updateStatements we already have, we simply add ours to those<br>
*                                                          
* @param {String}pOutputInformation                       <p>
*                                                         we pass the outputinformation trough so we can add to the string<br>
*                                                          
* @return {Object}                                        <p>{"updateStatements": updateStatements
*                                                               , "outputInformation": outputInformation
*                                                               , "newGradingString": newGradingString};
*/
ClassificationUpdateHelper._buildUpdateClassificationValueStatements = function(pAchievedScores, pGradingObject, pOrderedGroups, pCurrentValue, pRowId, pRowType, pUpdateStatements, pOutputInformation)
{
    var pointsPerGroupObj = {};
    var newGradingString = pCurrentValue;
    for(var position in pOrderedGroups)
    {
        var groupId = pOrderedGroups[position][0];
        for(var type in pAchievedScores[groupId])
        {
            if (pAchievedScores[groupId][type]["points"] || pAchievedScores[groupId][type]["points"] == 0)
            {
                if (!pointsPerGroupObj.hasOwnProperty(groupId))
                {
                    pointsPerGroupObj[groupId] = {};
                    pointsPerGroupObj[groupId]["points"] = 0;
                    pointsPerGroupObj[groupId]["maxPoints"] = 0;
                }
                pointsPerGroupObj[groupId]["points"] = eMath.addInt(parseInt(pointsPerGroupObj[groupId]["points"]), parseInt(pAchievedScores[groupId][type]["points"]));
                pointsPerGroupObj[groupId]["maxPoints"] = eMath.addInt(parseInt(pointsPerGroupObj[groupId]["maxPoints"]), parseInt(pAchievedScores[groupId][type]["maxPoints"]));
            }
        }
        if (pointsPerGroupObj && pointsPerGroupObj[groupId])
        {
            newGradingString = StringUtils.replaceAt(newGradingString, position, ClassificationUtils.getGradingFromObject(pGradingObject, groupId, pointsPerGroupObj[groupId]["points"], pointsPerGroupObj[groupId]["maxPoints"]));
        }
    }

    if (pCurrentValue != newGradingString)
    {
        pUpdateStatements.push(["CLASSIFICATIONSTORAGE", ["CLASSIFICATIONVALUE", "OUTDATED"], null, [newGradingString, "0"], newWhere("CLASSIFICATIONSTORAGE.OBJECT_ROWID", pRowId).build()]);
        pOutputInformation[pRowType].updatedElements += 1;
    }
    else
    {
        pUpdateStatements.push(["CLASSIFICATIONSTORAGE", ["OUTDATED"], null, ["0"], newWhere("CLASSIFICATIONSTORAGE.OBJECT_ROWID", pRowId).build()]);
        pOutputInformation[pRowType].nonChangedElements++;
    }

    return {"updateStatements": pUpdateStatements
            , "outputInformation": pOutputInformation
            , "newGradingString": newGradingString};
};

/**
* Builds the updateStatments.<p><br>
* 
* @param {Array}pRowIds                                   <p>
*                                                         rowIds of datasets<br>
*                                                          
* @param {String}pCurrentObjectType                       <p>
*                                                         current Object Type we want the attributeObject for<br>
*                                                          
* @return {Object}                                        <p>attributeObj[objectRowId][encodedName] = [values];;
*/
ClassificationUpdateHelper._buildAttributeObject = function(pRowIds, pCurrentObjectType)
{
    var idColumn = pCurrentObjectType.toUpperCase() + "ID";
    if (pCurrentObjectType == "Organisation")
    {
        idColumn = "CONTACTID";
    }
    var attributeObj = {};
    if (pRowIds && pRowIds.length > 0)
    {
        var objectRowIds = [];
        for (let i = 0; i < pRowIds.length; i++)
        {
            objectRowIds.push(pRowIds[i][idColumn]);
        }

        //select attributevalues for the objectRowIds
        var attributeArray = newSelect(["AB_ATTRIBUTERELATION.OBJECT_ROWID", "AB_ATTRIBUTERELATION.AB_ATTRIBUTE_ID", "AB_ATTRIBUTERELATION.AB_ATTRIBUTERELATIONID",
                                        SqlBuilder.caseWhen(newWhere("AB_ATTRIBUTERELATION.CHAR_VALUE is not null"))
                                                            .then("AB_ATTRIBUTERELATION.CHAR_VALUE")
                                                            .elseValue(SqlBuilder.caseWhen(newWhere("AB_ATTRIBUTERELATION.ID_VALUE is not null"))
                                                                                    .then("AB_ATTRIBUTERELATION.ID_VALUE")
                                                                                    .elseValue("null")
                                                                                    .toString())
                                                            .toString()
                                            ,SqlBuilder.caseWhen(newWhere("AB_ATTRIBUTERELATION.INT_VALUE is not null"))
                                                            .then("AB_ATTRIBUTERELATION.INT_VALUE")
                                                            .elseValue(SqlBuilder.caseWhen(newWhere("AB_ATTRIBUTERELATION.NUMBER_VALUE is not null"))
                                                                                    .then("AB_ATTRIBUTERELATION.NUMBER_VALUE")
                                                                                    .elseValue("null")
                                                                                    .toString())
                                                            .toString()
                                        , "AB_ATTRIBUTE.ATTRIBUTE_TYPE"])
                        .from("AB_ATTRIBUTERELATION")
                        .join("AB_ATTRIBUTE", "AB_ATTRIBUTE_ID = AB_ATTRIBUTEID")
                        .where("AB_ATTRIBUTERELATION.OBJECT_ROWID", objectRowIds, SqlBuilder.IN())
                        .table();



        var helperObject = {};
        let objectRowId, attributeId, attributeRelationId, value, numericValue, attributeType;
        //assign them to attributeObj for easier access 
        for (let element  in attributeArray)
        {
Benjamin Ulrich's avatar
Benjamin Ulrich committed
            [objectRowId, attributeId, attributeRelationId, value, numericValue, attributeType] = attributeArray[element];
            var encodedName = AttributeSearchNameCoder.encode(attributeId, attributeType);

            if (!helperObject.hasOwnProperty(objectRowId))
            {
                attributeObj[objectRowId] = {};
                helperObject[objectRowId] = "";

            }
            if (!helperObject.hasOwnProperty(objectRowId + encodedName))
            {
                attributeObj[objectRowId][encodedName] = []; //same logic as before
                helperObject[objectRowId + encodedName] = "";
            }
            if (!helperObject.hasOwnProperty(attributeRelationId)) //objectRowId
            {
                let valueToPush = value && value != "" ? value : numericValue;
                attributeObj[objectRowId][encodedName].push(valueToPush);

                helperObject[attributeRelationId] = "";
            }
        }
    }
    return attributeObj;
};

//helper Function for better code-readability
ClassificationUpdateHelper._processObjectValuesBatchFn = function(pBatchData, pIndicatorObj, pAchievedScoresObject, pGradingObject, pOrderedGroups, pCurrentObjectType, pOutputInformation, pFieldDisplayObject, pFilteredRecsObj, pClassificationTypesNoFilterObj)
{
    var achievedScoresObject = pAchievedScoresObject;
    var attributeObj = ClassificationUpdateHelper._buildAttributeObject(pBatchData, pCurrentObjectType);//call for every "page"
    var updateStatements = [];

    var idColumn = pCurrentObjectType.toUpperCase() + "ID"
    if (pCurrentObjectType == "Organisation")
    {
        idColumn = "CONTACTID";
    }
    //logic from above applies here aswell
    for (let ii = 0; ii < pBatchData.length; ii++) 
    {
        var currentDataset = pBatchData[ii];
        if (currentDataset["CLASSIFICATIONVALUE"] && currentDataset["CLASSIFICATIONVALUE"] != "")
        {
            var columns = [];
            var values = [];

            for (var property in currentDataset)
            {
               if (!currentDataset.hasOwnProperty(property))
               {
                  continue;
               }
               columns.push(property);
               values.push(currentDataset[property]);
            }

                achievedScoresObject = ClassificationUpdateHelper._handleEntityFields(pIndicatorObj[$ClassificationIndicatorTypes.ENTITYFIELD()], values, columns, currentDataset[idColumn], achievedScoresObject, pFieldDisplayObject[pCurrentObjectType], pFilteredRecsObj, pClassificationTypesNoFilterObj, pCurrentObjectType);
                achievedScoresObject = ClassificationUpdateHelper._handleAttributes(pIndicatorObj[$ClassificationIndicatorTypes.ATTRIBUTE()], attributeObj, currentDataset[idColumn], achievedScoresObject, pFieldDisplayObject[pCurrentObjectType], pFilteredRecsObj, pClassificationTypesNoFilterObj, pCurrentObjectType);
                achievedScoresObject = ClassificationUpdateHelper._handleComplex(pIndicatorObj[$ClassificationIndicatorTypes.COMPLEX()], pCurrentObjectType, currentDataset[idColumn], achievedScoresObject, pFieldDisplayObject[pCurrentObjectType], pFilteredRecsObj, pClassificationTypesNoFilterObj);

                var buildUpdateClassificationValueStatements = ClassificationUpdateHelper._buildUpdateClassificationValueStatements(achievedScoresObject[currentDataset[idColumn]], pGradingObject, pOrderedGroups, currentDataset["CLASSIFICATIONVALUE"], currentDataset[idColumn], pCurrentObjectType, updateStatements, pOutputInformation);
                updateStatements = buildUpdateClassificationValueStatements["updateStatements"];
                pOutputInformation = buildUpdateClassificationValueStatements["outputInformation"];

        }
    }
    db.execute(updateStatements);
    var gradingString = buildUpdateClassificationValueStatements != undefined ? buildUpdateClassificationValueStatements["newGradingString"] : "";
    return {"achievedScoresObject": achievedScoresObject
            , "outputInformation": pOutputInformation
            , "newGradingString": gradingString};
};


/**
* Get's the entityfields of pCurrentObjectType by using ClassificationUtils.getEntityFields(), adds the uid column to it and returns it as array<p><br>
* 
* @param {Array}pCurrentObjectType                        <p>
*                                                         Object type you want the fields for<br>
*                                                          
* @return {Array}                                         <p>fields;
*/
ClassificationUpdateHelper._getEntityFields = function(pCurrentObjectType)
{
    var fieldArray = [];
    var entityFields = ClassificationUtils.getEntityFields(pCurrentObjectType);
    for(var field in entityFields)
    {
        fieldArray.push(entityFields[field][0]);
    }
    fieldArray.push("CLASSIFICATIONVALUE");
    if (pCurrentObjectType == "Organisation")
    {
        fieldArray.push("CONTACTID");
    }
    else
    {
        fieldArray.push(pCurrentObjectType.toUpperCase() + "ID");
    }


    return fieldArray;
};

/**
 * handles the complex indicators so you can add them to achievedScoresObject  <p><br>
 * 
 * @param {Object}pClassificationTypes                     <p>
 *                                                         as returned by buildindicatorObj()<br>
 *                                                          
 * @param {String}pObject                                  <p>
 *                                                         current Object Type<br>
 *                                                          
 * @param {String}pUid                                     <p>
 *                                                         current Object uid<br>
 *                                                          
 * @param {Object}pAchievedScoresObject                    <p>
 *                                                         achievedScoresObj we add ours to this<br>
 *                                                          
 * @param {Array[[][]]}pFieldDisplayObject                 <p>
 *                                                         twodimensional array with value and key so we can get the displayValues<br>  
 *                                                         
 * @param {Object}pFilteredRecsObj                         <p>
 *                                                         as returned by ClassificationUpdateHelper._buildFilteredRecsObject()<br>  
 *                                                         
 * @param {Object}pClassificationTypesNoFilterObj          <p>
 *                                                         as built by ClassificationUpdateHelper._buildFilterAndNoFilterObj()<br>  
 *                                                          
 * @return {Object}                                        <p>pAchievedScoresObject;
 */
 ClassificationUpdateHelper._handleComplex = function(pClassificationTypes, pObject, pUid, pAchievedScoresObject, pFieldDisplayObject, pFilteredRecsObj, pClassificationTypesNoFilterObj)
 {
     for(var type in pClassificationTypes)
     {
         if(ClassificationUpdateHelper._isRelevant(type, pUid, pClassificationTypes[type]["filter"], pFilteredRecsObj, pClassificationTypesNoFilterObj, pObject))
         {
             var achievedValueArray = $ClassificationComplexIndicatorRegistry[pClassificationTypes[type]["field"]]().getValueFn(pObject, pUid);

             for (var valueScore in pClassificationTypes[type]["values"])
             {
                 if (!pAchievedScoresObject.hasOwnProperty(pUid))
                 {
                     pAchievedScoresObject[pUid] = {};
                 }
                 if (!pAchievedScoresObject[pUid].hasOwnProperty(pClassificationTypes[type]["classificationGroupId"]))
                 {
                     pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]] = {};
                 }

                 if (!pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]].hasOwnProperty(type))
                 {   
                     pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type] = {};
                     pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["key"] = "-";
                     pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["value"] = "-";
                     pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["maxPoints"] = pClassificationTypes[type]["maxPercent"] / 100 * pClassificationTypes[type]["points"];
                     pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["points"] = 0;
                     pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["fieldDisplay"] = ClassificationUtils.getFieldDisplayValue(pFieldDisplayObject, pClassificationTypes[type]["field"]);
                 }

                 for (var value in achievedValueArray)
                 {
                     if (pClassificationTypes[type]["fieldType"] == $ClassificationFieldTypes.NUMBER() || pClassificationTypes[type]["fieldType"] == $ClassificationFieldTypes.INTEGER()
                         || pClassificationTypes[type]["fieldType"] == $ClassificationFieldTypes.DATE())
                     {
                         var numberValue;
                         if (pClassificationTypes[type]["fieldType"] == $ClassificationFieldTypes.DATE())
                         {
                             numberValue = ClassificationUpdateHelper._getCorrectNumberValue(false, pClassificationTypes[type], false, null, parseInt(achievedValueArray), true);
                         }
                         else
                         {
                             numberValue = ClassificationUpdateHelper._getCorrectNumberValue(false, pClassificationTypes[type], false, null, parseInt(achievedValueArray));
                         }

                         pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["key"] = numberValue["key"];
                         if (pClassificationTypes[type]["fieldType"] == $ClassificationFieldTypes.DATE())
                         {
                             pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["value"] = $ClassificationComplexIndicatorRegistry[pClassificationTypes[type]["field"]]().getDisplayValueFn(numberValue["key"].toString());
                         }
                         else
                         {
                             pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["value"] = numberValue["value"];
                         }
                         pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["maxPoints"] = numberValue["maxPoints"];
                         pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["points"] = numberValue["points"];
                     }
                     else
                     {
                         if (achievedValueArray[value] == valueScore)
                         {
                             pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["maxPoints"] = pClassificationTypes[type]["maxPercent"] / 100 * pClassificationTypes[type]["points"];
                             //replace if the value is greater than the one we already have
                             if (parseInt(pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["points"]) < parseInt(pClassificationTypes[type]["values"][valueScore])*parseInt(pClassificationTypes[type]["points"]) / 100)
                             {                                
                                 pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["points"] = parseInt(pClassificationTypes[type]["values"][valueScore]) * parseInt(pClassificationTypes[type]["points"]) / 100;
                                 pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["key"] = valueScore;
                                 pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["value"] = $ClassificationComplexIndicatorRegistry[pClassificationTypes[type]["field"]]().getDisplayValueFn(valueScore);

                             }
                         }
                     }
                 }
             }
         }
     }
     return pAchievedScoresObject;
 };
 
/**
* handles the attribute indicators so you can add them to achievedScoresObject  <p><br>
* 
* @param {Object}pClassificationTypes                     <p>
*                                                         as returned by buildindicatorObj()<br>
*                                                         
* @param {Object}attributeObj                             <p>
*                                                         as returned by ClassificationUpdateHelper._buildAttributeObject()<br>
*                                                          
* @param {String}pUid                                     <p>
*                                                         current Object uid<br>
*                                                          
* @param {Object}pAchievedScoresObject                    <p>
*                                                         achievedScoresObj we add ours to this<br>
*                                                         
* @param {Array[[][]]}pFieldDisplayObject                 <p>
*                                                         twodimensional array with value and key so we can get the displayValues<br>  
*                                                         
* @param {Object}pFilteredRecsObj                         <p>
*                                                         as returned by ClassificationUpdateHelper._buildFilteredRecsObject()<br>  
*                                                         
* @param {Object}pClassificationTypesNoFilterObj          <p>
*                                                         as built by ClassificationUpdateHelper._buildFilterAndNoFilterObj()<br>  
*                                                          
* @param {String}pCurrentObjectType                       <p>
*                                                         current Object Type<br>
*                                                          
* @return {Object}                                        <p>pAchievedScoresObject;
*/
ClassificationUpdateHelper._handleAttributes = function(pClassificationTypes, attributeObj, pUid, pAchievedScoresObject, pFieldDisplayObject, pFilteredRecsObj, pClassificationTypesNoFilterObj, pCurrentObjectType)
{
    var classificationTypes = pClassificationTypes;
    var currentAttributes = attributeObj[pUid];

    for(var type in classificationTypes)
    {
        if(ClassificationUpdateHelper._isRelevant(type, pUid, pClassificationTypes[type]["filter"], pFilteredRecsObj, pClassificationTypesNoFilterObj, pCurrentObjectType))
        {
            ClassificationUtils.validateUserSetValues(classificationTypes[type], true);
            if (!pAchievedScoresObject.hasOwnProperty(pUid))
            {
                pAchievedScoresObject[pUid] = {};
            }
            if (!pAchievedScoresObject[pUid].hasOwnProperty(classificationTypes[type]["classificationGroupId"]))
            {
                pAchievedScoresObject[pUid][classificationTypes[type]["classificationGroupId"]] = {};
            }
            if (!pAchievedScoresObject[pUid][classificationTypes[type]["classificationGroupId"]].hasOwnProperty(type))
            {
                pAchievedScoresObject[pUid][classificationTypes[type]["classificationGroupId"]][type] = {};
                pAchievedScoresObject[pUid][classificationTypes[type]["classificationGroupId"]][type]["points"] = 0;
                pAchievedScoresObject[pUid][classificationTypes[type]["classificationGroupId"]][type]["key"] = "-";
                pAchievedScoresObject[pUid][classificationTypes[type]["classificationGroupId"]][type]["value"] = "-";
                pAchievedScoresObject[pUid][classificationTypes[type]["classificationGroupId"]][type]["maxPoints"] = classificationTypes[type]["maxPercent"] / 100 * classificationTypes[type]["points"];
                pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["fieldDisplay"] = ClassificationUtils.getFieldDisplayValue(pFieldDisplayObject, pClassificationTypes[type]["field"]);
            }

            for (var filter in classificationTypes[type]["values"])
            {
                for (var attribute in currentAttributes)
                {
                    if (classificationTypes[type]["fieldType"] == $ClassificationFieldTypes.NUMBER() || classificationTypes[type]["fieldType"] == $ClassificationFieldTypes.INTEGER())
                    {
                        var numberValue = ClassificationUpdateHelper._getCorrectNumberValue(currentAttributes[classificationTypes[type]["field"]], pClassificationTypes[type]);

                        pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type] = {};
                        pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["key"] = numberValue["key"];
                        pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["value"] = numberValue["value"];
                        pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["maxPoints"] = numberValue["maxPoints"];
                        pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["points"] = numberValue["points"];
                        pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["fieldDisplay"] = ClassificationUtils.getFieldDisplayValue(pFieldDisplayObject, pClassificationTypes[type]["field"]);
                    }
                    else
                    {
                        var currentValue = JSON.parse(filter)["filter"]["childs"][0]["key"];
                        for (var attributeValue in currentAttributes[attribute])
                        {
                            if (currentAttributes[attribute][attributeValue] == currentValue || currentAttributes[attribute][attributeValue] == parseInt(currentValue))
                            {
                                    pAchievedScoresObject[pUid][classificationTypes[type]["classificationGroupId"]][type] = {};
                                    pAchievedScoresObject[pUid][classificationTypes[type]["classificationGroupId"]][type]["points"] = classificationTypes[type]["values"][filter]*classificationTypes[type]["points"] / 100;
                                    pAchievedScoresObject[pUid][classificationTypes[type]["classificationGroupId"]][type]["key"] = JSON.parse(filter)["filter"]["childs"]["0"]["key"];
                                    pAchievedScoresObject[pUid][classificationTypes[type]["classificationGroupId"]][type]["value"] = JSON.parse(filter)["filter"]["childs"]["0"]["value"];
                                    pAchievedScoresObject[pUid][classificationTypes[type]["classificationGroupId"]][type]["maxPoints"] = classificationTypes[type]["maxPercent"] / 100 * classificationTypes[type]["points"];
                                    pAchievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["fieldDisplay"] = ClassificationUtils.getFieldDisplayValue(pFieldDisplayObject, pClassificationTypes[type]["field"]);

                                //replace if the value is greater than the one we already have
                                if (parseInt(pAchievedScoresObject[pUid][classificationTypes[type]["classificationGroupId"]][type]["points"]) < parseInt(classificationTypes[type]["values"][filter])*parseInt(classificationTypes[type]["points"]) / 100)
                                {
                                    pAchievedScoresObject[pUid][classificationTypes[type]["classificationGroupId"]][type]["points"] = parseInt(classificationTypes[type]["values"][filter])*parseInt(classificationTypes[type]["points"]) / 100;
                                    pAchievedScoresObject[pUid][classificationTypes[type]["classificationGroupId"]][type]["key"] = JSON.parse(filter)["filter"]["childs"]["0"]["key"];
                                    pAchievedScoresObject[pUid][classificationTypes[type]["classificationGroupId"]][type]["value"] = JSON.parse(filter)["filter"]["childs"]["0"]["value"];
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return pAchievedScoresObject;
};

/**
 * handles the entityfield indicators so you can add them to achievedScoresObject  <p><br>
 * 
 * @param {Object}pClassificationTypes                     <p>
 *                                                         as returned by buildindicatorObj()<br>
 *                                                         
 * @param {Object}pColumns                                 <p>
 *                                                         columns of the objectType<br>
 *                                                          
 * @param {Object}pRows                                    <p>
 *                                                         rows of the dataset<br>
 *                                                          
 * @param {String}pUid                                     <p>
 *                                                         current Object uid<br>
 *                                                          
 * @param {Object}pAchievedScoresObject                    <p>
 *                                                         achievedScoresObj we add ours to this<br>
 *                                                                                                           
 * @param {Array[[][]]}pFieldDisplayObject                 <p>
 *                                                         twodimensional array with value and key so we can get the displayValues<br>  
 *                                                         
 * @param {Object}pFilteredRecsObj                         <p>
 *                                                         as returned by ClassificationUpdateHelper._buildFilteredRecsObject()<br>  
 *                                                         
 * @param {Object}pClassificationTypesNoFilterObj          <p>
 *                                                         as built by ClassificationUpdateHelper._buildFilterAndNoFilterObj()<br>  
 *                                                          
 * @param {String}pCurrentObjectType                       <p>
 *                                                         current Object Type<br>
 *                                                          
 * @return {Object}                                        <p>pAchievedScoresObject;
 */
 ClassificationUpdateHelper._handleEntityFields = function(pClassificationTypes, pRows, pColumns, pUid, pAchievedScoresObject, pFieldDisplayObject, pFilteredRecsObj, pClassificationTypesNoFilterObj, pCurrentObjectType)
 {
     var achievedScoresObject = pAchievedScoresObject;
     var helperObject = {};
     for (var type in  pClassificationTypes)
     {
         if(ClassificationUpdateHelper._isRelevant(type, pUid, pClassificationTypes[type]["filter"], pFilteredRecsObj, pClassificationTypesNoFilterObj, pCurrentObjectType))
         {
             var valueSet = false;
             ClassificationUtils.validateUserSetValues(pClassificationTypes[type]);
             for (var filter in pClassificationTypes[type]["values"])
             {
                 if (!valueSet)
                 {
                     if (!helperObject.hasOwnProperty(pUid))
                     {
                         helperObject[pUid] = {};
                         achievedScoresObject[pUid] = {};
                     }
                     if (!helperObject.hasOwnProperty(pUid + pClassificationTypes[type]["classificationGroupId"]))
                     {
                         helperObject[pUid + pClassificationTypes[type]["classificationGroupId"]] = {};
                         achievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]] = {};
                     }
                     if (!helperObject.hasOwnProperty(pUid + type))
                     {
                         helperObject[pUid + type] = {};
                         achievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type] = 0;
                     }
                     if (pClassificationTypes[type]["fieldType"] == $ClassificationFieldTypes.NUMBER() || pClassificationTypes[type]["fieldType"] == $ClassificationFieldTypes.INTEGER())
                     {
                         var numberValue = ClassificationUpdateHelper._getCorrectNumberValue(false, pClassificationTypes[type], pColumns, pRows);
                         achievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type] = {};
                         achievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["key"] = numberValue["key"];
                         achievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["value"] = numberValue["value"];
                         achievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["maxPoints"] = numberValue["maxPoints"];
                         achievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["points"] = numberValue["points"];
                         achievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["fieldDisplay"] = ClassificationUtils.getFieldDisplayValue(pFieldDisplayObject, pClassificationTypes[type]["field"]);
                     }
                     else
                     {
                         if(achievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["fieldDisplay"] == undefined)
                         {
                             achievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type] = {};
                             achievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["fieldDisplay"] = ClassificationUtils.getFieldDisplayValue(pFieldDisplayObject, pClassificationTypes[type]["field"]);
                         }

                         var filterValue = JditoFilterUtils.filterRecords(pColumns, [pRows], JSON.parse(filter).filter);
                         if (filterValue.length > 0)
                         {
                             achievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["key"] = JSON.parse(filter)["filter"]["childs"]["0"]["key"];
                             achievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["value"] = JSON.parse(filter)["filter"]["childs"]["0"]["value"];
                             achievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["maxPoints"] = pClassificationTypes[type]["maxPercent"] / 100 * pClassificationTypes[type]["points"];
                             achievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["points"] = 0;
                             achievedScoresObject[pUid][pClassificationTypes[type]["classificationGroupId"]][type]["points"] = parseInt(pClassificationTypes[type]["values"][filter]) * parseInt(pClassificationTypes[type]["points"]) / 100;
                             valueSet = true;
                         }
                     }
                 }
             }
         }
     }
     return achievedScoresObject;
 };
 
/**
* builds the indicatorObject, which stores all the classificationTypes we need with all their information like value, displayvalue, indicatortype, fieldType, maxpoints, max percents and their possible values and their percent  <p><br>
* 
*                                                         
* @param {Object}pCurrentObjectType                       <p>
*                                                         Object Type (needed, altough we have the object table, since organisation as example uses contact as it's table<br>
*                                                          
* @return {Object}                                        <p>indicatorObj[indicatorType][typeId] = {"classificationGroupId": classificationGroupId
*                                                                           , "fieldType": fieldType
*                                                                           , "field": field
*                                                                           , "maxPercent": maxPercent
*                                                                           , "points": points
*                                                                           , "filter": filter
*                                                                           , "values": {value: percent}
*/
ClassificationUpdateHelper._buildindicatorObj = function(pCurrentObjectType)
{
    var currentObjectType = pCurrentObjectType;
    var indicatorObj = {};
    var helperObj2 = {};
    indicatorObj[$ClassificationIndicatorTypes.ENTITYFIELD()] = {};
    indicatorObj[$ClassificationIndicatorTypes.ATTRIBUTE()] = {};
    indicatorObj[$ClassificationIndicatorTypes.COMPLEX()] = {};


    var classificationTypeScorePoints = newSelect("CLASSIFICATIONTYPE.CLASSIFICATIONGROUP_ID, CLASSIFICATIONTYPE.CLASSIFICATIONTYPEID, CLASSIFICATIONSCORE.CLASSIFICATIONSCOREID\n\
                                                    , CASE WHEN CLASSIFICATIONSCORE.INDICATORTEXT is not null THEN CLASSIFICATIONSCORE.INDICATORTEXT ELSE \n\
                                                        CASE WHEN CLASSIFICATIONSCORE.INDICATORNUMBER is not null THEN CLASSIFICATIONSCORE.INDICATORNUMBER ELSE  \n\
                                                            CASE WHEN CLASSIFICATIONSCORE.INDICATORINTEGER is not null THEN CLASSIFICATIONSCORE.INDICATORINTEGER ELSE \n\
                                                                CASE WHEN CLASSIFICATIONSCORE.FIELDVALUE is not null THEN CLASSIFICATIONSCORE.FIELDVALUE ELSE null \n\
                                                                end\n\
                                                            end\n\
                                                        end\n\
                                                      END\n\
                                                        , CLASSIFICATIONTYPE.SCOREPOINTS, CLASSIFICATIONTYPE.FIELD, CLASSIFICATIONTYPE.FIELDTYPE \n\
                                                        , CLASSIFICATIONTYPE.INDICATORTYPE, CLASSIFICATIONSCORE.SCOREPERCENT, CLASSIFICATIONTYPE.SCOREPOINTS, CLASSIFICATIONTYPE.FILTER")
                                                    .from("CLASSIFICATIONSCORE")
                                                    .join("CLASSIFICATIONTYPE", "CLASSIFICATIONSCORE.CLASSIFICATIONTYPE_ID = CLASSIFICATIONTYPE.CLASSIFICATIONTYPEID")
                                                    .where("CLASSIFICATIONTYPE.OBJECT_TYPE", currentObjectType)
                                                    .orderBy("CLASSIFICATIONTYPE.CLASSIFICATIONGROUP_ID, CLASSIFICATIONTYPE.CLASSIFICATIONTYPEID")
                                                    .table();
    for (let i = 0; i < classificationTypeScorePoints.length; i++)
    {
        var typeId = classificationTypeScorePoints[i][1];

        if (classificationTypeScorePoints[i][7] && classificationTypeScorePoints[i][6] != "")
        {
            if (!helperObj2.hasOwnProperty(typeId))
            {
                indicatorObj[classificationTypeScorePoints[i][7]][typeId] = {"classificationGroupId": classificationTypeScorePoints[i][0]
                                                                            , "fieldType": classificationTypeScorePoints[i][6]
                                                                            , "field": classificationTypeScorePoints[i][5]
                                                                            , "maxPercent": classificationTypeScorePoints[i][8]
                                                                            , "points": classificationTypeScorePoints[i][9]
                                                                            , "filter": classificationTypeScorePoints[i][10]
                                                                            , "values": {}
                                                                            };
                helperObj2[typeId] = "";
            }

            if (classificationTypeScorePoints[i][7] == $ClassificationIndicatorTypes.COMPLEX() && classificationTypeScorePoints[i][6] == $ClassificationFieldTypes.DATE()) // we don't use the actual value as the key for the dates, since they change daily
            {
                indicatorObj[classificationTypeScorePoints[i][7]][typeId]["values"][$ClassificationComplexIndicatorRegistry[classificationTypeScorePoints[i][5]]().getActualDateValueFn(classificationTypeScorePoints[i][3].toString())] = classificationTypeScorePoints[i][8];
            }
            else
            {
                indicatorObj[classificationTypeScorePoints[i][7]][typeId]["values"][classificationTypeScorePoints[i][3]] = classificationTypeScorePoints[i][8];
            }
            if (parseFloat(indicatorObj[classificationTypeScorePoints[i][7]][typeId]["maxPercent"]) < parseFloat(classificationTypeScorePoints[i][8]))
            {
                indicatorObj[classificationTypeScorePoints[i][7]][typeId]["maxPercent"] = classificationTypeScorePoints[i][8];
            }
        }
    }
    return indicatorObj;
};

/**
 * Builds filteredRecsObj Object which stores all the included Datasets to the specific filter.
 * (loops trough classificationTypesFilterObj and uses either entites.getRow or an select for every different filter)
 */
ClassificationUpdateHelper._buildFilteredRecsObject = function(pClassificationTypesFilterObj, pCurrentObjectType, pFilterFields)
{
    var currentObjectType = pCurrentObjectType;
    var filteredRecsObj = {}; //reset for every objectType
    var executeGetRows = true; //reset for every objectTyp

    for (var index in pClassificationTypesFilterObj[currentObjectType])
    {
        for (var indexIndex in pClassificationTypesFilterObj[currentObjectType][index]) 
        {
            var unparsedFilter = pClassificationTypesFilterObj[currentObjectType][index][indexIndex];
            var filter = JSON.parse(unparsedFilter).filter;
            //filteredRecsObj uses the filter as the key -> if multiple indicators use the exact same filtercondition we only have to get these rows once