Skip to content

Commit

Permalink
Added: support to export inventory adjustment from NS to OMS. (160-sy…
Browse files Browse the repository at this point in the history
…nc-inventory-adjustment-from-ns-to-oms) (#161)
  • Loading branch information
rehan3586 authored Oct 14, 2024
1 parent f02aa39 commit b44ce84
Show file tree
Hide file tree
Showing 6 changed files with 387 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
/**
* @NApiVersion 2.1
* @NScriptType MapReduceScript
*/
define(['N/file', 'N/record', 'N/search', 'N/sftp', 'N/error', 'N/task'],
(file, record, search, sftp, error, task) => {
const internalIdList = new Set([]);

const checkInternalId = (internalid) => {
if (internalIdList.has(internalid)) {
return false;
} else {
internalIdList.add(internalid);
return true;
}
}

const getInputData = (inputContext) => {
var inventoryAdjustmentSearch = search.load({ id: 'customsearch_hc_exp_inventory_adjustment' });
return inventoryAdjustmentSearch;
}

const map = (mapContext) => {
var contextValues = JSON.parse(mapContext.value);

var internalid = contextValues.values.internalid.value;
var productSku = contextValues.values.item.value;
var lineId = contextValues.values.line;
var quantity = contextValues.values.quantity;
var locationInternalId = contextValues.values.location.value;
var comments = "Inventory Adjusted from Inventory Adjustment Transaction # " + internalid + " in NetSuite ";

if (internalid) {
var checkId = checkInternalId(internalid);
if (checkId) {
var id = record.submitFields({
type: record.Type.INVENTORY_ADJUSTMENT,
id: internalid,
values: {
custbody_hc_inven_adjustment_exported: true
}
});
}
}

var inventoryDeltaData = {
'externalFacilityId': locationInternalId,
'idValue': productSku,
'idType': "NETSUITE_PRODUCT_ID",
'availableDelta': quantity,
'comments': comments
};

mapContext.write({
key: contextValues.id + '-' + lineId,
value: inventoryDeltaData
});
}

const reduce = (reduceContext) => {
var contextValues = JSON.parse(reduceContext.values);
var keyId = reduceContext.key;

var content = contextValues.externalFacilityId + ',' + contextValues.idValue + ',' + contextValues.idType + ',' + contextValues.availableDelta + ',' + contextValues.comments + '\n';
reduceContext.write(keyId, content);
}

const summarize = (summaryContext) => {
try {
var fileLines = 'externalFacilityId,idValue,idType,availableDelta,comments\n';
var totalRecordsExported = 0;

summaryContext.output.iterator().each(function(key, value) {
fileLines += value;
totalRecordsExported = totalRecordsExported + 1;
return true;
});
log.debug("====totalRecordsExported=="+totalRecordsExported);
if (totalRecordsExported > 0) {

var fileName = summaryContext.dateCreated + '-ExportInventoryAdjustment.csv';
var fileObj = file.create({
name: fileName,
fileType: file.Type.CSV,
contents: fileLines
});

//Get Custom Record Type SFTP details
var customRecordSFTPSearch = search.create({
type: 'customrecord_ns_sftp_configuration',
columns: [
'custrecord_ns_sftp_server',
'custrecord_ns_sftp_userid',
'custrecord_ns_sftp_port_no',
'custrecord_ns_sftp_host_key',
'custrecord_ns_sftp_guid',
'custrecord_ns_sftp_default_file_dir'
]

});
var sftpSearchResults = customRecordSFTPSearch.run().getRange({
start: 0,
end: 1
});

var sftpSearchResult = sftpSearchResults[0];

var sftpUrl = sftpSearchResult.getValue({
name: 'custrecord_ns_sftp_server'
});

var sftpUserName = sftpSearchResult.getValue({
name: 'custrecord_ns_sftp_userid'
});

var sftpPort = sftpSearchResult.getValue({
name: 'custrecord_ns_sftp_port_no'
});

var hostKey = sftpSearchResult.getValue({
name: 'custrecord_ns_sftp_host_key'
});

var sftpKeyId = sftpSearchResult.getValue({
name: 'custrecord_ns_sftp_guid'
});

var sftpDirectory = sftpSearchResult.getValue({
name: 'custrecord_ns_sftp_default_file_dir'
});

sftpDirectory = sftpDirectory + 'inventoryadjustment';
sftpPort = parseInt(sftpPort);

var connection = sftp.createConnection({
username: sftpUserName,
secret: sftpKeyId,
url: sftpUrl,
port: sftpPort,
directory: sftpDirectory,
hostKey: hostKey
});
log.debug("Connection established successfully with SFTP server!");

if (fileObj.size > connection.MAX_FILE_SIZE) {
throw error.create({
name:"FILE_IS_TOO_BIG",
message:"The file you are trying to upload is too big"
});
}
connection.upload({
directory: '/import/',
file: fileObj
});
log.debug("Inventory Adjustment File Uploaded Successfully to SFTP server with file" + fileName);
}
} catch (e) {
//Generate error csv
var errorFileLine = 'orderId,Recordtype\n';

summaryContext.output.iterator().each(function (key, value) {
var index = key.split('-')
var internalId = index[0]
var recordType = "INVENTORY_ADJUSTMENT"

var valueContents = internalId + ',' + recordType + '\n'
errorFileLine += valueContents;

return true;
});

var fileName = summaryContext.dateCreated + '-FailedInventoryTransferExport.csv';
var failExportCSV = file.create({
name: fileName,
fileType: file.Type.CSV,
contents: errorFileLine
});

// Check HotWax Export Fail Record CSV is created or not
var folderInternalId = search
.create({
type: search.Type.FOLDER,
filters: [['name', 'is', 'HotWax Export Fail Record CSV']],
columns: ['internalid']
})
.run()
.getRange({ start: 0, end: 1 })
.map(function (result) {
return result.getValue('internalid');
})[0];

// Made Export Fail Sales Order CSV folder in NetSuite File Cabinet
if (folderInternalId == null) {
var folder = record.create({ type: record.Type.FOLDER });
folder.setValue({
fieldId: 'name',
value: 'HotWax Export Fail Record CSV'
});

var folderInternalId = folder.save();
}

failExportCSV.folder = folderInternalId;
failExportCSV.save();

if (folderInternalId) {
var scriptTask = task.create({
taskType: task.TaskType.MAP_REDUCE,
});

scriptTask.scriptId = 'customscript_hc_mr_mark_false',
scriptTask.deploymentId = 'customdeploy_hc_mr_mark_false'
scriptTask.params = { "custscript_hc_mr_mark_false": folderInternalId }

var mapReduceTaskId = scriptTask.submit();
log.debug("Map/reduce task submitted!");
}

log.error({
title: 'Error in exporting and uploading inventory adjustment csv files',
details: e,
});
throw error.create({
name:"Error in exporting and uploading inventory adjustment csv files",
message: e
});
}
}
return {getInputData, map, reduce, summarize}
});
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ define(['N/sftp', 'N/record', 'N/error', 'N/search', 'N/file'], function (sftp,
for (var dataIndex = 0; dataIndex < returnAuthorizationDataList.length; dataIndex++) {
var orderId = returnAuthorizationDataList[dataIndex].order_id;
var posReturnTotal = returnAuthorizationDataList[dataIndex].pos_return_total;
var hcReturnId = returnAuthorizationDataList[dataIndex].hc_return_id;
var itemList = returnAuthorizationDataList[dataIndex].items;
var paymentlist = returnAuthorizationDataList[dataIndex].payment_list;
// exchange credit value contain giftcard amount.
Expand All @@ -113,6 +114,11 @@ define(['N/sftp', 'N/record', 'N/error', 'N/search', 'N/file'], function (sftp,
fieldId: 'orderstatus',
value: "B"
});

returnAuthorizationRecord.setValue({
fieldId: 'custbody_hc_pos_return_id',
value: hcReturnId
});

var lineCount = returnAuthorizationRecord.getLineCount({
sublistId: 'item'
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<transactionbodycustomfield scriptid="custbody_hc_inven_adjustment_exported">
<accesslevel>2</accesslevel>
<applyformatting>F</applyformatting>
<bodycustomerpayment>F</bodycustomerpayment>
<bodycustomtransactions></bodycustomtransactions>
<bodydeposit>F</bodydeposit>
<bodydepositapplication>F</bodydepositapplication>
<bodyexpensereport>F</bodyexpensereport>
<bodyinventoryadjustment>T</bodyinventoryadjustment>
<bodyitemfulfillment>F</bodyitemfulfillment>
<bodyitemfulfillmentorder>F</bodyitemfulfillmentorder>
<bodyitemreceipt>F</bodyitemreceipt>
<bodyitemreceiptorder>F</bodyitemreceiptorder>
<bodyjournal>F</bodyjournal>
<bodyothertransaction>F</bodyothertransaction>
<bodypickingticket>F</bodypickingticket>
<bodyprintflag>F</bodyprintflag>
<bodyprintpackingslip>F</bodyprintpackingslip>
<bodyprintstatement>F</bodyprintstatement>
<bodypurchase>F</bodypurchase>
<bodysale>F</bodysale>
<bodytransferorder>F</bodytransferorder>
<bodyvendorpayment>F</bodyvendorpayment>
<checkspelling>F</checkspelling>
<defaultchecked>F</defaultchecked>
<defaultselection></defaultselection>
<defaultvalue></defaultvalue>
<description></description>
<displayheight></displayheight>
<displaytype>NORMAL</displaytype>
<displaywidth></displaywidth>
<dynamicdefault></dynamicdefault>
<encryptatrest>F</encryptatrest>
<fieldtype>CHECKBOX</fieldtype>
<fldsizelabel></fldsizelabel>
<globalsearch>F</globalsearch>
<help></help>
<isformula>F</isformula>
<ismandatory>F</ismandatory>
<isparent>F</isparent>
<label>HC Inventory Adjustment Exported</label>
<linktext></linktext>
<maxlength></maxlength>
<maxvalue></maxvalue>
<minvalue></minvalue>
<onparentdelete></onparentdelete>
<parentsubtab></parentsubtab>
<searchcomparefield></searchcomparefield>
<searchdefault></searchdefault>
<searchlevel>2</searchlevel>
<selectrecordtype></selectrecordtype>
<showhierarchy>F</showhierarchy>
<showinlist>F</showinlist>
<sourcefilterby></sourcefilterby>
<sourcefrom></sourcefrom>
<sourcelist></sourcelist>
<storevalue>T</storevalue>
<subtab>[scriptid=custtab_hc_tab]</subtab>
</transactionbodycustomfield>
29 changes: 29 additions & 0 deletions src/Objects/InventoryAdjustment/customscript_exp_inventory_adj.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<mapreducescript scriptid="customscript_exp_inventory_adj">
<description></description>
<isinactive>F</isinactive>
<name>HC_MR_ExportedInventoryAdjustmentCSV</name>
<notifyadmins>F</notifyadmins>
<notifyemails></notifyemails>
<notifyowner>T</notifyowner>
<scriptfile>[/SuiteScripts/InventoryTransfer/HC_MR_ExportedInventoryAdjustmentCSV.js]</scriptfile>
<scriptdeployments>
<scriptdeployment scriptid="customdeploy_exp_inventory_adj">
<buffersize>1</buffersize>
<concurrencylimit>1</concurrencylimit>
<isdeployed>T</isdeployed>
<loglevel>DEBUG</loglevel>
<queueallstagesatonce>T</queueallstagesatonce>
<status>SCHEDULED</status>
<title>HC_MR_ExportedInventoryAdjustmentCSV</title>
<yieldaftermins>60</yieldaftermins>
<recurrence>
<daily>
<everyxdays>1</everyxdays>
<repeat>PT1H</repeat>
<startdate>2023-08-22</startdate>
<starttime>05:00:00Z</starttime>
</daily>
</recurrence>
</scriptdeployment>
</scriptdeployments>
</mapreducescript>
Loading

0 comments on commit b44ce84

Please sign in to comment.