Partial item Receipt creation API

We have created a custom API for item receipts through the Restlet API. If items and quantity are requested and if it is there in the corresponding purchase order, a request is received for those items and item receipt is created.

In a transfer order, items are transferred from one location to another. When items are fulfilled and shipped, and the items and quantity for which the request is sent, item receipt is created for those items for the specified quantity.

Developer Document

GitHub Link

Swyft_Inc/JJ RL Partial Item receipt creation SWYFT-45.js at main · Jobin-And-Jismi-IT-Services-LLP/Swyft_Inc · GitHub

Suitescript

/**
 *@NApiVersion 2.1
 *@NScriptType Restlet
 */
/*******************************************************************************
 * SWYFT-45   Partial Item receipt creation through RESTlet API
 * *************************************************************************
 * 
 * Created Date: 10-03-2021
 * 
 * Author: Jobin & Jismi IT Services LLP
 *
 * Revision  History:
 * Revision 1.0 ${10-03-2021} Gloria : created 
 * 
 *****************************************************************************
 **/

//global variables
var errorJson = {};
var successJson = {};
var error = false;
var itemquantity = {};
var reason = [];
var allowedStatus = {
    'Partially Received': 'Partially Received',
    'Pending Billing/Partially Received': 'Pending Billing/Partially Received',
    'Pending Receipt': 'Pending Receipt',
    'Pending Receipt/Partially Fulfilled': 'Pending Receipt/Partially Fulfilled'
}
var receivedFulfillments = {};

