Skip to content

ft3 Extension Functions

Updated pdexter 2021-12-10

ft3 Extension Functions is a Ruleset-Include which is designed to add "helper" functions which can simplify coding with some of the complex objects we come across in rulesets.

Usage

Include the rulesetInclude "ft3 Extension Functions"

#include "ft3 Extension Functions",

Objects/Functions Available

Object/Function Description
esResult A handler for the ElasticSearch result object returned by ft3.findDocumentsByElastic.
getCountByEqry A function to return the count of documents matching a query.
getDialogConfirm A function to open a confirm/cancel dialog and return whether confirmed or cancelled.
getDocsByEqry A function to return an array of documents matching a query.
getFieldNamesOfPanel A function to fetch the field names within a panel definition of the template.
refreshSCDataTable A function to reload an sc-data-tables component.

esResult

esResult is designed to handle the result object returned by findDocumentsByElastic, and allow the developer to write more readable code.

Syntax

var esResultObject = ft3.esResult(elasticSearchResult);

Part Description
esResultObject handler object used to interrogate result
elasticSearchResult JSON object returned by findDocumentsByElastic

Once this object is created, it can be used to get information from the result using functions of the object:

Function Description Old Method
isValid Returns true if the result is a valid ElasticSearch result; false if not. if (result && result.data && result.data.hits && result.data.hits.hits) ...
toDocArray Returns a document array from the result result.data.hits.hits.map(function(hit){return hit._source});
isComplete Returns whether the result contains all matches to the query, or whether only a limited count of matches. if (result.data.hits.total > result.data.hits.hits.length) ...
fullCount Returns the total of matches from the query, which may be more than the result contains. result.data.hits.total
count Returns the number of matches to the query contained in the results, which may be less than the full potential count. result.data.hits.hits.length
firstDocument Returns the first document of the query results. result.data.hits.hits[0]._source

Example

ruleQueryLots : {
    ruleCondition : function(ntf) { 
        return (
            ntf.context.fieldChanged === 'commonName'
            && ntf.context.newValue === 'test000'
        );
    },

    ruleAction : function(ntf, callback) { 
        var ft3 = ntf.scope;
        var eqry = {"query": {"bool": {"filter": [
            {'term' : {'appTags' : 'spider'}},
            {'term' : {'systemHeader.systemType' : 'document'}}
        ]}}}; 
        eqry.size = 5;

        ft3.findDocumentsByElastic(eqry, ntf.userId, function(err, result) {
            var esResult = ft3.esResult(result);
            if (err) {
                ntf.errorMessage = 'Error on query: ' + err.message;
            }
            else if (esResult.isValid()) {
                var docs = esResult.toDocArray();

                var spiderNames = docs.map(function(doc){
                    return doc.commonName;
                });
                ntf.document.description = 'All Spiders: \n' + spiderNames.join(', ');

                if (!esResult.isComplete()) {
                    ntf.document.description += ', (incomplete list)';
                }

                ntf.document.description += '\n\n# Total Spiders: ' + esResult.fullCount();

                ntf.document.description += '\n# fetched by query: ' + esResult.count();

                ntf.document.description += '\n\n# First Spider found: ' + esResult.firstDocument().commonName;
            }
            else {
                alert('esResult not valid');
            }

            callback();
        });
    }
},

getCountByEqry

Returns a count of documents in the database which match a specified query.

This is intended to be used in place of the full ft3.findDocumentsByElastic call with handling function when all that is required is the count of resulting documents.

This is an awaitable function, hence knowledge of async/await is required. The containing ruleAction block is required to be declared "async".

If an error occurs, then the variable ntf.errorOnEqry is set (error object).

Caveat: This value may be inexact for queries which cover very large numbers of documents, under ElasticSearch 7; the upper limit here is 10000.

Internally, this only queries for a maximum of 1 result, thus reducing network traffic, but the full potential count is returned for use.

Example

    ruleAction : async function(ntf, callback) {
        var ft3 = ntf.scope;

        // -----------------------------------------------------------------
        // Query for open Costs on this Action
        // -----------------------------------------------------------------
        var eqry = {'query':{'bool':{
            'filter':[
                {'term':{'appTags':'cww'}},
                {'term':{'appTags':'cost'}},
                {'term':{'parentsRel.documentId':ntf.document.documentId}}
            ],
            must_not : [
                {term : {'status' : 'Cancelled'}}
            ]
        }}};

        var recCount = await ft3.getCountByEqry(ntf, eqry);

        if (ntf.errorOnEqry) {
            ntf.errorMessage = 'Error in query for Costs: ' + ntf.errorOnEqry.message;
            callback(); return;
        }

        ntf.logger.info('Found ' + recCount + ' Cost items.');

        callback();
    }

getDialogConfirm

Returns true or false on a confirmation dialog, structured with SweetAlert.

Requires the #include "SweetAlert Dialog"

This is an awaitable function, hence knowledge of async/await is required. The containing ruleAction block is required to be declared "async".

Example

ruleAction : async function(ntf, callback) {
    var ft3 = ntf.scope;

    var confirm = await ft3.getDialogConfirm(ntf, {
        title : 'Waiting',
        text : 'Click ok when ready',
        showCancelButton : true
    });

    if (confirm) {
        ft3.showNotification('Ok clicked');
    }
    else {
        ft3.showNotification('Cancel clicked')
    }
    callback();
}

getDocsByEqry

Returns an array of documents for a specified query.

This is intended to be used in place of the full ft3.findDocumentsByElastic call with handling function when all that is required is the resulting documents (arguably 99% of all usages).

This is an awaitable function, hence knowledge of async/await is required. The containing ruleAction block is required to be declared "async".

Example

ruleQuerySpiderNames : {
    ruleCondition : function(ntf) { 
        return (
            ntf.context.fieldChanged === 'commonName'
            && ntf.context.newValue === 'test000'
        );
    },

    ruleAction : function(ntf, callback) { 
        var ft3 = ntf.scope;
        var eqry = {"query": {"bool": {"filter": [
            {'term' : {'appTags' : 'spider'}},
            {'term' : {'systemHeader.systemType' : 'document'}}
        ]}}}; 
        eqry.size = 5;

        var docs = await ft3.getDocsByEqry(ntf, eqry);

        if (ntf.errorOnEqry) {
            ntf.errorMessage = 'Error in query for Spiders: ' + ntf.errorOnEqry.message;
            callback(); return;
        }

        var spiderNames = (docs || []).map(doc => doc.commonName);
        ntf.document.description = 'All Spiders: \n' + spiderNames.join(', ');
        callback();
    }
},

getFieldNamesOfPanel

Returns all the fields within a named panel defined by a sc-static-html component pair.

Syntax

var fieldNames = ft3.getFieldNames(ntf, panel-name );

This may be of use when one wants to hide a panel and clear all of its fields.

refreshSCDataTable

Reloads a sc-data-tables field on the document.

Syntax

ft3.refreshSCDataTable( field-name )