Split Backordered items to a new Sales Order

Whenever a Sales Order include items which are backordered, those items are removed from the original order and a new Sales Order is created with the backordered items. A saved search is used to identify the Sales Orders to be considered for splitting. This saved search is passed as script parameter.

function processSplitOrders() {
    try {
        var daysToAdd = nlapiGetContext().getSetting('SCRIPT', 'custscript_added_days_split_so2');
        if (!daysToAdd || daysToAdd == '') {
            daysToAdd = 0;
        }
        var filterDate = new Date();
        var filters = new Array();
        nlapiLogExecution('Error', 'daysToAdd', daysToAdd);
       var savedSearchID = nlapiGetContext().getSetting('SCRIPT', 'custscript_split_order_ss2');

        if (salesOrders) {
            nlapiLogExecution('Error', 'salesOrders', salesOrders.length);
for (var i = 0; i < salesOrders.length; i++) {
                nlapiLogExecution('DEBUG', 'salesOrders ID=' + salesOrders[i].getId(), i);
                var columns = salesOrders[i].getAllColumns();
                var currentSOID = salesOrders[i].getId(),
                    copyOrderWeight = 0;

                var filters = new Array(),
                    columns = new Array();

                filters[0] = new nlobjSearchFilter("custbody_split_order_id", null, "is", currentSOID);

                var soLinkSrch = nlapiSearchRecord("salesorder", 888, filters);

                if (!soLinkSrch) {
                    var soRecord = nlapiLoadRecord('salesorder', currentSOID, { 'recordmode': 'dynamic' });

                 
                    var noOfPromo = soRecord.getLineItemCount('promotions');
                    nlapiLogExecution("DEBUG", "noOfPromo", noOfPromo)
                    var promotionArray = [];
                    for (var itemPromo = 1; itemPromo <= noOfPromo; itemPromo++) {
                        var promotionItemsList = {};
                        promotionItemsList.promoItem = soRecord.getLineItemValue('promotions', 'discount', itemPromo);
                        promotionItemsList.promoDiscount = soRecord.getLineItemValue('promotions', 'purchasediscount', itemPromo);
                        promotionItemsList.eligibleFreeGift = soRecord.getLineItemValue('promotions', 'eligiblefreegifts', itemPromo);
                        promotionItemsList.discountTaxable = soRecord.getLineItemValue('promotions', 'discountistaxable', itemPromo);
                        promotionItemsList.applicablyStatus = soRecord.getLineItemValue('promotions', 'applicabilitystatus', itemPromo);
                        promotionArray.push(promotionItemsList);

                    }
                    nlapiLogExecution("DEBUG", "promotionArray", JSON.stringify(promotionArray))

                    var itemCount = soRecord.getLineItemCount('item'),
                        specialOrderItems = [],
                        specialOrderItemsQty = [];
                    var allLinesCommited = true;
                    var noLineCommited = true;
                    for (var it = 1; it <= itemCount; it++) {
                        var orderStatus = soRecord.getLineItemValue('item', 'commitinventory', it),//value 6 is ready to ship
                            orderedQty = soRecord.getLineItemValue('item', 'quantity', it),
                            commitedQty = soRecord.getLineItemValue('item', 'quantitycommitted', it);

                        //  nlapiLogExecution("Error", "orderedQty "+orderedQty, "commitedQty "+commitedQty);
                        if (((orderedQty - commitedQty) == 0)) {
                            allLinesCommited = false;
                        }

                        //  nlapiLogExecution("Error", "orderedQty "+orderedQty, "commitedQty "+commitedQty);
                        if (((orderedQty - commitedQty) != 0)) {
                            noLineCommited = false;
                        }
                    }
                    nlapiLogExecution("Error", "allLinesCommited " + allLinesCommited, "noLineCommited " + noLineCommited);
                    if (!allLinesCommited && !noLineCommited) {
                        var copyOrder = nlapiCopyRecord('salesorder', currentSOID, { 'recordmode': 'dynamic' });
                        /*Updated by JJ0016*/
                        //set a flag in the record.
                        var copyOrderLines = copyOrder.getLineItemCount('item');
                        var soOrderLines = soRecord.getLineItemCount('item');
                        for (var it = copyOrderLines; it >= 1; it--) {
                            var orderStatus = copyOrder.getLineItemValue('item', 'commitinventory', it),//value 6 is ready to ship
                                orderedQty = soRecord.getLineItemValue('item', 'quantity', it),
                                itemId = soRecord.getLineItemValue('item', 'item', it),
                                commitedQty = soRecord.getLineItemValue('item', 'quantitycommitted', it),
                                SOlocation = soRecord.getFieldValue('location'),
                                NeedToCommit = orderedQty - commitedQty;

                            if (NeedToCommit > 0) {
                                nlapiLogExecution("DEBUG", "Item in loop--BO ITem", soRecord.getLineItemText('item', 'item', it))
                                copyOrder.selectLineItem('item', it)
                                copyOrder.setCurrentLineItemValue('item', 'custcol_jj_backordered_order_split', 'T');
                                copyOrder.setCurrentLineItemValue('item', 'custcol_jj_backordered_quantity_split', NeedToCommit);
                                copyOrder.commitLineItem('item');
                                var isSpecialItem = soRecord.getLineItemValue('item', 'custcol_is_special_ord_item', it);
                                if (isSpecialItem == "T") {
                                    specialOrderItems.push(itemId);
                                    specialOrderItemsQty.push(orderedQty);
                                }
                            }

                        }


                        var copyOrderLines = copyOrder.getLineItemCount('item');
                        var soOrderLines = soRecord.getLineItemCount('item');
                        for (var it = copyOrderLines; it >= 1; it--) {
                            var isBackOrdered = copyOrder.getLineItemValue('item', 'custcol_jj_backordered_order_split', it);
                            var BackorderedQty=copyOrder.getLineItemValue('item', 'custcol_jj_backordered_quantity_split', it);

                            if ((isBackOrdered == 'F' || isBackOrdered == false)) {
                                copyOrder.removeLineItem('item', it);
                            } else {
                                if (SOlocation == 140) {
                                    nlapiLogExecution("Error", "entered");
                                    copyOrder.selectLineItem('item', it)
                                    copyOrder.setCurrentLineItemValue('item', 'quantity', BackorderedQty);
                                    copyOrder.commitLineItem('item');
                                }
                                copyOrderWeight += Number(copyOrder.getLineItemValue('item', 'custcol_item_weight', it));

                            }
                        }

                        copyOrder.setFieldValue('custbody_split_order_id', currentSOID);
                        copyOrder.setFieldValue("custbody_back_order", "T");
                        copyOrder.setFieldValue('trandate', nlapiDateToString(new Date()));
                        try {
                            copyOrder.setFieldValue("tobeemailed", "F");
                            copyOrder.setFieldValue('shippingcost', 0);

                            if (copyOrder.getFieldValue('shipmethod') == 7801)
                                copyOrder.setFieldValue('shipmethod', 7789);
                            nlapiLogExecution('Error', 'copyOrderWeight', copyOrderWeight);
                            copyOrder.setFieldValue('custbody_total_wt', copyOrderWeight.toFixed(2));


                            // check for custentity7  : Updated by JJ0200
                            var customer=copyOrder.getFieldValue('entity');
                            var backorders= nlapiLookupField('customer', customer, 'custentity7');

                            if((backorders=='')||(backorders==null)||(backorders==undefined)){
                                nlapiLogExecution('Error', 'backorders', backorders);
                            }
                           // if custentity7 is No Backorders then Close the split order
                            else if(backorders==3){
                               var count = copyOrder.getLineItemCount('item');
                               for (var i = 1; i <= count; i++) {
                                   copyOrder.selectLineItem('item', i);
                                   copyOrder.setCurrentLineItemValue('item','isclosed', 'T');
                                   copyOrder.commitLineItem('item');
                               }
                           }
                            // if custentity7 is Must Confirm Backorders then set split order status to Pending approval
                            else if(backorders==2){
                               copyOrder.setFieldValue('orderstatus', 'A');
                           }

                            try {

                                var copyOrderID = nlapiSubmitRecord(copyOrder, true, true);
                            } catch (e) {
                                nlapiLogExecution("ERROR", "Error @ save order", e);
                            }
                            //copyOrder = nlapiLoadRecord('salesorder', copyOrderID);



                            for (var it = itemCount; it >= 1; it--) {
                                var orderStatus = soRecord.getLineItemValue('item', 'commitinventory', it),//value 6 is ready to ship
                                    orderedQty = soRecord.getLineItemValue('item', 'quantity', it),
                                    commitedQty = soRecord.getLineItemValue('item', 'quantitycommitted', it),
                                    SOCAlocation = soRecord.getFieldValue('location');
                                if (((orderedQty - commitedQty) != 0)) {
                                    if (SOCAlocation == 140) {
                                        if (commitedQty > 0) {
                                            nlapiLogExecution('Error', 'SOCAlocation', SOCAlocation);
                                            soRecord.selectLineItem('item', it);
                                            soRecord.setCurrentLineItemValue('item', 'quantity', commitedQty);
                                            soRecord.commitLineItem('item');
                                        } else {
                                            soRecord.removeLineItem('item', it);
                                        }
                                    } else {
                                        soRecord.removeLineItem('item', it);
                                    }
                                }
                            }
                            //soRecord.setFieldValue('shippingcost', 0);
                            soRecord.setFieldValue('custbody_split_order_id', copyOrderID);

                            //checking all promotion added to the order
                            var itemCount = soRecord.getLineItemCount('item');
                            for (var it = itemCount; it >= 1; it--) {
                                //get item name
                                var item = soRecord.getLineItemValue('item', 'item', it);
                                var amount = soRecord.getLineItemValue('item', 'amount', it)

                                //check the item already added in the so
                                for (var j = 0; j < promotionArray.length; j++) {
                                    if (promotionArray[j]['promoItem'] == item) {
                                        // if(promotionArray[i]['promoDiscount']>0) {
                                        promotionArray[j]['promoDiscount'] = Number(promotionArray[j]['promoDiscount']) - (Number(amount))
                                        // }else{
                                        //     promotionArray[i]['promoDiscount'] = Number(promotionArray[i]['promoDiscount']) + Number(amount)
                                        // }
                                    }
                                }
                            }
                            nlapiLogExecution("DEBUG", "Latest promotion array", JSON.stringify(promotionArray))
                            // remaining promotions are needed to add in so
                            for (var k = 0; k < promotionArray.length; k++) {
                                if (promotionArray[k]['applicablyStatus'] == "APPLIED") {
                                    soRecord.selectNewLineItem('item');
                                    soRecord.setCurrentLineItemValue('item', 'item', promotionArray[k]['promoItem']);
                                    //custom
                                    soRecord.setCurrentLineItemValue('item', 'price', -1);
                                    soRecord.setCurrentLineItemValue('item', 'price_display', "Custom");
                                    soRecord.setCurrentLineItemValue('item', 'amount', promotionArray[k]['promoDiscount']);

                                    // commit the line to the database
                                    soRecord.commitLineItem('item');

                                }
                            }

                            nlapiSubmitRecord(soRecord, true, true);
                            nlapiLogExecution("Error", "copyOrderID " + copyOrderID, "currentSOID " + currentSOID);
                            //var ack = checkForSpecialOrderItemAndCreateOrder(specialOrderItems,specialOrderItemsQty);
                            for (var s = 0; s < specialOrderItems.length; s++) {
                                var itmId = specialOrderItems[s],
                                    qty = specialOrderItemsQty[s];
                                var itemrec = nlapiLoadRecord("inventoryitem", itmId);

                                var vendorId = itemrec.getLineItemValue("itemvendor", "vendor", 1);

                                var poRec = nlapiCreateRecord("purchaseorder");
                                poRec.setFieldValue("entity", vendorId);
                                poRec.setFieldValue("tobeemailed", "F");
                                poRec.selectNewLineItem("item");
                                poRec.setCurrentLineItemValue("item", "item", itmId);
                                poRec.setCurrentLineItemValue("item", "quantity", qty);
                                poRec.commitLineItem("item");
                                nlapiLogExecution("Error", "itmId" + itmId, "qty" + qty);
                                //var poId = nlapiSubmitRecord(poRec,true,true);
                            }
                            //nlapiLogExecution("Error", "ack", ack);
                        }
                        catch (e) {
                            nlapiLogExecution('Error', 'e', e);
                        }
                    } else {
                        // make split order false
                        nlapiSubmitField('salesorder', currentSOID, 'custbody_split_processing', 'F')
                    }
                    //  }
                } else {
                    //  nlapiSubmitField('salesorder',currentSOID,'custbody_split_processing','F')
                }
                // }
            }
        }
        //nlapiScheduleScript("customscript_change_so_status_schedule", "customdeploy_change_so_status_schedule_m");
    }
    catch (error) {
        var err_message = "";
        if (error instanceof nlobjError) {
            err_message = error.getDetails();
        } else {
            err_message = error.toString();
        }
        nlapiLogExecution("Error", "Error Message", err_message);
    }
}

Leave a comment

Your email address will not be published. Required fields are marked *