Requirement:
Create item receipt automatically for transfer orders having item lines with quantity fulfilled greater than quantity received.
Solution:
/**
* @NApiVersion 2.1
* @NScriptType MapReduceScript
*/
/************************************************************************************************
** Swyft Inc | Create Item Receipt For Transfer Order**
* **********************************************************************************************
*
* Author: Jobin & Jismi IT Services LLP
*
* Date Created: 29-December-2022
*
* Created By: Lakshmi priya Suresh, Jobin & Jismi IT Services LLP
*
* Description: Create Item Receipt For Transfer Order.
*
* REVISION HISTORY
***********************************************************************************************/
define(['N/email', 'N/error', 'N/file', 'N/format', 'N/record', 'N/search'],
/**
* @param{email} email
* @param{error} error
* @param{file} file
* @param{format} format
* @param{record} record
* @param{search} search
*/
(email, error, file, format, record, search) => {
var TransferOrdID;
var main = {
getInputData: function (inputContext) {
log.debug("debug", "*** START ***")
//get the transfer orders
var transferOrders = main.fetchTransferOrders()
return transferOrders;
},
reduce: function (reduceContext) {
log.debug("reduce", JSON.parse(reduceContext.values))
var dataObj = JSON.parse(reduceContext.values).values
var transOrdID = dataObj["GROUP(internalid)"].value
var transDoc = dataObj["GROUP(tranid)"]
TransferOrdID = transDoc;
var status = dataObj["GROUP(statusref)"].text
var ifList = main.getToBeReceivedIFs(transOrdID)
log.debug("ifList", ifList)
//transform the TO record to IR **Partially Fulfilled**
var tranformTO = main.transformToIR(dataObj, transOrdID, status, ifList)
},
summarize: function (summaryContext) {
//send email if the error file has content
log.debug("**********summary*********")
var fileCreate = main.getFileFromFolder()
if (checkForParameter(fileCreate)) {
var attachment = file.load({id: fileCreate});
//send email
email.send({
author: 53163, //Able
recipients: 47004, //Sukanya
subject: 'Error in Converting Transfer Order to Item Receipt',
body: 'Hi, <br><br> There has been some error/s occurred in receiving transfer orders.<br>Please find the attached document.<br><br>Thank You',
attachments: [attachment],
});
//move the CSV file to another folder once the email is sent
var copyErrorFile = file.load({id: fileCreate});
copyErrorFile.folder = 95747
copyErrorFile.name = "Error in TO Conversion_"+new Date()
copyErrorFile.save()
}
},
fetchTransferOrders: function () {
var transferorderSearchObj = search.create({
type: "transferorder",
filters:
[
["type", "anyof", "TrnfrOrd"],
"AND",
["mainline", "is", "F"],
"AND",
["cogs", "is", "F"],
"AND",
["shipping", "is", "F"],
"AND",
["taxline", "is", "F"],
"AND",
["location","anyof","6889","99","5399"],
"AND",
["status", "anyof", "TrnfrOrd:D", "TrnfrOrd:F", "TrnfrOrd:E"],
"AND",
["internalid", "anyof","973770" ], //"429980","466549"
"AND",
["sum(formulanumeric: SUM(Case When {applyingtransaction.type}='Item Fulfillment' AND {applyingtransaction.status}='Shipped' Then {applyingtransaction.quantity} Else 0 End)-SUM(Case When {applyingtransaction.type}='Item Receipt' Then {applyingtransaction.quantity} Else 0 End))", "greaterthan", "0"]
],
columns:
[
search.createColumn({
name: "formulanumeric",
summary: "SUM",
formula: "Case When {applyingtransaction.type}='Item Fulfillment' AND {applyingtransaction.status}='Shipped' Then {applyingtransaction.quantity} Else 0 End",
label: "Fulfilled Quantity"
}),
search.createColumn({
name: "formulanumeric",
summary: "SUM",
formula: "Case When {applyingtransaction.type}='Item Receipt' Then {applyingtransaction.quantity} Else 0 End",
label: "Received Quantity"
}),
search.createColumn({
name: "formulanumeric",
summary: "SUM",
formula: "SUM(Case When {applyingtransaction.type}='Item Fulfillment' AND {applyingtransaction.status}='Shipped' Then {applyingtransaction.quantity} Else 0 End)-SUM(Case When {applyingtransaction.type}='Item Receipt' Then {applyingtransaction.quantity} Else 0 End)",
label: "Remaining Quantity"
}),
search.createColumn({
name: "internalid",
summary: "GROUP",
label: "Internal ID"
}),
search.createColumn({
name: "statusref",
summary: "GROUP",
label: "Status"
}),
search.createColumn({
name: "tranid",
summary: "GROUP",
label: "Document Number"
})
]
});
var searchResultCount = transferorderSearchObj.runPaged().count;
log.debug("transferorderSearchObj result count", searchResultCount);
return transferorderSearchObj;
},
transformToIR: function (dataObj, transOrdID, status, ifList) {
for (var i=0; i<ifList.length; i++){
var objRecord = record.transform({
fromType: record.Type.TRANSFER_ORDER,
fromId: transOrdID,
toType: record.Type.ITEM_RECEIPT,
isDynamic: true,
defaultValues: {'itemfulfillment': ifList[i]}
});
log.debug('obj record', objRecord)
var line = objRecord.getLineCount({sublistId: 'item'})
if (line == 0)
continue
objRecord.save({ignoreMandatoryFields: true, enableSourcing: true})
}
status = search.lookupFields({
type: search.Type.TRANSFER_ORDER,
id: transOrdID,
columns: ['status']
}).status;
status = status[0].text
},
getToBeReceivedIFs: function (transOrdID){
var transferorderSearchObj = search.create({
type: "transferorder",
filters:
[
["type","anyof","TrnfrOrd"],
"AND",
["mainline","is","F"],
"AND",
["shipping","is","F"],
"AND",
["taxline","is","F"],
"AND",
["cogs","is","F"],
"AND",
["applyingtransaction.type","anyof","ItemShip"],
"AND",
["applyingtransaction.status","anyof","ItemShip:C"],
"AND",
["internalid","anyof",transOrdID]
],
columns:
[
search.createColumn({
name: "internalid",
join: "applyingTransaction",
summary: "GROUP",
sort: search.Sort.ASC,
label: "Internal ID"
})
]
});
var searchResultCount = transferorderSearchObj.runPaged().count;
log.debug("transferorderSearchObj result count",searchResultCount);
var returnArr = []
transferorderSearchObj.run().each(function(result){
returnArr.push(result.getValue({
name: "internalid",
join: "applyingTransaction",
summary: "GROUP",
sort: search.Sort.ASC,
label: "Internal ID"
}))
return true;
});
return returnArr;
},
getFileFromFolder: function (){
var folderSearchObj = search.create({
type: "folder",
filters:
[
["internalid","anyof","95746"]
],
columns:
[
search.createColumn({name: "numfiles", label: "# of Files"}),
search.createColumn({
name: "internalid",
join: "file",
label: "Internal ID"
})
]
});
var searchResultCount = folderSearchObj.runPaged().count;
log.debug("folderSearchObj result count",searchResultCount);
var fileNo, fileID;
folderSearchObj.run().each(function(result){
fileNo = result.getValue({name: "numfiles", label: "# of Files"})
if (fileNo>0)
fileID = result.getValue({
name: "internalid",
join: "file",
label: "Internal ID"
})
return false;
});
return fileID
}
}
for (var key in main) {
if (typeof main[key] === 'function') {
main[key] = trycatch(main[key], key);
}
}
function trycatch(myfunction, key) {
return function () {
try {
return myfunction.apply(this, arguments);
} catch (e) {
log.debug("e in " + key, e);
//create error file and send to client
createAndSendErrorFile(e.message, TransferOrdID)
}
}
}
/**
* Function for creating error file and sending email to client
* @param error
* @param recordId
*/
function createAndSendErrorFile(error, recordId){
var errorFile, fileContent, csvContent=""
csvContent += recordId + ',' + error + ',';
csvContent += '\r\n';
//check if an error file is already created
var fileID = main.getFileFromFolder()
if (checkForParameter(fileID)) {
errorFile = file.load({id: fileID});
fileContent = errorFile.getContents()
fileContent += csvContent + '\r\n'
log.debug("csvContent", fileContent)
}else{
//create file for storing errors
var titleArray = ["Transfer Order", "Error"];
fileContent = titleArray.toString() + '\r\n';
fileContent += csvContent + '\r\n';
//fileContent += '\r\n';
}
var fileObj = file.create({
name: 'Error in TO Conversion',
fileType: file.Type.CSV,
contents: fileContent,
encoding: file.Encoding.UTF8,
folder: 95746,
isOnline: true
})
var fileCreate = fileObj.save()
}
function checkForParameter(parameter) {
if (parameter != "" && parameter != null && parameter != undefined && parameter != "undefined" && parameter != " " && parameter != false) {
return true;
} else {
return false;
}
}
return main;
});