define(['N/search', 'N/record'],
    function (search, record) {
        //entry point
        function post(requestBody) {
            try {
                var itemReceiptIds = [];
                log.debug('requestBody', requestBody);
                if (requestBody.type == 'purchaseorder') {
                    itemReceiptIds = purchaseOrderProcess(requestBody);
                } else if (requestBody.type == 'transferorder') {
                    itemReceiptIds = transferOrderProcess(requestBody);
                } else {
                    error = true;
                    errorJson = { type: 'error', name: 'TYPE_IS_MISSING', reason: 'The order type is missing in the request.' }
                }

                log.debug('errorJson', errorJson)
                var response = processResponse(itemReceiptIds, requestBody);
                return JSON.stringify(response);
            } catch (e) {
                log.error('error@post', e)
            }
        }

        /**
         * purchase order processing function
         * @param {Object} requestBody 
         */
        function purchaseOrderProcess(requestBody) {
            try {
                var itemReceiptIds = [];
                var selectedLines = [];
                var orderId = requestBody.orderId;
                var items = requestBody.items;
                var memo = requestBody.memo
                log.debug('items', items)
                if (orderId) {
                    var POSearchResult = getPurchaseOrderId(orderId)

                    if (POSearchResult && POSearchResult.id) {
                        if (allowedStatus[POSearchResult.status]) {
                            if (items && items.length) {
                                //transforming the purchase order to item receipt
                                var itemRecieptRec = record.transform({
                                    fromType: 'purchaseorder',
                                    fromId: POSearchResult.id,
                                    toType: 'itemreceipt',
                                    isDynamic: true,
                                });

                                //item line count
                                var itemlineCount = itemRecieptRec.getLineCount({
                                    sublistId: 'item'
                                });

                                //expense line count
                                var explineCount = itemRecieptRec.getLineCount({
                                    sublistId: 'expense'
                                });

                                //unmarking receive check boxes on each  expense line if it exists

                                if (explineCount)
                                    for (var index = 0; index < explineCount; index++) {

                                        itemRecieptRec = itemRecieptRec.selectLine({
                                            sublistId: 'expense',
                                            line: index
                                        });
                                        itemRecieptRec.setCurrentSublistValue({
                                            sublistId: 'expense',
                                            fieldId: 'itemreceive',
                                            value: false,
                                            // ignoreFieldChange: true
                                        });
                                        itemRecieptRec.commitLine({
                                            sublistId: 'expense'
                                        });

                                    }

                                //creating the array of objects from item lines of item receipt
                                var itemLines = getSublist(itemRecieptRec, 'item').reduce(function (a, v, idx) {
                                    a.push({
                                        item: v.item,
                                        itemtype: v.itemtype,
                                        itemname: v.itemname,
                                        quantity: v.quantity,
                                        itemreceive: v.itemreceive,
                                        location: v.location,
                                        line: v.line,
                                        orderline: v.orderline,
                                        index: idx
                                    });
                                    return a;
                                }, [])
                                log.debug('itemLines', itemLines)

                                //iterating over the item list given in the request
                                for (var i = 0; i < items.length; i++) {
                                    if (items[i].hasOwnProperty("itemid") && items[i].hasOwnProperty("quantity")) {

                                        //creating an object containing key as the item name and value as the quantity of the item needed to be created for item receipt.
                                        if (itemquantity[items[i].itemid])
                                            itemquantity[items[i].itemid] = itemquantity[items[i].itemid] + items[i].quantity;
                                        else
                                            itemquantity[items[i].itemid] = items[i].quantity;

                                    } else {
                                        error = true;
                                        errorJson = { type: "error", name: "INVALID_REQUEST_BODY", reason: "The request body is not in valid format, missing parameter 'itemid'/'quantity'or both." };
                                        break;
                                    }
                                }

                                //iterating over the item list given in the request
                                for (var i = 0; i < Object.keys(itemquantity).length; i++) {

                                    //filter the item lines of specific item 
                                    var lines = itemLines.filter(function (item) {
                                        return item.item.value == Object.keys(itemquantity)[i];
                                    });
                                    log.debug('lines', lines)

                                    //if lines exists
                                    if (lines && lines.length) {
                                        //recieve the items, setuping the item lines of item receipt
                                        var result = setItemLines(itemRecieptRec, lines, Object.keys(itemquantity)[i], 'purchase', itemquantity)
                                        log.debug('result', result)

                                        //slected lines from the transformed item receipt
                                        selectedLines = selectedLines.concat(result.selectedLines);


                                    }


                                }

                                log.debug('selectedLines', selectedLines)


                                //if error does not exists.
                                if (!error) {
                                    //set memo
                                    if (memo)
                                        itemRecieptRec.setValue({ fieldId: 'memo', value: memo })
                                    //remove unrequired lines

                                    for (var index = 0; index < itemlineCount; index++) {

                                        if (selectedLines.indexOf(index) == -1) {
                                            itemRecieptRec.selectLine({
                                                sublistId: 'item',
                                                line: index
                                            });
                                            itemRecieptRec.setCurrentSublistValue({
                                                sublistId: 'item',
                                                fieldId: 'itemreceive',
                                                value: false,
                                                // ignoreFieldChange: true
                                            });
                                            itemRecieptRec.commitLine({
                                                sublistId: 'item'
                                            });
                                        }
                                    }

                                    var itemLinesFinal = getSublist(itemRecieptRec, 'item').reduce(function (a, v, idx) {
                                        a.push({
                                            item: v.item,
                                            itemtype: v.itemtype,
                                            itemname: v.itemname,
                                            quantity: v.quantity,
                                            itemreceive: v.itemreceive,
                                            location: v.location,
                                            line: v.line,
                                            orderline: v.orderline,
                                            index: idx
                                        });
                                        return a;
                                    }, [])
                                    log.debug('itemLinesFinal', itemLinesFinal)
                                    if (selectedLines.length) {
                                        var recordId = itemRecieptRec.save({
                                            enableSourcing: true,
                                            ignoreMandatoryFields: true
                                        });
                                        log.debug('recordId', recordId)
                                        itemReceiptIds.push(recordId)
                                    } else {
                                        error = true;
                                        errorJson = { type: 'error', name: 'ITEM_DOES_NOT_EXIST', reason: 'The requested item/items does not exists in the Purchase order.' }
                                    }
                                    for (var key in itemquantity) {
                                        if (Number(itemquantity[key]) > 0) {
                                            reason.push(itemquantity[key] + " '" + key + "'")
                                        }
                                    }

                                    if (!reason.length)
                                        successJson = { type: "success", name: "ITEM_RECEIPT_CREATED_SUCCESSFULLY", reason: "The item receipt is created successfully." }
                                }
                            } else {
                                error = true;
                                errorJson = { type: "error", name: "INVALID_REQUEST_BODY", reason: "The request body is not in valid format, missing parameter 'itemid'/'quantity'or both." };
                                return errorJson
                            }
                        } else {
                            error = true;
                            errorJson = { type: "error", name: "ORDER_NOT_IN_PROPER_STATUS", reason: "The order is not in a status to create item receipt. Please provide a valid order id." }
                            return errorJson
                        }
                    } else {
                        error = true;
                        errorJson = { type: "error", name: "ORDER_DOES_NOT_EXIST", reason: "The order does not exists. Please provide a valid order id." }
                        return errorJson
                    }
                } else {
                    error = true;
                    errorJson = { type: "error", name: "ORDER_ID_IS_MISSING", reason: "The order id is missing in the Request." }
                    return errorJson
                }
                log.debug('errorJson', errorJson)
                return itemReceiptIds
            } catch (e) {
                log.error("errror@1", e)
                error = true;
                errorJson = { type: "error", name: e.name, reason: e.message }
            }

        }

        /**
         * Transfer order processing function
         * @param {object} requestBody 
         */
        function transferOrderProcess(requestBody) {
            try {
                var orderId = requestBody.orderId;
                var items = requestBody.items ? requestBody.items : '';
                var fulfillments = [];
                var groupedFulfillment;
                var itemReceiptIds = [];
                var itemDoesNotExists = []
                log.debug('items', items)
                if (orderId) {


                    var fieldLookUp = search.lookupFields({
                        type: 'transferorder',
                        id: orderId,
                        columns: ['internalid']
                    });
                    log.debug('fieldLookUp', fieldLookUp)
                    //if the order exists in netsuite
                    if (fieldLookUp.internalid && fieldLookUp.internalid.length) {
                        //transfer order search to find the order internal id and its item fulfillments
                        var orderSearchObj = getTransferOrderDetails(orderId)
                        log.debug('orderSearchObj', orderSearchObj)
                        if (orderSearchObj.id && allowedStatus[orderSearchObj.status]) {

                            //if item fulfillments exists for the order
                            if (orderSearchObj.fulfillments && orderSearchObj.fulfillments.length) {
                                if (requestBody.hasOwnProperty("itemfulfillment")) {
                                    if (requestBody.itemfulfillment) {
                                        //getting the item lines related to the requested itemfulfillment.
                                        var fulfillmentLines = orderSearchObj.fulfillments.filter(function (item) {
                                            return item.fulfillment == requestBody.itemfulfillment;
                                        });
                                        log.debug('fulfillmentLines', fulfillmentLines);
                                        if (fulfillmentLines && fulfillmentLines.length) {
                                            if (items && items.length) {
                                                // //getting the item lines.
                                                // var itemlines = fulfillmentLines.filter(function (item) {
                                                //     return item.item == items[i].itemid;
                                                // });
                                                //iterating over item list requested
                                                fulfillments = itemLineIteration(items, itemDoesNotExists, fulfillmentLines, fulfillments)

                                                log.debug('fulfillemnts', fulfillments)
                                                if (!error) {
                                                    createItemReceiptFromTO(orderId, requestBody.itemfulfillment, items, itemDoesNotExists, itemquantity, itemReceiptIds, requestBody.memo, requestBody)
                                                    for (var key in itemquantity) {
                                                        if (Number(itemquantity[key]) > 0) {
                                                            reason.push(itemquantity[key] + " '" + key + "'")
                                                        }
                                                    }

                                                    if (!reason.length)
                                                        successJson = { type: "success", name: "ITEM_RECEIPT_CREATED_SUCCESSFULLY", reason: "The item receipts are created successfully." }
                                                }
                                            } else {
                                                log.debug("items out", orderSearchObj.fulfillments)
                                                if (!error) {
                                                    createItemReceiptWithNoSpecifiedItem(requestBody.itemfulfillment, orderId, itemReceiptIds, requestBody.memo)


                                                    if (!reason.length)
                                                        successJson = { type: "success", name: "ITEM_RECEIPT_CREATED_SUCCESSFULLY", reason: "The item receipts are created successfully for all the item fulfillemnt available in the order." }
                                                }
                                            }
                                        } else {
                                            error = true;
                                            errorJson = { type: "error", name: "ITEM_FULFILLMENT_DOES_NOT_EXIST", reason: "The requested item fulfillment does not exist in the transfer order." }
                                        }
                                    } else {
                                        error = true;
                                        errorJson = { type: "error", name: "ITEM_FULFILLMENT_DOES_NOT_EXIST", reason: "The requested item fulfillment does not exist in the transfer order." }
                                    }


                                } else {
                                    log.debug('orderSearchObj.fulfillments in')
                                    if (items && items.length) {
                                        log.debug("items in")
                                        fulfillments = itemLineIteration(items, itemDoesNotExists, orderSearchObj.fulfillments, fulfillments)

                                        log.debug('fulfillemnts', fulfillments)
                                        if (!error) {
                                            groupedFulfillment = groupBasedOnItems(fulfillments, "fulfillment");


                                            log.debug('groupedFulfillment', groupedFulfillment)

                                            for (var key in groupedFulfillment) {
                                                var returnedVal = createItemReceiptFromTO(orderId, key, items, itemDoesNotExists, itemquantity, itemReceiptIds, requestBody.memo, requestBody)
                                                if (returnedVal)
                                                    break;
                                            }
                                            for (var key in itemquantity) {
                                                if (Number(itemquantity[key]) > 0) {
                                                    reason.push(itemquantity[key] + " '" + key + "'")
                                                }
                                            }

                                            if (!reason.length)
                                                successJson = { type: "success", name: "ITEM_RECEIPT_CREATED_SUCCESSFULLY", reason: "The item receipts are created successfully." }
                                        }
                                    } else {
                                        log.debug("items out", orderSearchObj.fulfillments)
                                        if (!error) {
                                            groupedFulfillment = groupBasedOnItems(orderSearchObj.fulfillments, "fulfillment");
                                            log.debug('groupedFulfillment', groupedFulfillment)
                                            for (var key in groupedFulfillment) {
                                                var returnedVal = createItemReceiptWithNoSpecifiedItem(key, orderId, itemReceiptIds, requestBody.memo)
                                                if (returnedVal)
                                                    break;
                                            }
                                            if (!reason.length)
                                                successJson = { type: "success", name: "ITEM_RECEIPT_CREATED_SUCCESSFULLY", reason: "The item receipts are created successfully for all the item fulfillemnt available in the order." }
                                        }
                                    }
                                }
                            } else {
                                error = true;
                                errorJson = { type: "error", name: "ITEMS_ARE_NOT_FULFILLED", reason: "The items needed to be fulfilled or the requested items does not exists in the requested order." }
                            }

                        } else {
                            error = true;
                            errorJson = { type: "error", name: "ORDER_NOT_IN_PROPER_STATUS", reason: "The order is not in a status to create item receipt. Please provide a valid order id." }
                        }
                    } else {
                        error = true;
                        errorJson = { type: "error", name: "ORDER_DOES_NOT_EXIST", reason: "The order does not exists. Please provide a valid order id." }
                    }
                } else {
                    error = true;
                    errorJson = { type: "error", name: "ORDER_ID_IS_MISSING", reason: "The order id is missing in the Request." }
                }
                return itemReceiptIds;
            } catch (e) {
                log.error("error@2", e)
                error = true;
                errorJson = { type: "error", name: e.name, reason: e.message }
            }
        }

        /**
         * Creating item receipt when items are not specified
         * @param {Number} fulfillmentId - The fullfillement internal id
         * @param {Number} orderId - The order internal Id
         * @param {String} memo The memo needed to be added in the item receipt
         */
        function createItemReceiptWithNoSpecifiedItem(fulfillmentId, orderId, itemReceiptIds, memo) {
            try {
                //transforming the Transfer order to item receipt
                try {
                    var itemRecieptRec = record.transform({
                        fromType: 'transferorder',
                        fromId: orderId,
                        toType: 'itemreceipt',
                        isDynamic: true,
                        defaultValues: {
                            itemfulfillment: fulfillmentId
                        }
                    });
                } catch (e) {
                    if (e.name = 'INVALID_INITIALIZE_REF') {
                        return true;
                    }
                }

                //item line count of item receipt
                var itemlineCount = itemRecieptRec.getLineCount({
                    sublistId: 'item'
                });
                if (itemlineCount) {

                    //expense line count of item receipt
                    var explineCount = itemRecieptRec.getLineCount({
                        sublistId: 'expense'
                    });

                    //unmarking receive check boxes on each expense line if it exists

                    if (explineCount)
                        for (var index = 0; index < explineCount; index++) {

                            itemRecieptRec = itemRecieptRec.selectLine({
                                sublistId: 'expense',
                                line: index
                            });
                            itemRecieptRec.setCurrentSublistValue({
                                sublistId: 'expense',
                                fieldId: 'itemreceive',
                                value: false,
                                // ignoreFieldChange: true
                            });
                            itemRecieptRec.commitLine({
                                sublistId: 'expense'
                            });

                        }
                    //set memo
                    if (memo)
                        itemRecieptRec.setValue({ fieldId: 'memo', value: memo })
                    var recordId = itemRecieptRec.save({
                        enableSourcing: true,
                        ignoreMandatoryFields: true
                    });
                    log.debug('recordId', recordId)
                    if (recordId)
                        receivedFulfillments[recordId] = fulfillmentId;
                    itemReceiptIds.push(recordId);
                } else {
                    error = true;
                    errorJson = { type: "error", name: "ITEM_FULFILLMENT_IS_ALREADY_RECEIVED", reason: "The requested item fulfillment is fully received." }
                }
                return false;
            } catch (e) {
                log.debug("error@createItemReceiptWithNoSpecifiedItem", e)
            }
        }
        /**
         * iterate through request item array to create itemquantity object and to find the requested itemlines and the array of items that does not exists.
         * @param {Arrya[Objects]} items request items
         * @param {Array} itemDoesNotExists 
         * @param {Array[Objects]} itemlines 
         * @param {Array[Objects]} fulfillments 
         */
        function itemLineIteration(items, itemDoesNotExists, itemlines, fulfillments) {
            try {
                for (var i = 0; i < items.length; i++) {

                    if (items[i].hasOwnProperty("itemid") && items[i].hasOwnProperty("quantity")) {

                        //getting the item lines related to the requested items.
                        var lines = itemlines.filter(function (item) {
                            return item.item == items[i].itemid;
                        });

                        //creating an object containing key as the item name and value as the quantity of the item needed to be created for item receipt.
                        if (itemquantity[items[i].itemid])
                            itemquantity[items[i].itemid] = itemquantity[items[i].itemid] + items[i].quantity;
                        else
                            itemquantity[items[i].itemid] = items[i].quantity;

                        log.debug('lines', lines)
                        if (lines && lines.length) {
                            log.debug("enter condition")

                            //making the all related item fulfillment as one array.
                            fulfillments = fulfillments.concat(lines);
                        } else {
                            itemDoesNotExists.push(items[i].itemid)
                        }
                    } else {
                        error = true;
                        errorJson = { type: "error", name: "INVALID_REQUEST_BODY", reason: "The request body is not in valid format, missing parameter 'itemid'/'quantity' or both." };
                        break;
                    }
                }
                log.debug('itemLineIteration -fulfillments ', fulfillments)
                log.debug('itemDoesNotExists', itemDoesNotExists)

                log.debug('itemquantity', itemquantity)
                if (itemDoesNotExists.length == items.length) {
                    error = true;
                    errorJson = { type: 'error', name: 'ITEM_DOES_NOT_EXIST', reason: 'The requested item/items does not exists in the Transfer order or available for creating item receipt.' }
                }
                return fulfillments;
            } catch (e) {
                log.debug("error@itemLineIteration", e)
            }
        }

        /**
         * Creating item receipt when items and its quantity specified in the request
         * @param {Number} orderId - order internal id
         * @param {Number} fulfillmentId - internal id of item fulfillment
         * @param {Array[Objects]} items - requested item array
         * @param {Array} itemDoesNotExists - the items doesnot exists in the order
         * @param {Object} itemquantity -the requested item and its quantity as an object. the quantity will reduce when the item receieved.
         * @param {Array} itemReceiptIds - the created item receipt internla id array
         * @param {String} memo - The memo needed to be added in the item receipt
         */
        function createItemReceiptFromTO(orderId, fulfillmentId, items, itemDoesNotExists, itemquantity, itemReceiptIds, memo, requestBody) {
            try {
                var selectedLines = []; var itemAlreadyReceived = [];
                log.debug('fulfillmentId', fulfillmentId)
                log.debug('createItemReceiptFromTO-itemDoesNotExists', itemDoesNotExists)
                //transforming the Transfer order to item receipt
                try {
                    var itemRecieptRec = record.transform({
                        fromType: 'transferorder',
                        fromId: orderId,
                        toType: 'itemreceipt',
                        isDynamic: true,
                        defaultValues: {
                            itemfulfillment: fulfillmentId
                        }
                    });
                } catch (e) {
                    if (e.name = 'INVALID_INITIALIZE_REF') {
                        return true;
                    }
                }
                //item line count of item receipt
                var itemlineCount = itemRecieptRec.getLineCount({
                    sublistId: 'item'
                });

                //expense line count of item receipt
                var explineCount = itemRecieptRec.getLineCount({
                    sublistId: 'expense'
                });

                //unmarking receive check boxes on each  expense line if it exists

                if (explineCount)
                    for (var index = 0; index < explineCount; index++) {

                        itemRecieptRec = itemRecieptRec.selectLine({
                            sublistId: 'expense',
                            line: index
                        });
                        itemRecieptRec.setCurrentSublistValue({
                            sublistId: 'expense',
                            fieldId: 'itemreceive',
                            value: false,
                            // ignoreFieldChange: true
                        });
                        itemRecieptRec.commitLine({
                            sublistId: 'expense'
                        });

                    }

                //creating the array of objects from item lines of item receipt
                var itemLines = getSublist(itemRecieptRec, 'item').reduce(function (a, v, idx) {
                    a.push({
                        item: v.item,
                        itemtype: v.itemtype,
                        itemname: v.itemname,
                        quantity: v.quantity,
                        itemreceive: v.itemreceive,
                        location: v.location,
                        line: v.line,
                        orderline: v.orderline,
                        index: idx
                    });
                    return a;
                }, [])
                log.debug('itemLines', itemLines)
                if (itemLines && itemLines.length) {

                    for (var i = 0; i < Object.keys(itemquantity).length; i++) {

                        //filter the item lines of specific item from the array of item lines
                        var lines = itemLines.filter(function (item) {
                            return item.item.value == Object.keys(itemquantity)[i];
                        });
                        log.debug('lines', lines)

                        //if lines exists
                        if (lines && lines.length) {
                            //recieve the items
                            var result = setItemLines(itemRecieptRec, lines, Object.keys(itemquantity)[i], 'transfer', itemquantity, itemDoesNotExists)
                            log.debug('result', result)
                            selectedLines = selectedLines.concat(result.selectedLines);

                        } else {
                            itemAlreadyReceived.push(Object.keys(itemquantity)[i])
                        }
                    }

                    //if no items
                    if (itemAlreadyReceived.length == Object.keys(itemquantity).length) {
                        // error = true;
                        errorJson = { type: 'error', name: 'ITEM_DOES_NOT_EXIST', reason: 'The requested item/items does not exists in the Item fulfillment or already received.' }
                    }

                    log.debug('selectedLines in main', selectedLines)
                    log.debug('itemquantity', itemquantity)

                    //remove unrequired lines

                    for (var index = 0; index < itemlineCount; index++) {

                        if (selectedLines.indexOf(index) == -1) {
                            itemRecieptRec.selectLine({
                                sublistId: 'item',
                                line: index
                            });
                            itemRecieptRec.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'itemreceive',
                                value: false,
                                // ignoreFieldChange: true
                            });
                            itemRecieptRec.commitLine({
                                sublistId: 'item'
                            });
                        }
                    }

                    var finalitemLines = getSublist(itemRecieptRec, 'item').reduce(function (a, v, idx) {
                        a.push({
                            item: v.item,
                            itemtype: v.itemtype,
                            itemname: v.itemname,
                            quantity: v.quantity,
                            itemreceive: v.itemreceive,
                            location: v.location,
                            line: v.line,
                            orderline: v.orderline,
                            index: idx
                        });
                        return a;
                    }, []);
                    log.debug('final ItemLines', finalitemLines)

                    //save the newly created item Receipt
                    if (selectedLines && selectedLines.length) {
                        //set memo
                        if (memo)
                            itemRecieptRec.setValue({ fieldId: 'memo', value: memo })
                        var recordId = itemRecieptRec.save({
                            enableSourcing: true,
                            ignoreMandatoryFields: true
                        });
                        log.debug('recordId', recordId)
                        if (recordId)
                            receivedFulfillments[recordId] = fulfillmentId;
                        itemReceiptIds.push(recordId);
                    } else {
                        // error = true;
                        errorJson = { type: 'error', name: 'ITEM_DOES_NOT_EXIST', reason: 'The requested item/items does not exists in the Transfer order or already received.' }
                    }
                } else if (requestBody.itemfulfillment) {
                    // error = true;
                    errorJson = { type: 'error', name: 'ITEM_DOES_NOT_EXIST', reason: 'The requested item/items does not exists in the Item fulfillment or already received.' }
                } else {
                    errorJson = { type: 'error', name: 'ITEM_DOES_NOT_EXIST', reason: 'The requested item/items does not exists in the Transfer order or already received.' }
                }
                return false;
            } catch (e) {
                log.debug("error@createItemReceiptFromTO", e)
            }
        }

        /*******************************************************************************
         * This function is used to group result data
         *******************************************************************************/
        function groupBasedOnItems(searchResult, key) {
            try {
                "use strict";

                log.debug('in grouping', searchResult)
                function groupBy(objectArray, property) {
                    return objectArray.reduce(function (acc, obj) {
                        var key = obj[property];

                        if (!acc[key]) {
                            acc[key] = [];
                        } // Add object to list for given key's value


                        acc[key].push(obj);
                        return acc;
                    }, {});
                }

                var groupedPeople = groupBy(searchResult, key);
                //console.log(groupedPeople);
                // log.debug("groupedPeople",groupedPeople)




                return groupedPeople;
            } catch (error) {
                log.debug("Err@groupBasedOnItems", error)
                log.debug("Err@groupBasedOnItems", error)

            }
        }

        /**
         * Transfer order search to get the internal id and the item fulfillemtns in the transfer order
         * @param {String} tranId 
         * @returns {Object}
         */
        function getTransferOrderDetails(orderId) {
            var id, status;
            var fulfillments = [];

            var transferorderSearchObj = search.create({
                type: "transferorder",
                filters:
                    [
                        ["type", "anyof", "TrnfrOrd"],
                        "AND",
                        ["mainline", "is", "F"],
                        "AND",
                        ["internalid", "anyof", orderId],
                        "AND",
                        ["applyingtransaction.type", "anyof", "ItemShip"],
                        "AND",
                        ["applyingtransaction.status", "anyof", "ItemShip:C"]
                    ],
                columns:
                    [
                        search.createColumn({
                            name: "internalid",
                            summary: "GROUP",
                            sort: search.Sort.ASC,
                            label: "Internal ID"
                        }),
                        search.createColumn({
                            name: "tranid",
                            summary: "GROUP",
                            label: "Document Number"
                        }),
                        search.createColumn({
                            name: "formulatext",
                            summary: "GROUP",
                            formula: "{item.itemid}",
                            label: "Item Name"
                        }),
                        search.createColumn({
                            name: "item",
                            summary: "GROUP",
                            sort: search.Sort.ASC,
                            label: "Item"
                        }),
                        search.createColumn({
                            name: "quantity",
                            summary: "GROUP",
                            function: "absoluteValue",
                            label: "Quantity"
                        }),
                        search.createColumn({
                            name: "applyingtransaction",
                            summary: "GROUP",
                            label: "Applying Transaction"
                        }),
                        search.createColumn({
                            name: "quantityshiprecv",
                            summary: "GROUP",
                            sort: search.Sort.DESC,
                            label: "Quantity Fulfilled/Received"
                        }),
                        search.createColumn({
                            name: "statusref",
                            summary: "GROUP",
                            label: "Status"
                        })
                    ]
            });
            var searchResultCount = transferorderSearchObj.runPaged().count;
            log.debug("transferorderSearchObj result count", searchResultCount);
            transferorderSearchObj.run().each(function (result) {
                // .run().each has a limit of 4,000 results
                id = result.getValue({
                    name: "internalid",
                    summary: "GROUP",
                    sort: search.Sort.ASC,
                    label: "Internal ID"
                });
                status = result.getText({
                    name: "statusref",
                    summary: "GROUP",
                    label: "Status"
                })
                var qtyRecieved = result.getValue({
                    name: "quantityshiprecv",
                    summary: "GROUP",
                    sort: search.Sort.DESC,
                    label: "Quantity Fulfilled/Received"
                })
                var fulfillment = result.getValue({
                    name: "applyingtransaction",
                    summary: "GROUP",
                    label: "Applying Transaction"
                });
                var qty = result.getValue({
                    name: "quantity",
                    summary: "GROUP",
                    function: "absoluteValue",
                    label: "Quantity"
                });
                var item = result.getValue({
                    name: "item",
                    summary: "GROUP",
                    sort: search.Sort.ASC,
                    label: "Item"
                });
                var itemName = result.getValue({
                    name: "formulatext",
                    summary: "GROUP",
                    formula: "{item.itemid}",
                    label: "Item Name"
                });
                if (qtyRecieved) {
                    fulfillments.push({
                        item: item,
                        itemName: itemName,
                        qty: qty,
                        fulfillment: fulfillment,
                        qtyRecieved: qtyRecieved
                    })
                }
                return true;
            });
            log.debug('fulfillements in search', fulfillments)
            return { id: id, status: status, fulfillments: fulfillments }
        }

        /**
         * Purchase order search to get the internal id
         * @param {String} tranId -purchase order docuemtn number
         * @returns {Object}
         */
        function getPurchaseOrderId(orderId) {
            var id, status;
            var purchaseorderSearchObj = search.create({
                type: "purchaseorder",
                filters:
                    [
                        ["type", "anyof", "PurchOrd"],
                        "AND",
                        ["mainline", "is", "F"],
                        "AND",
                        ["internalid", "anyof", orderId]
                    ],
                columns:
                    [
                        search.createColumn({ name: "internalid", label: "Internal ID" }),
                        search.createColumn({ name: "tranid", label: "Document Number" }),
                        search.createColumn({ name: "item", label: "Item" }),
                        search.createColumn({ name: "quantity", label: "Quantity" }),
                        search.createColumn({ name: "statusref", label: "Status" })
                    ]
            });
            var searchResultCount = purchaseorderSearchObj.runPaged().count;
            log.debug("purchaseorderSearchObj result count", searchResultCount);
            purchaseorderSearchObj.run().each(function (result) {
                // .run().each has a limit of 4,000 results
                id = result.getValue({ name: "internalid", label: "Internal ID" })
                status = result.getText({ name: "statusref", label: "Status" })
                // return true;
            });
            return { id: id, status: status }
        }

        /**
          * Get Sublist fields and their values
          * 
          * @param recordObj {Object} Initialised Object reference to record
          * @param sublistId {String} sublistId on the Object
          * @return {Array[Object]} 
          */
        function getSublist(recordObj, sublistId) {

            var result = [];
            var sublistFields = recordObj.getSublistFields(sublistId);
            var lineCount = recordObj.getLineCount({
                sublistId: sublistId
            });
            for (var line = 0; line < lineCount; line++) {
                result.push(
                    sublistFields.reduce(function (a, c) {
                        try {
                            a[c] = {
                                value: recordObj.getSublistValue({
                                    sublistId: sublistId,
                                    fieldId: c,
                                    line: line
                                }),
                                text: recordObj.getSublistText({
                                    sublistId: sublistId,
                                    fieldId: c,
                                    line: line
                                })
                            };
                            return a;
                        } catch (er) { }
                        return a;
                    }, {})
                );
            }
            return result;
        }

        /**
         * Set the item lines of the item receipt based on the requested item and quantity
         * @param {Rcord Object} itemRecieptRec - item receipt rcord Object
         * @param {Arrey[Objects]} lines - item receipt lines related to  a specific item
         * @param {Object} item - An item and its quantity from the request
         * @param {String} requestType - Order type of the request
         * @param {Object} itemquantity - request item and quantity pair object
         */
        function setItemLines(itemRecieptRec, lines, itemid, requestType, itemquantity, itemDoesNotExists) {

            var itemQty = itemquantity[itemid];

            var selectedLines = [];
            if ((requestType == 'transfer' && itemDoesNotExists.indexOf(itemid) == -1) || requestType == 'purchase') {
                //sort the sublist lines in the transfromed item receipt in the index number
                lines.sort(function (a, b) { return b.index - a.index });

                for (var i = 0; i < lines.length; i++) {

                    if (itemQty <= 0)
                        break;
                    var q = itemRecieptRec.getSublistValue({ sublistId: 'item', fieldId: 'quantity', line: lines[i].index })
                    log.debug('q', q)
                    log.debug('itemQty', itemQty)
                    if (q >= itemQty) {
                        if (itemQty <= 0)
                            break;
                        selectedLines.push(lines[i].index);
                        log.debug("test1")
                        itemRecieptRec = itemRecieptRec.selectLine({
                            sublistId: 'item',
                            line: lines[i].index
                        });
                        itemRecieptRec.setCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'itemreceive',
                            value: true,
                            ignoreFieldChange: true
                        });
                        itemRecieptRec.setCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'quantity',
                            value: itemQty,
                            ignoreFieldChange: true
                        });
                        itemRecieptRec.commitLine({
                            sublistId: 'item'
                        });
                        itemQty = 0;
                        break;
                    } else {
                        if (itemQty <= 0)
                            break;
                        selectedLines.push(lines[i].index);
                        log.debug("test2")

                        itemRecieptRec.selectLine({
                            sublistId: 'item',
                            line: lines[i].index
                        });

                        itemRecieptRec.setCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'itemreceive',
                            value: true,
                            ignoreFieldChange: true
                        });
                        itemRecieptRec.setCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'quantity',
                            value: q,
                            ignoreFieldChange: true
                        });
                        itemRecieptRec.commitLine({
                            sublistId: 'item'
                        });
                        itemQty = itemQty - q;

                    }
                }

                itemquantity[itemid] = itemQty;
            }
            log.debug('selectedLines', selectedLines)
            log.debug('itemquantity', itemquantity)

            return {
                selectedLines: selectedLines
            }
        }

        /**
         * Processing the request response
         * @param {Array} itemReceiptIds 
         * @returns {Object}
         */
        function processResponse(itemReceiptIds, requestBody) {
            var type = requestBody.type
            var response;
            var resonString = '';

            log.debug('reason', reason)
            //if error exists
            if (itemReceiptIds && itemReceiptIds.length) {
                var itemReceipts = getItemReceiptId(itemReceiptIds, receivedFulfillments, type);
                if (reason && reason.length) {
                    if (reason.length > 1) {
                        for (var i = 0; i < reason.length; i++) {
                            if (i == reason.length - 1) {
                                reason[i] = 'and ' + reason[i];
                            } else {
                                reason[i] = reason[i] + ", ";
                            }
                        }
                        reason.push(" are not able to receive.")
                        resonString = reason.join("")
                        log.debug('resonString', resonString)
                    } else {
                        reason.push(" is not able to receive.")
                        resonString = reason.join("")
                        log.debug('resonString', resonString)
                    }
                    if (error) {
                        response = {
                            status: 'PARTIAL_SUCCESS',
                            code: errorJson.name,
                            reason: errorJson.reason + " " + resonString,
                            data: itemReceipts.length ? itemReceipts : []
                        }

                    } else {
                        if (type == 'purchaseorder') {
                            var reasoninobj = 'The requested item quantity exceeds the total quantity available in the Purchase order or the item does not exist in the order.'
                        } else {
                            var reasoninobj = 'The requested item quantity exceeds the total fulfilled quantity available in the Transfer order or the item does not exist in the order. '
                        }
                        response = {
                            status: 'PARTIAL_SUCCESS',
                            code: 'ITEM_QUANTITY_EXCEEDED',
                            reason: reasoninobj + resonString,
                            itemReceipts: itemReceipts.length ? itemReceipts : []
                        }

                    }
                } else if (successJson.type && successJson.type == 'success') {

                    response = {
                        status: 'SUCCESS',
                        code: successJson.name,
                        reason: successJson.reason,
                        itemReceipts: itemReceipts.length ? itemReceipts : []
                    }

                } else {
                    response = {
                        status: 'PARTIAL_SUCCESS',
                        code: errorJson.name ? errorJson.name : "ERROR",
                        reason: errorJson.reason ? errorJson.reason : 'The item receipt creation is partially successful',
                        data: itemReceipts
                    }

                }
            } else {
                if (error) {
                    response = {
                        status: 'FAILURE',
                        code: errorJson.name,
                        reason: errorJson.reason,
                        data: []
                    }
                } else {
                    response = {
                        status: 'FAILURE',
                        code: errorJson.name ? errorJson.name : "ERROR",
                        reason: errorJson.reason ? errorJson.reason : 'Failed to create item receipt',
                        data: []
                    }
                }
            }

            return response
        }


        /**
         * search to find the dcuement number of item receipt
         * @param {Array} itemReceiptIds - item receipt ids
         * @returns {Array[Objects]} documentNumbers 
         */
        function getItemReceiptId(itemReceiptIds, receivedFulfillments, type) {
            var documentNumbers = []
            var itemreceiptSearchObj = search.create({
                type: "itemreceipt",
                filters:
                    [
                        ["type", "anyof", "ItemRcpt"],
                        "AND",
                        ["mainline", "is", "T"],
                        "AND",
                        ["internalid", "anyof", itemReceiptIds]
                    ],
                columns:
                    [
                        search.createColumn({ name: "tranid", label: "Document Number" }),
                        search.createColumn({ name: "internalid", label: "Internal ID" }),
                    ]
            });
            var searchResultCount = itemreceiptSearchObj.runPaged().count;
            log.debug("itemreceiptSearchObj result count", searchResultCount);
            itemreceiptSearchObj.run().each(function (result) {
                // .run().each has a limit of 4,000 results
                var tranId = result.getValue({ name: "tranid", label: "Document Number" });
                var id = result.getValue({ name: "internalid", label: "Internal ID" })
                if (type == 'transferorder')
                    documentNumbers.push({
                        internalid: id,
                        documentNo: tranId,
                        fulfillmentid: receivedFulfillments ? receivedFulfillments[id] : ''
                    })
                else if (type == 'purchaseorder')
                    documentNumbers.push({
                        internalid: id,
                        documentNo: tranId
                    })

                return true;
            });
            return documentNumbers;
        }
        return {
            post: post
        }
    });

Leave a comment

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