Get a first look at what's coming. The Developer Passport Australia Release Preview kicks off March 12. Dive in! 

RITM to SCTASK attachment copy – duplicates and email attachments corrupted

RushikeshB24337
Mega Contributor

Good day, everyone. I hope you're all doing well.

I am trying to copy attachments from RITM to SCTASK using a Business Rule on sys_attachment (after insert).

Flow:

- User uploads files in portal → RITM created
- User sends additional attachments via email
- SCTASK is created

Issue:

1. Attachments are getting duplicated in SCTASK
2. Email attachments are getting corrupted in SCTASK (but work fine in RITM)

Implementation on BR on sys_attachment (after insert) with condition tablename = sc_req_item   
Script:- 

   var ritm = current.table_sys_id;
 
    var grSCTask = new GlideRecord('sc_task');
        grSCTask.addQuery('request_item', ritm);
        grSCTask.query();
 
        while(grSCTask.next()){
 
            var att = new GlideRecord('sys_attachment');
                att.addQuery('table_sys_id', grSCTask.sys_id.toString());
                att.query();
                att.deleteMultiple();
       
            GlideSysAttachment.copy('sc_req_item', ritm, 'sc_task', grSCTask.sys_id);
 
            // var gsa = new GlideSysAttachment();
            //  gsa.writeContentStream(
            //      grSCTask,
            //      current.file_name,
            //      current.content_type,
            //      gsa.getContentStream(current.sys_id.toString()));
        }    
})(current, previous);

What is the recommended way to copy RITM attachments to SCTASK without duplication and corruption (especially for email attachments).




1 REPLY 1

ayushraj7012933
Kilo Guru

 

Hi,

The issue is happening because the Business Rule is deleting and re-copying all attachments every time a new attachment is added. This leads to duplicates and also causes corruption for email attachments, as they may not be fully processed when the rule runs.

Recommended Approach

Instead of deleting and copying all attachments, you should copy only the newly added attachment and add a check to avoid duplicates.

Updated Script

 

 
(function executeRule(current, previous) {

if (current.table_name != 'sc_req_item')
return;

var ritmId = current.table_sys_id;

var grSCTask = new GlideRecord('sc_task');
grSCTask.addQuery('request_item', ritmId);
grSCTask.query();

while (grSCTask.next()) {

// Check if attachment already exists
var attCheck = new GlideRecord('sys_attachment');
attCheck.addQuery('table_sys_id', grSCTask.sys_id);
attCheck.addQuery('file_name', current.file_name);
attCheck.query();

if (!attCheck.hasNext()) {

var gsa = new GlideSysAttachment();
gsa.writeContentStream(
grSCTask,
current.file_name,
current.content_type,
gsa.getContentStream(current.sys_id)
);
}
}

})(current, previous);