Example: Duplicate a container

This example script duplicates a container and all its contents, copying the assigned participants. This script could be used with a custom button, allowing users to generate a new project that matches a template project, or it could be used as an automation embedded in a workflow. For example, this script could create a new marketing campaign or product launch project with a standard set of assets, such as logos, icons, and templates, and a standard set of assigned roles, such as the marketing lead, product manager, and creative services team.

This sample script duplicates a container. You could write your own custom script to create a similar automation and add any additional operations required for your project or container templatization process.

Example script
const siteBaseURL = "https://orangedam.orangelogic.com/";
const siteBearer = "[Secret.OrangeDAM-Bearer-token]";
const containerTypes = ["Album","Story","Project"]
var childContainers = [];

function main() {
    var initialChildren = getContainerContents("[Document.EncryptedRecordID]","[Document.CoreField.DocType]");
    Log.Error("initialChildren: "+ JSON.stringify(initialChildren));
    var initialParentRecordID = cloneRecord("[Document.EncryptedRecordID]", "[Document.CoreField.TitleWithFallback]", "[Document.CoreField.Mother]");
    Log.Error("initialParentRecordID: "+initialParentRecordID);
    cloneContents(initialParentRecordID,initialChildren);
    Log.Error('childContainers: '+JSON.stringify(childContainers));
    while (childContainers.length > 0) {
        let contents = getContainerContents(childContainers[0].originRecordID,childContainers[0].originType);
        Log.Error('contents of '+childContainers[0].originRecordID+': '+JSON.stringify(contents));
        cloneContents(childContainers[0].clonedRecordID,contents);
        Log.Error(`Removing: ${JSON.stringify(childContainers[0])}`);
        childContainers.splice(0, 1);
        // childContainers.shift(); // Removes the first element of the array
    }
    Log.Error("Array is now empty!");
}

function getContainerContents(recordID,docType) {
    var children = [];
    Utils.CallInternalAPI(
        '/webapi/objectmanagement/relations/getcontent_46W_v1?ObjectRecordID='+recordID+'&DocType='+docType+'&Fields=CoreField.DocType&Fields=CoreField.TitleWithFallback&SeeThru=false',
        // Success callback function
        function (_sResp) {        
            var oResp = JSON.parse(_sResp);
            Log.Error('Executed getContent sucessfully: '+ JSON.stringify(oResp));
            var contentItems = [];
            try {
                contentItems = JSON.parse(oResp.Response.Response).contentItems;
            } catch(e) {Log.Error('JSON.parse(oResp.Response.Response).contentItems; failed.');}
            if (contentItems.length < 1) {
                Log.Error('contentItems.length < 1');
                try {
                    contentItems = oResp.Response.Response.contentItems;
                } catch(e) {Log.Error('oResp.Response.Response.contentItems; failed.');}
            }
            Log.Error('contentItems: '+JSON.stringify(contentItems));
            children = contentItems;
        }, 
        // Failure callback function
        function (_sResp) {
            Log.Error('Execution Failed: '+ _sResp);
        }    
    );
    return children
}

function cloneRecord(targetRecordID, originalTitle, parentRecordID) {
    var newRecordID = "";
    var postBody = {
        "targetDocumentID": targetRecordID,
        "cloneDescendents": true,
        "title": "Clone of "+ originalTitle,
        "motherID": parentRecordID,
        //"relatedDocumentID": "",
        //"relationshipWithOtherDocument": ""
    };
    Log.Error('clone postBody: '+JSON.stringify(postBody));
    var headers = {"Authorization": siteBearer};
    Utils.ExecuteHttpRequest(siteBaseURL+'webapi/objectmanagement/singleobjecttools/clone/41q_v1',
        {
        Method: 'POST',
        Headers: headers,
        Data: postBody
        },
        // Success callback function
        function (oHttp) {
        var oResult = JSON.parse(oHttp.responseText);
        Log.Error('clone Executed successfully: ' + JSON.stringify(oResult));
        let newRecords = oResult.createdDocuments
        Object.keys(newRecords).forEach(key => {
            Log.Error(`${key}: ${JSON.stringify(newRecords[key])}`);
            newRecordID = newRecords[key].documentID;
        });
        }, 	
        // Failure callback function
        function (oHttp) {
        var oResult = JSON.parse(oHttp.responseText);
        Log.Error('Execution failed: ' + JSON.stringify(oResult))
        }	
    );
    return newRecordID
}

function cloneContents(parentRecordID,contents) {
    Log.Error("all contents: "+JSON.stringify(contents)+" to "+parentRecordID);
    if (contents == "") {
        Log.Error('contents = ""');
    } else {
        if (!(Array.isArray(contents))) {
        Log.Error("was not array");
        contents = [contents];
        Log.Error('contents: '+JSON.stringify(contents));
    }
    for (i=0;i<contents.length;i++) {
        Log.Error('contents[i]: '+JSON.stringify(contents[i]));
        if (containerTypes.includes(contents[i].fields['CoreField.DocType'])) {
            let clonedRecord = cloneRecord(contents[i].recordID, contents[i].fields['CoreField.TitleWithFallback'], parentRecordID);
            Log.Error('clonedRecord: '+JSON.stringify(clonedRecord) + " original record "+JSON.stringify(contents[i]));
            childContainers.push({'originRecordID': contents[i].recordID, 'originType': contents[i].fields['CoreField.DocType'], 'clonedRecordID':clonedRecord})
            if (contents[i].fields['CoreField.DocType'] == 'Project') {
                copyParticipants(contents[i].recordID,clonedRecord)
            }
        } else {
            cloneRecord(contents[i].recordID, contents[i].fields['CoreField.TitleWithFallback'], parentRecordID)
        }
    }
    Log.Error("childContainers: "+JSON.stringify(childContainers));
    }
}

function copyParticipants(originRecordID,newRecordID) {
    // /api/DocumentParticipants/v1.0/CopyParticipants
    Utils.CallInternalAPI(
        '/api/DocumentParticipants/v1.0/CopyParticipants?SourceRecordID='+originRecordID+'&TargetRecordIDs='+newRecordID+'&SyncParticipants=true&format=JSON',
        // Success callback function
        function (_sResp) {        
            var oResp = JSON.parse(_sResp);
            Log.Error('Executed sucessfully: '+ _sResp);
        }, 
        // Failure callback function
        function (_sResp) {
            Log.Error('Execution Failed: '+ _sResp);
        }    
    );
}

main()