Example Empty Rater File

function rate(date, riskId, debugOverrideFlag, premiumOutputConfigObject) {

    //Find Risk in database
    var risk = db.risk.find({
        'RiskId': riskId
    }).sort({
        'Modified': -1
    }).limit(1);

    //Global arrays
    var debugObject = {};
    var debugVariables = [];
    var debugLookups = [];
    var debugLog = [];
    var results = [];
    var errors = [];

    //UI Questions
    var uiQuestions = [];

    //Input Data
    var inputData = [];

    var questionsToCheck = {};
    var questions = [];
    
    // Output
    var technicalPremiums = [];

    debugLog.push('>> Running TechnicalPremium');

    //Run initialise function
    initialise();

    //Setting Output Object
    var outputObject = {
        Type: 'Output',
        Errors: errors,
        UIQuestions: uiQuestions,
        InputData: inputData
    };

    //Adding Debug To Output
    if (debugOverrideFlag) {
        debugObject['Debug Variables'] = debugVariables;
        debugObject['Debug Lookups'] = debugLookups;
        debugObject['Debug Log'] = debugLog;
        
        outputObject['Debug'] = debugObject;
    }

    //Add to results
    technicalPremiums.push(outputObject);

    //Return Technical Premiums
    return technicalPremiums;


    function initialise() {
        debugLog.push('> Running initialise');

        //Return individual risk record
        risk = risk.toArray();

        if (risk.length === 0) {
            addError('CONFIG', 'Unable to find risk in database');
        } else if (risk.length > 1) {
            addError('CONFIG', 'Found multiple risk records in database');
        } else if (risk.length === 1) {
            risk = risk[0];
        }

        //Set Questions
        questions = risk['Questions'];
        getQuestion(questions);
        questions = questionsToCheck;

        //Calculate Premiums
        calculatePremiums();
    }

    function calculatePremiums() {
        //Global Questions
        var premiumCurrency = getQuestionAnswer('RiskCurrency');
        var commissionPercentage = getQuestionAnswer('Commission');
        
        //Premium Sections
        exampleCover();


        // Functions
        function exampleCover() {
            var sectionCode = 'ExampleCover';
            var classOfBusiness = 'Example Cover';
            
            addNormalDebug("Processing Section", classOfBusiness); //addNormalDebug(name, value, printNewLine)

            var additionalProperties = {};
            var overrides = {};

            //Premium Calculations
            var commissionPercentage = 0;
            var limit = 0;
            var excess = 0;
            var premium = 0;

            //Round Premium
            premium = currencyRound(premium);
            debugLog.push('premium (rounded): ' + premium);
            
            //Return Object
            var returnObject = {
                'Type': 'TechnicalPremium',
                'SectionCode': sectionCode,
                'ClassOfBusiness': classOfBusiness,
                'Premium': premium,
                'AdditionalPremium': 0,
                'Limit': limit,
                'Excess': excess,
                'CommissionPercentage': commissionPercentage,
                'PremiumCurrency': premiumCurrency,
                'LimitCurrency': premiumCurrency,
                'AttachmentPointCurrency': premiumCurrency,
                'AdditionalProperties': additionalProperties
            };
            
            //Push to technicalPremiums
            technicalPremiums.push(returnObject);
        }
    }

    //Global Functions
    function addError(errorType, errorText) {
        errors.push({
            'Type': errorType,
            'Text': errorText
        });
    }

    //Add UI Question
    function addUIQuestion(questionsArray, questionCode, questionAnswer) {
        var found = questionsArray.find(q => q['QuestionCode'] === questionCode);

        if (found) {
            found['QuestionAnswer'] = questionAnswer;
        } else {
            var question = {
                'QuestionCode': questionCode,
                'QuestionAnswer': questionAnswer
            }
            questionsArray.push(question);
        }
    }

    function getQuestion(questions) {
        for (var i = 0; i < questions.length; i++) {
            var questionAnswer = "";
            try {
                questionAnswer = JSON.parse(questions[i].QuestionAnswer);
            } catch (error) {
                questionAnswer = questions[i].QuestionAnswer;
            }
            questionsToCheck[questions[i].QuestionCode] = (!questionAnswer || questionAnswer["_csharpnull"]) ? null : questionAnswer;
            if (questions[i].SubQuestions && questions[i].SubQuestions.length > 0) {
                getQuestion(questions[i].SubQuestions);
            }
        }
    }

    // Common code to get question and print to debug
    function getQuestionAnswer(questionCode, defaultIfNull) {
        var otherReturn = defaultIfNull ? defaultIfNull : '';
        var value = questions[questionCode] ? questions[questionCode] : otherReturn;
        
        try {
            value = JSON.parse(value);
        } catch (err) {
            // Failed, but no need to throw error
        }
        
        var printNewLine = false;
        if (typeof value === 'object' || typeof value === 'array') {
            printNewLine = true;
        }
        
        addDebug(value, debugVariables, questionCode, printNewLine);
        return value;
    }
    
    // Common code to get a lookup and print to debug
    function getLookup(table, filter, resultColumn, valueIfNotFound, title) {
        var value = null;
        if (valueIfNotFound) {
            value = singleRateLookup(table, filter, resultColumn, true, valueIfNotFound);
        } else {
            value = singleRateLookup(table, filter, resultColumn, false, null);
        }
        addDebug(value, debugLookups, title);
        return value;
    }
    
    function singleRateLookup(collection, filters, returnColumn, allowNotFound, valueIfNotFound) {
        //Fallback value for rate that can't be found
        var returnValue = -1;

        //If a different fallback value is provided
        if (valueIfNotFound !== undefined) {
            returnValue = valueIfNotFound;
        }

        //Setting up query
        var queryAnd = [];

        //Filters
        if (filters && Array.isArray(filters) && filters.length > 0) {
            for (var x = 0; x < filters.length; x++) {
                var filter = filters[x];
                queryAnd.push(filter);
            }
        }

        var query = { };
        if (queryAnd.length > 0) {
            query['$and'] = queryAnd
        }

        var queryResults = db[collection].find(query).sort({
            'Modified': -1
        }).limit(1);

        var results = queryResults.toArray();
        if (results.length === 1) {
            if (results[0].hasOwnProperty(returnColumn)) {
                returnValue = results[0][returnColumn];
            } else {
                addError('Lookup', 'Failed to find "' + returnColumn + '" in "' + collection + '"');
            }
        } else if (results.length > 1) {
            addError('Lookup', 'Lookup returned multiple rows for "' + returnColumn + '" from "' + collection + '"');
        } else if (!allowNotFound) {
            addError('Lookup', 'Failed to return "' + returnColumn + '" from "' + collection + '"');
        }
        
        return returnValue;
    }
    
    // If required, you  can provide the heading (name) of the variable to help identify it in debug
    function addDebug(value, target, name, printNewLine) {
        if (debugOverrideFlag && value) {
            var title = name ? name : value;
        
            if (printNewLine) {
                target.push(title + "...");
                target.push(value);
            } else { 
                target.push(title + ": " + value);
            }
        }
    }
    
    // Here for ease
    function addNormalDebug(name, value, printNewLine) {
        addDebug(value, debugLog, name, printNewLine);
    }
    
    //Add RiskCode
    function addRiskCode(riskCodesArray, riskCode, riskCodeShare) {
        riskCodesArray.push({ 'RiskCode': riskCode, 'Share': riskCodeShare ? parseFloat(riskCodeShare) : 0 });
    }

    function currencyRound(num) {
        var num = num.toString().replace(/,/g, '');
        num = parseFloat(num);
        return Math.round(num * 100) / 100;
    }

    function round(num, decimalPlaces) {
        var num = num.toString().replace(/,/g, '');
        num = parseFloat(num);
        const factorOfTen = Math.pow(10, decimalPlaces);
        return Math.round(num * factorOfTen) / factorOfTen;
    }
}

Last updated