Scenario
- When a Cash Sale/Invoice is generated for the Adobe Commerce order it will be synced to the Adobe Commerce website through a real time sync.
- The invoice/cash sale of the items that are in stock at the time of order placing will be considered for invoice in Adobe Commerce.
/**
* @NApiVersion 2.1
* @NScriptType UserEventScript
*/
/*******************************************************************************************************
* Szco Supplies, Inc
*
* SZCO-756 : NetSuite - Magento invoice Sync
*
* *****************************************************************************************************
*
* Author: Jobin and Jismi IT Services
*
* Date Created : 23-August-2023
*
*Description : This script is to implement an integration between NetSuite and Magento to sync the
invoice in NetSuite to Magento
*
* REVISION HISTORY
*
* @version 1.0 SZCO-755 : 23-August-2023 : Created the initial build by JJ0152
*
******************************************************************************************************/
define(['N/record', 'N/search', 'N/https', 'N/runtime', '../Common Library/jj_adobe_common_library.js', '../Common Library/jj_adobe_ns_utility.js'],
/**
* @param{record} record
*/
(record, search, https, runtime, adobeLibrary, jjUtil) => {
/**
* @desc function to fetch the integration record data
* @param soId
* @return {*}
*/
function fetchIntegrationRecData(soId) {
try {
let integrationRecData = {};
let customRecordSearch = search.create({
type: 'customrecord_jj_adobe_order_sync_szco227',
columns: [{
name: 'custrecord_jj_adobe_order_id'
}, {
name: 'internalid'
}],
filters: [["custrecord_jj_adobe_sales_order", "is", soId], "AND", ["isinactive", "is", "F"]]
});
let customRecordSearchCount = customRecordSearch.runPaged().count;
integrationRecData.count = customRecordSearchCount;
if (customRecordSearchCount !== 0) {
customRecordSearch.run().each(function (result) {
integrationRecData.recId = result.getValue({
"name": "internalid"
});
integrationRecData.orderEnityId = result.getValue({
"name": "custrecord_jj_adobe_order_id"
});
return true;
});
}
return integrationRecData;
} catch (e) {
log.error("Error @ fetchIntegrationRecData", e.message);
return { 'count': 0, recId: '', orderEnityId: '' };
}
}
/**
* @desc function to create IF in Adobe
* @param customRecDetails
* @param newRecord
*/
function createInvoiceInAdobe (newRecord, soAdobeId) {
try {
let numLines = newRecord.getLineCount({
sublistId: 'item'
});
let items = [];
for (let i = 0; i < numLines; i++) {
let lineItemObj = {};
let itemQuantity = newRecord.getSublistValue({
fieldId: 'quantity',
sublistId: 'item',
line: i
});
let itemType = newRecord.getSublistValue({
fieldId: 'itemtype',
sublistId: 'item',
line: i
});
let lineItemID = newRecord.getSublistValue({
fieldId: 'custcol_jj_adobe_line_id',
sublistId: 'item',
line: i
});
if (itemType == 'InvtPart') {
lineItemObj.order_item_id = lineItemID;
lineItemObj.qty = itemQuantity;
items.push(lineItemObj);
}
}
log.debug("items", items);
let responseData = {};
let apiCredentials = adobeLibrary.ADOBE_API_REQUESTS.CREATE_INVOICE;
apiCredentials = apiCredentials.replace("{order_id}", soAdobeId);
let BODY_TO_SEND = {
"capture": true,
"items": items,
"notify": true
};
responseData.payLoad = BODY_TO_SEND;
log.debug("apiCredentials", apiCredentials);
log.debug("BODY_TO_SEND", BODY_TO_SEND);
let response = adobeLibrary.commonFunctions.sendAPIRequest(
"POST",
apiCredentials,
BODY_TO_SEND
);
log.debug("response from library", response.code);
log.debug("response from body", JSON.parse(response.body));
responseData.code = response.code;
responseData.response = JSON.parse(response.body);
return responseData;
} catch (e) {
log.error("createInvoiceInAdobe", e);
return {
'payLoad': {
"capture": true,
"items": "",
"notify": true
}, 'code': '', 'response': e.message
}
}
}
/**
* @desc function to set data in integration record
* @param responseData
* @param customRecDetails
*/
function setIntegrationRecData(responseData, customRecDetails, invRecId, recType) {
try {
let today = new Date();
let customRecord = record.load({
type: 'customrecord_jj_adobe_order_sync_szco227',
id: Number(customRecDetails.recId),
isDynamic: true
});
if (responseData.code == 200) {
log.debug("inside if 200");
let adobeId = responseData.response;
customRecord.setValue({
fieldId: "custrecord_jj_status_inv_creation",
value: "CREATED"
});
customRecord.setValue({
fieldId: "custrecord_jj_inv_api_request",
value: JSON.stringify(responseData.payLoad)
});
customRecord.setValue('custrecord_jj_inv_created_date', today);
let inletray = customRecord.getValue('custrecord_jj_invoice_id');
inletray.push(invRecId);
customRecord.setValue({
fieldId: "custrecord_jj_invoice_id",
value: inletray
});
log.debug("inletray", inletray);
let invID = customRecord.getValue('custrecord_jj_magento_inv_id');
if (invID) {
customRecord.setValue('custrecord_jj_magento_inv_id', invID + ", " + adobeId)
} else {
customRecord.setValue({
fieldId: "custrecord_jj_magento_inv_id",
value: adobeId
});
}
customRecord.setValue('custrecord_jj_err_invc_creation', "");
// set value in IF record in netsuite
record.submitFields({
type: recType,
id: invRecId,
values: {
custbody_jj_adobe_invoice_id: adobeId
},
options: {
enableSourcing: false,
ignoreMandatoryFields: true
}
});
} else {
customRecord.setValue('custrecord_jj_status_inv_creation', "FAILED");
customRecord.setValue('custrecord_jj_err_invc_creation', responseData.response?.message);
}
customRecord.save({
ignoreMandatoryFields: true,
enableSourcing: false
});
} catch (e) {
log.error("error @setIntegrationRecData", e);
}
}
/**
* @desc Beforeload
*/
const beforeLoad = (scriptContext) => {
try {
let recordNew = scriptContext.newRecord;
if (scriptContext.type === "copy") {
recordNew.setValue({ fieldId: 'custbody_jj_adobe_invoice_id', value: "" });
}
} catch (e) {
log.debug("error @beforeload", e);
}
}
/**
* Defines the function definition that is executed after record is submitted.
* @param {Object} scriptContext
* @param {Record} scriptContext.newRecord - New record
* @param {Record} scriptContext.oldRecord - Old record
* @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum
* @since 2015.2
*/
const afterSubmit = (scriptContext) => {
if (scriptContext.type == scriptContext.UserEventType.CREATE || scriptContext.type == scriptContext.UserEventType.EDIT) {
try {
let isSandbox = jjUtil.refFunction.isSandbox();
log.debug("isSandbox",isSandbox);
if(isSandbox) {
return;
}
let newRecord = scriptContext.newRecord;
let invRecId = scriptContext.newRecord.id;
let recType = scriptContext.newRecord.type;
let soId = newRecord.getValue('createdfrom');
log.debug("recType id", recType);
let adobeInvoiceExist = newRecord.getValue('custbody_jj_adobe_invoice_id');
log.debug("adobeInvoiceExist", adobeInvoiceExist);
if (adobeInvoiceExist) {
return;
}
let paymentMethod = search.lookupFields({
type: search.Type.SALES_ORDER,
id: soId,
columns: ['paymentmethod']
}).paymentmethod;
log.debug("paymentMethod", paymentMethod);
//if the payment method is credit card, then we donot ned to create invoice in adobe commerce
// if (paymentMethod == 22)
// {
// return;
// }
let dueAmount = newRecord.getValue('amountremaining');
log.debug("dueAmount", dueAmount);
let customRecDetails = fetchIntegrationRecData(soId)
if (customRecDetails.count == 0) {
return;
}
let soAdobeId = customRecDetails.orderEnityId;
let responseData = createInvoiceInAdobe(newRecord, soAdobeId);
log.debug("responseData", responseData);
setIntegrationRecData(responseData, customRecDetails, invRecId, recType);
} catch (err) {
log.debug("error@afterSubmit", err.message);
}
}
}
return { beforeLoad, afterSubmit }
});