Script client element onChange consecutive number

Mario Preciado
Tera Contributor

Dear Developers,

I request your support as my code is being executed from an element task. This code retrieves a consecutive number from another table to create a new task and sets the consecutive number in a form field. The code works as intended, but it happened that two executives created a ticket at the same time, assigning the same consecutive number. I would like to clarify that this script is executed before pressing the update button of the task. What can I do to prevent this from happening and avoid assigning the same consecutive number? Below is the code I use:

 

 

function onChange(control, oldValue, newValue, isLoading) {
    try {
        // Exit the function if the page is still loading or the new value is empty.
        if (isLoading || newValue === '') {
            return;
        }

        // Get the value of the 'se_genera_oat' field.
        var goat = g_form.getValue('se_genera_oat');

        // Get the current date in 'yyMMdd' format.
        var now = new Date();
        var year = now.getFullYear().toString().slice(2);
        var month = ('0' + (now.getMonth() + 1)).slice(-2);
        var day = ('0' + now.getDate()).slice(-2);
        var mesActual = year + month;

        var type = new GlideAjax('AjaxHoras');
        type.addParam('sysparm_name', 'horaDetails');
        type.getXML(function(response) {
            try {
                var ans = response.responseXML.documentElement.getAttribute("answer");
                var temp = ans.split('^');
                var fechaH = temp[0]; // YYYY-MM-DD HH:MM:SS AM/PM

                // If the value of 'se_genera_oat' is 'Yes', generate the 'OAT' code + current date and assign it to the 'oat' field. But first, check if there are existing records and if so, add consecutive numbers.
                var oatsPrefix = 'OAT' + mesActual;
                var counter = 0; // Initialize the counter

                try {
                    var oatE = new GlideRecord('u_gesti_n_de_oat_historico');
                    oatE.addQuery('u_oat', 'STARTSWITH', oatsPrefix);
                    oatE.orderBy('u_oat'); // Order by ascending order
                    oatE.query();

                    while (oatE.next()) {
                        // Continue iterating until there are no more records
                        counter++;
                    }

                    while (true) {
                        // Increment the counter until finding an OAT that does not exist
                        counter++;
                        var tempOatsNumber = ('0' + counter).slice(-2);
                        var tempOats = oatsPrefix + tempOatsNumber;
                        oatE = new GlideRecord('u_gesti_n_de_oat_historico');
                        oatE.addQuery('u_oat', tempOats);
                        oatE.query();
                        if (!oatE.hasNext()) {
                            // If the OAT does not exist, exit the loop
                            var oatsNumber = tempOatsNumber;
                            break;
                        }
                    }

                    var oats = oatsPrefix + oatsNumber;
                    g_form.clearValue('oasis');
                    g_form.setValue('oat', oats);
                    g_form.setValue('recib_oat_para_tramite', fechaH);
                    g_form.setValue('a_ventas', fechaH);
                    g_form.setValue('a_concil', fechaH);
                    g_form.setValue('a_factur', fechaH);
                } catch (error1) {
                    alert("Error in AJAX response function: " + error1);
                }
            } catch (error2) {
                alert("Error in AJAX response function: " + error2);
            }
        });
    } catch (error) {
        alert("Error in onChange function: " + error);
    }
}

 

 

 

Thanks for your support in advance.

 
 
 
 
 
3 REPLIES 3

-O-
Kilo Patron
Kilo Patron

The only reliable solution is to do it in an insert business rule.
Doing it client side will always run into the problem that you never know if the number is saves/used in the same order as handed out, or if the number is even saved/used.

E.g. 2 users load the form, each is given a consecutive number, but maybe the user who has order 1 does not save the record, so now you only have the record with consecutive number 2; or 1st the user that has received consecutive number 2 saves its records and so consecutive number 2 will "exist" before consecutive number 1, which depending on why this number needs to be consecutive might or might not be a problem.

Server side this can be handled better in an on-before business rule set to run the very last to avoid insert being interrupted by a current.setAbortAction(true) call after the consecutive number is set.

Community Alums
Not applicable

Hi @Mario Preciado  ,

 

Use Before Insert Business Rule to check if the number exists. Doing it in client script is always unpredictable & please avoid using glide record in client scripts.

 

You can check "Number Maintenance" module if it satisfies your requirement.

Sai149_0-1716261140694.png

 

I started answering community questions recently. If my answer helped you in any way, please mark it as helpful or correct. It would be a great boost. 

Mario Preciado
Tera Contributor

I need something to help me validate that someone else is not using that number in real time, leave it alone to the first and assign a consecutive to the second, all this before saving the information