Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to delete duplicate catalog item draft

Obito
Tera Expert

Hi all,

 

I need to delete duplicate catalog item draft. I need to only keep last created. There is one question 'Jira ID'  where I am getting unique value from Jira, Based on that question's value I have do the glide aggregate count. If the count is greater than 1 (means there are more than 1 record where Jira Id is same) then I will only keep the latest one.  

How can I write this glide aggregate code?

1 ACCEPTED SOLUTION

@Obito and by what script - BR, catalog client script (calling Ajax), scheduled job, flow, .... ? 

Not knowing your conditions, to delete it always or under conditions, for all user or just some...?

 

Then you can write your code accordingly pointing to the table I shared [sc_cart_item].

 

———
/* If my response wasn’t a total disaster ↙️ drop a Kudos or Accept as Solution ↘️ Cheers! */


View solution in original post

7 REPLIES 7

Ankur Bawiskar
Tera Patron
Tera Patron

@Obito 

what's your actual business requirement?

when should the drafts for that catalog item be deleted?

what's the trigger?

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

raviteja1600
Tera Guru

Hi @Obito ,

 

Please try with the below script to delete the Duplicate Catalog items

(function() {
    var ga = new GlideAggregate('sc_cart_item'); // or your catalog item table
    ga.addAggregate('COUNT');
    ga.groupBy('u_jira_id'); // Replace with the actual question variable name or field
    ga.query();

    while (ga.next()) {
        var jiraId = ga.getValue('u_jira_id');
        var count = parseInt(ga.getAggregate('COUNT'));

        if (count > 1) {
            // Get all records with this Jira ID, sorted by creation date descending
            var gr = new GlideRecord('sc_cart_item');
            gr.addQuery('u_jira_id', jiraId);
            gr.orderByDesc('sys_created_on');
            gr.query();

            var keepFirst = true;
            while (gr.next()) {
                if (keepFirst) {
                    keepFirst = false; // Keep the latest one
                    continue;
                }

                // Delete older duplicates
                gr.deleteRecord();
            }
        }
    }
})();

 

If the provided solution is helpful to you, please mark it as "Helpful" and "Accept" the solution.

 

Regards,

Raviteja

anurampalli
Tera Guru

Sort the response by descending datetime. Skip the first record and delete the rest.