Script summarizes on pushing the invoice data to numerik
/**
* @NApiVersion 2.1
* @NScriptType UserEventScript
*/
/******************************************************************************
* Date : 19 July 2021
*
* Author: Jobin & Jismi IT Services LLP
* Script Description : Pushing invoice datas to numerik
*
******************************************************************************
* DEPLOYMENT :INVOICE
* This script summarises on pushing invoice datas to numerik.
*
* SCENARIO: On creating invoice in netsuite, the corresponding cretaed from SO is deleted from numerik. And if the invoice subsidiary is Canada
* the invoice data is pushed to numerik. Only lines which have item accounts as Income are pushed to numerik
* When on editing invoices, the updates are happed in numerik too. On delete, the same will be deleted from numerik
* If Invoice customer is not is numerik, the customer is also pushed to numerik
*
* *****************************************************************************
* REVISION HISTORY
*
* Revision 1.0 ${19 July 2021} JJ0131 : created
* Revision 2.0 ${28 Sep 2021} JJ0131 : Updated
*/
define(['N/https', 'N/record', 'N/search', 'N/email', 'N/runtime'],
/**
* @param{https} https
* @param{record} record
* @param{search} search
*/
(https, record, search, email, runtime) => {
const afterSubmit = (scriptContext) => {
try {
//Canada Subsidiaries internalid
var CASUB = 11,
CASUB2 = 14;
var header = [];
header['ApiKey'] = 'GcKVrpepGj1kwkIKNi5eNBNdnLuHgdEp3e972WrJ+qo=';
header['Content-Type'] = 'application/json';
var Invrecordd = scriptContext.newRecord;
if (scriptContext.type === scriptContext.UserEventType.CREATE) {
var Invrecord = record.load({
type: record.Type.INVOICE,
id: Invrecordd.id,
isDynamic: true
});
log.debug("Recordid", Invrecordd.id)
var subid = Invrecord.getValue({fieldId: 'subsidiary'});
if (subid == CASUB || subid == CASUB2) {
var sotranid = Invrecord.getValue({fieldId: 'custbody_createdfrom'});
log.debug("SOid", sotranid)
var invTranid = Invrecord.getValue({fieldId: 'tranid'});
log.debug("InvTranid", invTranid);
var invtranDate = Invrecord.getValue({fieldId: 'trandate'})
//On creating invoice, the corresponding SO is deleted from numerik
if (sotranid) {
var Soresponse = https.get({
url: 'https://numerik-publicapi-prod.azurewebsites.net/api/SalesData/TransactionId/' + sotranid,
headers: header
});
if (Soresponse.code == 200) {
log.debug("SO is present in numerik")
var SOdelete = https.delete({
url: 'https://numerik-publicapi-prod.azurewebsites.net/api/SalesData/TransactionId/' + sotranid,
headers: header
});
log.debug("CODE", SOdelete.code)
}
}
/***** If customer is not in numerik, customer is pushed ****/
cus(Invrecord, header);
/*** Pushing Invoice data to numerik**/
Invoice(Invrecord, header);
}
}
if (scriptContext.type === scriptContext.UserEventType.EDIT) {
//if invoice is updated in netsuite, the same is updated in numerik
var Invrecord = record.load({
type: record.Type.INVOICE,
id: Invrecordd.id,
isDynamic: true
});
log.debug("Record ID", Invrecord.id);
var tranInv = Invrecord.getValue({fieldId: 'tranid'});
log.debug("Tranid", tranInv)
var subsid = Invrecord.getValue({fieldId: 'subsidiary'});
if (subsid == CASUB || subsid == CASUB2) {
/****If invocie is present, Invoice is deleted and again pushed to numerik*****/
var editInv = https.get({
url: 'https://numerik-publicapi-prod.azurewebsites.net/api/SalesData/TransactionId/' + tranInv,
headers: header
});
if (editInv.code == 200) {
// log.debug("Invoice is present")
var InvDelete = https.delete({
url: 'https://numerik-publicapi-prod.azurewebsites.net/api/SalesData/TransactionId/' + tranInv,
headers: header
});
log.debug("CODE", InvDelete.code)
}
/**If customer is not in numerik, customer is pushed to numerik**/
cus(Invrecord, header);
/***Pushing invoide data to numerik**/
Invoice(Invrecord, header);
}
}
if (scriptContext.type === scriptContext.UserEventType.DELETE) {
//When invoice is deleted the same will be deleted from numerik
var Invrecord = scriptContext.newRecord;
log.debug("Record ID", Invrecord.id);
var tranInv = Invrecord.getValue({fieldId: 'tranid'});
log.debug("Tranid", tranInv)
var editInv = https.get({
url: 'https://numerik-publicapi-prod.azurewebsites.net/api/SalesData/TransactionId/' + tranInv,
headers: header
});
if (editInv.code == 200) {
var InvDelete = https.delete({
url: 'https://numerik-publicapi-prod.azurewebsites.net/api/SalesData/TransactionId/' + tranInv,
headers: header
});
log.debug("CODE", InvDelete.code)
}
}
} catch (e) {
log.debug({title: e.title, details: e.message});
log.error({title: e.title, details: e.message});
}
}
/*****Function to push customer data to numerik*****/
function cus(Invrecord, header) {
try {
var cus = Invrecord.getValue({fieldId: 'entity'});
log.debug("CUsid", cus);
var cuname = Invrecord.getText({fieldId: 'entity'});
var cusrecord = record.load({
type: record.Type.CUSTOMER,
id: cus,
isDynamic: true
});
var cusrecID = cusrecord.id;
log.debug("CURecId", cusrecID);
var cusSub = cusrecord.getValue({fieldId: 'subsidiary'});
var cusResponse = https.get({
url: 'https://numerik-publicapi-prod.azurewebsites.net/api/Customers',
headers: header
});
var cusObj = JSON.parse(cusResponse.body);
var cusPresent = false;
for (var i = 0; i < cusObj.length; i++) {
if (cusObj[i].id == cusrecID) {
cusPresent = true;
return cusPresent;
}
}
log.debug("Cuspresent", cusPresent);
if (cusPresent == false) {
var cusname = cusrecord.getValue({fieldId: 'companyname'});
var cusadr1 = cusrecord.getValue({fieldId: 'billaddr1'});
var cusadr2 = cusrecord.getValue({fieldId: 'billaddr2'});
var cusadr3 = cusrecord.getValue({fieldId: 'billaddr3'});
var cusemail = cusrecord.getValue({fieldId: 'email'});
var cusphone = cusrecord.getValue({fieldId: 'phone'});
var postcode = cusrecord.getValue({fieldId: 'billzip'});
var cuscity = cusrecord.getValue({fieldId: 'billcity'});
var cuscountry = cusrecord.getValue({fieldId: 'billcountry'});
var primarycontact = cusrecord.getValue('contact');
var cusalesrep = cusrecord.getText({fieldId: 'salesrep'});
var cusgrp1 = cusrecord.getText('custentity32');
var cusgrp2 = cusrecord.getText('custentity_distribution_channel');
var cusgrp4 = cusrecord.getText('custentity43');
var cusgrp6 = cusrecord.getValue('custentity44');
var cusgrp7 = cusrecord.getValue('parent');
var cusgrp8 = cusrecord.getText('custentity2');
var cusgrp9 = cusrecord.getText('custentity_rep_run');
var cusobj = [{}];
cusobj[0]["numerikId"] = 0;
cusobj[0]["id"] = cusrecID.toString();
cusobj[0]["name"] = cusname;
cusobj[0]["address1"] = cusadr1;
cusobj[0]["address2"] = cusadr2;
cusobj[0]["address3"] = cusadr3;
cusobj[0]["billToCity"] = cuscity;
cusobj[0]["postCode"] = postcode;
cusobj[0]["billToCountry"] = cuscountry;
cusobj[0]["email"] = cusemail;
cusobj[0]["phoneNumber"] = cusphone;
cusobj[0]["platinum"] = true;
cusobj[0]["consultant"] = primarycontact;
cusobj[0]["salesRep"] = cusalesrep;
cusobj[0]["customerGroup1"] = cusgrp1;
cusobj[0]["customerGroup2"] = cusgrp2; ////DISTRIBUTION CHANNEL
cusobj[0]["customerGroup3"] = '';
cusobj[0]["customerGroup4"] = cusgrp4; // Primary Group
cusobj[0]["customerGroup5"] = '';
cusobj[0]["customerGroup6"] = cusgrp6; //INSIDE SALES REP
cusobj[0]["customerGroup7"] = cusgrp7; // PARENT COMPANY
cusobj[0]["customerGroup8"] = cusgrp8; //Industry
cusobj[0]["customerGroup9"] = cusgrp9;
var response = https.post({
url: 'https://numerik-publicapi-prod.azurewebsites.net/api/Customers',
body: JSON.stringify(cusobj),
headers: header
});
log.debug("CODE", response.code);
} else {
log.debug("else")
}
} catch (e) {
log.debug({title: "Error@Customer", details: e.message});
log.error({title: "Error@Customer", details: e.message});
}
}
/*****funcion to push invoice data to numerik*****/
function Invoice(Invrecord, header) {
try {
var numLines = Invrecord.getLineCount({sublistId: 'item'});
log.debug("numlines", numLines)
var cus = Invrecord.getValue({fieldId: 'entity'});
log.debug("CUsid", cus);
var cuname = Invrecord.getText({fieldId: 'entity'});
var cusalesrep = Invrecord.getText({fieldId: 'salesrep'});
var productObj = [];
var salesDataObj = [];
for (var i = 0; i < numLines; i++) {
var itemtype = Invrecord.getSublistValue({sublistId: 'item', fieldId: 'itemtype', line: i});
if (itemtype !== 'Group' && itemtype !== 'EndGroup') {
var item = Invrecord.getSublistValue({sublistId: 'item', fieldId: 'item', line: i});
var invTranid = Invrecord.getValue({fieldId: 'tranid'});
var invtranDate = Invrecord.getValue({fieldId: 'trandate'})
log.debug("ITEM", item);
var rate = Invrecord.getSublistValue({sublistId: 'item', fieldId: 'rate', line: i});
if (rate == null || rate == "") {
rate = 0;
}
var qtycommit = Invrecord.getSublistValue({sublistId: 'item', fieldId: 'quantity', line: i});
var line = Invrecord.getSublistValue({sublistId: 'item', fieldId: 'line', line: i});
log.debug("line", line)
if (line == null || line == "")
line = i + 1;
log.debug('line', line);
var amount = Invrecord.getSublistValue({sublistId: 'item', fieldId: 'amount', line: i});
if (amount == null || amount == "") {
amount = 0;
}
var costestimate = Invrecord.getSublistValue({
sublistId: 'item',
fieldId: 'costestimate',
line: i
});
var itemfields = search.lookupFields({
type: 'item',
id: item,
columns: ['itemid', 'displayname', 'custitem19', 'incomeaccount']
});
var itemgroup = '';
if (itemfields.custitem19[0]) {
itemgroup = itemfields.custitem19[0].text;
}
if (costestimate == null || costestimate == '')
costestimate = 0;
var estgrossprofit = amount - costestimate;
var gross = estgrossprofit.toFixed(2);
log.debug("gross", gross)
var itemid = itemfields.itemid;
log.debug('itemname', itemid);
var itemdesc = itemfields.displayname;
var itemAcc = itemfields.incomeaccount[0].value;
log.debug("ItemAcc", itemAcc)
var Accsearch = search.lookupFields({
type: search.Type.ACCOUNT,
id: itemAcc,
columns: ['type']
});
var Acc = Accsearch.type[0].value;
log.debug("Acc", Acc)
if (Acc == 'Income') {
var Obj = {};
Obj[i] = {};
Obj[i].numerikId = 0;
Obj[i].id = item.toString();
Obj[i].name = itemid;
Obj[i].description = itemdesc;
Obj[i].productGroup = itemgroup;
Obj[i].productManager = '';
productObj.push(Obj[i]);
var salesObj = {};
salesObj[i] = {};
salesObj[i].numerikId = 0;
salesObj[i].transactionId = invTranid;
salesObj[i].dateOfTransaction = invtranDate;
salesObj[i].lineId = line.toString();
salesObj[i].quantity = qtycommit;
salesObj[i].unitSalesPrice = rate;
salesObj[i].lineTotal = amount;
salesObj[i].grossProfitDollars = gross;
salesObj[i].customerId = cus;
salesObj[i].customerName = cuname;
salesObj[i].productId = itemid;
salesObj[i].productDescription = itemdesc;
salesObj[i].productGroup = itemgroup;
salesObj[i].salesRep = cusalesrep;
salesObj[i].consultant = ''; //transType
salesObj[i].projectId = '';
salesObj[i].projectName = '';
salesDataObj.push(salesObj[i]);
}
}
}
var prodresponse = https.post({
url: 'https://numerik-publicapi-prod.azurewebsites.net/api/Products',
body: JSON.stringify(productObj),
headers: header
});
log.debug("PRDCODE", prodresponse.code);
var salesresponse = https.post({
url: 'https://numerik-publicapi-prod.azurewebsites.net/api/SalesData',
body: JSON.stringify(salesDataObj),
headers: header
});
log.debug("SALECODE", salesresponse.code)
} catch (e) {
log.debug({title: "Error@Invoice", details: e.message});
log.error({title: "Error@Invoice", details: e.message});
var script = runtime.getCurrentScript();
var rec = script.getParameter({
name: 'custscript_jj_inv_err_email'
});
var user = runtime.getCurrentUser();
var auth = user.id;
var env = runtime.envType;
var acnt = runtime.accountId;
var scriptid = script.id;
email.send({
author: auth,
recipients: rec,
subject: 'Numerik Sync Failure: Invoice #' + invTranid,
body: 'Account ID: ' + acnt + 'n' +
'Environment: ' + env + 'n' +
'Script: ' + scriptid + 'n' +
'Error Details: ' + e.name + 'n' +
'Error Message: ' + e.message
});
}
}
return {afterSubmit}
});