Jira Code: ESL-4
This will fetch orders from WooCommerce and create Sales Order in NetSuite. If the customer doesn’t exist, it will create a customer before creating the sales order. If any promotion/coupon code exists in WooCommerce, it will sync those as well while creating Sales Order.
This is using the promotions feature from SuitePromotions
/**
* @NApiVersion 2.x
* @NScriptType ScheduledScript
* @NModuleScope SameAccount
*/
/**
* Script Description
* This script will periodically fetch WooCommerce Orders and Create corresponding Customers
* and Sales orders in Netsuite
*
* Date Created : 30-July-2018
*/
/*******************************************************************************
* * Enlighten Smiles Limited | ESL-4 | WooCommerce Integration *
* **************************************************************************
*
*
* Author: Jobin & Jismi IT Services LLP
*
* Date Created : 30-July-2018
*
* REVISION HISTORY
*
*
******************************************************************************/
/**
* SCRIPT ID : customscript_esl4_jj_ss_woocommerce_inte
*
* DEPLOYMENT ID : customdeploy_esl4_jj_ss_woocommerce_inte
*
*/
/*
* WooCommerce API Reference : http://woocommerce.github.io/woocommerce-rest-api-docs/
*/
define(['N/https', 'N/record', 'N/search', 'N/runtime', 'N/task', 'N/url', 'N/format', 'N/log', 'SuiteScripts/customModule/moment'],
function (https, record, search, runtime, task, url, format, log, moment) {
//To check whether a value exists in parameter
function checkForParameter(parameter, parameterName) {
if (parameter != "" && parameter != null && parameter != undefined && parameter != "null" && parameter != "undefined" && parameter != " " && parameter != false) {
return true;
} else {
if (parameterName)
log.debug('Empty Value found', 'Empty Value for parameter ' + parameterName);
return false;
}
}
//To assign a default value if the it is empty
function assignDefaultValue(value, defaultValue) {
if (checkForParameter(value))
return value;
else
return defaultValue;
}
//WooCommerce REST API Calls
var wooCommerceAPIObj = {
listOrders: function (domain_url, auth, status, wc_ck, wc_cs, pageIndex) {
var request_url = url.format({
domain: domain_url + '/wp-json/wc/v2/orders',
params: {
consumer_key: wc_ck,
consumer_secret: wc_cs,
order: 'desc',
orderby: 'date',
status: ((checkForParameter(status)) ? (status) : ('processing')),
after: moment().subtract(10, 'days').toISOString(),
per_page: '100',
page: ((checkForParameter(pageIndex)) ? (pageIndex) : ('1'))
}
});
log.debug('request_url', request_url);
var response = https.get({
url: request_url,
headers: {
authorization: auth
}
});
return {
header: response.headers,
body: JSON.parse(response.body)
};
},
fetchCustomer: function (domain_url, auth, id, wc_ck, wc_cs) {
var response = https.get({
url: domain_url + '/wp-json/wc/v2/customers/' + id + '?consumer_key=' + wc_ck + '&consumer_secret=' + wc_cs,
headers: {
authorization: auth
}
});
return JSON.parse(response.body);
},
listCustomers: function (domain_url, auth, wc_ck, wc_cs) {
var response = https.get({
url: domain_url + '/wp-json/wc/v2/customers' + '?consumer_key=' + wc_ck + '&consumer_secret=' + wc_cs,
headers: {
authorization: auth
}
});
return {
header: response.headers,
body: JSON.parse(response.body)
};
},
fetchItem: function (domain_url, auth, id, wc_ck, wc_cs) {
var response = https.get({
url: domain_url + '/wp-json/wc/v2/products/' + id + '?consumer_key=' + wc_ck + '&consumer_secret=' + wc_cs,
headers: {
authorization: auth
}
});
return JSON.parse(response.body);
},
listItems: function (domain_url, auth, wc_ck, wc_cs) {
var response = https.get({
url: domain_url + '/wp-json/wc/v2/products' + '?consumer_key=' + wc_ck + '&consumer_secret=' + wc_cs,
headers: {
authorization: auth
}
});
return {
header: response.headers,
body: JSON.parse(response.body)
};
}
};
for (var key in wooCommerceAPIObj) {
if (typeof wooCommerceAPIObj[key] === 'function') {
wooCommerceAPIObj[key] = trycatch(wooCommerceAPIObj[key], 'wooCommerceAPIObj.' + key);
}
}
// GLOBAL OBJECT VARIABLES to store CUSTOMER, ITEM Mapping, Coupon Codes between WooCommerce and NetSuite
var GLOBAL_CUSTOMER_OBJ = {},
GLOBAL_ITEMS_OBJ = {},
GLOBAL_COUPON_OBJ = {};
//main or root object for this entire scheduled scritpt
var main = {
wooCommerceAPISearch: function () {
var responseArray = [];
var customrecord_esl4_jj_woocommerce_detailsSearchObj = search.create({
type: "customrecord_esl4_jj_woocommerce_details",
filters: [
["custrecord_esl4_jj_permission_type", "anyof", "1", "3"]
],
columns: [
search.createColumn({
name: "internalid",
sort: search.Sort.ASC,
label: "Internal ID"
}),
search.createColumn({
name: "custrecord_esl4_jj_website_url",
label: "Website URL"
}),
search.createColumn({
name: "custrecord_esl4_jj_consumer_key",
label: "Consumer Key"
}),
search.createColumn({
name: "custrecord_esl4_jj_consumer_secret",
label: "Consumer Secret"
}),
search.createColumn({
name: "custrecord_esl4_jj_authorization",
label: "Authorization"
}),
search.createColumn({
name: "custrecord_esl4_jj_permission_type",
label: "Permission Type"
})
]
}).run().each(function (result) {
responseArray.push({
Website_URL: result.getValue({
name: "custrecord_esl4_jj_website_url",
label: "Website URL"
}),
API_Authorization: result.getValue({
name: "custrecord_esl4_jj_authorization",
label: "Authorization"
}),
"Consumer_Secret": result.getValue({
name: "custrecord_esl4_jj_consumer_secret",
label: "Consumer Secret"
}),
"Consumer_Key": result.getValue({
name: "custrecord_esl4_jj_consumer_key",
label: "Consumer Key"
})
});
return true;
});
return responseArray;
},
searchCustomer: function (EMAIL_ID) {
var customerSearchObj = search.create({
type: "customer",
filters: [
["email", "is", EMAIL_ID],
"AND", ["stage", "anyof", "CUSTOMER", "LEAD", "PROSPECT"],
"AND", ["isinactive", "is", "F"]
],
columns: [
search.createColumn({
name: "internalid",
sort: search.Sort.ASC,
label: "Internal ID"
}),
search.createColumn({
name: "entityid",
label: "ID"
}),
search.createColumn({
name: "altname",
label: "Name"
}),
search.createColumn({
name: "email",
label: "Email"
}),
search.createColumn({
name: "phone",
label: "Phone"
})
]
}).run().getRange({
start: 0,
end: 2
});
if (customerSearchObj.length > 0)
return customerSearchObj[0];
else
return false;
},
modifyExistingAddress: function (customerAddressType, customerRecord) {
// sa - Shipping Address, ba - Billing Address
var addressLines = customerRecord.getLineCount({
sublistId: 'addressbook'
});
if (addressLines > 0) {
var defaultStatus;
for (i = 0; i < addressLines; i++) {
if (customerAddressType == 'sa')
defaultStatus = customerRecord.getSublistValue({
sublistId: 'addressbook',
fieldId: 'defaultshipping',
line: i
});
else if (customerAddressType == 'ba')
defaultStatus = customerRecord.getSublistValue({
sublistId: 'addressbook',
fieldId: 'defaultbilling',
line: i
});
if (defaultStatus == true)
return {
status: true,
line: i
};
}
return {
status: false,
};
}
return {
status: false,
};
},
setAddressSubRecord: function (customerRecord, addressObj, defaultBilling, defaultShipping) {
customerRecord.setCurrentSublistValue({
sublistId: 'addressbook',
fieldId: 'defaultbilling',
value: defaultBilling
});
customerRecord.setCurrentSublistValue({
sublistId: 'addressbook',
fieldId: 'defaultshipping',
value: defaultShipping
});
var myaddressSubrecord = customerRecord.getCurrentSublistSubrecord({
sublistId: 'addressbook',
fieldId: 'addressbookaddress'
});
myaddressSubrecord.setValue({
fieldId: 'country',
value: addressObj.country
});
try {
myaddressSubrecord.setValue({
fieldId: 'city',
value: addressObj.city
});
} catch (er) {
log.debug('Handled Error @main.setAddressSubRecord on city', er);
if (checkForParameter(addressObj.city))
myaddressSubrecord.setValue({
fieldId: 'city',
value: (addressObj.city).substring(0, 28)
});
}
try {
myaddressSubrecord.setValue({
fieldId: 'state',
text: addressObj.state
});
} catch (err) {
try {
log.debug('Handled Error @main.setAddressSubRecord on state', err);
if (checkForParameter(addressObj.state))
myaddressSubrecord.setValue({
fieldId: 'state',
text: (addressObj.state).substring(0, 28)
});
} catch (errr) {
log.debug('Handled 2nd Error @main.setAddressSubRecord on state ', errr);
}
}
myaddressSubrecord.setValue({
fieldId: 'zip',
value: addressObj.postcode
});
myaddressSubrecord.setValue({
fieldId: 'addrphone',
value: assignDefaultValue(addressObj.phone, '000 000 0000')
});
myaddressSubrecord.setValue({
fieldId: 'attention',
value: addressObj.first_name + ' ' + addressObj.last_name
});
myaddressSubrecord.setValue({
fieldId: 'addressee',
value: addressObj.company
});
myaddressSubrecord.setValue({
fieldId: 'addr1',
value: addressObj.address_1
});
myaddressSubrecord.setValue({
fieldId: 'addr2',
value: addressObj.address_2
});
customerRecord.commitLine({
sublistId: 'addressbook'
});
},
processCustomer: function (customerBilling, customerShipping, CUSTOMER_FORM_ID) {
log.debug('customerBilling', customerBilling);
log.debug('customerShipping', customerShipping);
customerBilling.email = (customerBilling.email).toString().trim();
if (!checkForParameter(customerBilling.email))
return false;
var customerRecord, customerObj;
if (checkForParameter(GLOBAL_CUSTOMER_OBJ[customerBilling.email])) {
log.debug('Customer Prossed Before ', 'YES');
customerRecord = record.load({
type: record.Type.CUSTOMER,
id: GLOBAL_CUSTOMER_OBJ[customerBilling.email],
isDynamic: true
});
} else {
customerObj = main.searchCustomer(customerBilling.email);
if (checkForParameter(customerObj)) {
log.debug('Customer Exits ', 'YES');
customerRecord = record.load({
type: record.Type.CUSTOMER,
id: customerObj.getValue({
name: 'internalid'
}),
isDynamic: true
});
} else {
log.debug('Customer Exits ', 'NO');
customerRecord = record.create({
type: record.Type.CUSTOMER,
isDynamic: true,
defaultValues: {
customform: CUSTOMER_FORM_ID
}
});
customerRecord.setValue({
fieldId: 'isperson',
value: 'T',
ignoreFieldChange: false
});
customerRecord.setValue({
fieldId: 'category',
value: 1, // Dentist
ignoreFieldChange: false
});
customerRecord.setValue({
fieldId: 'entitystatus',
value: 10, // CUSTOMER-Purchase
ignoreFieldChange: false
});
customerRecord.setValue({
fieldId: 'pricelevel',
value: 10, // Domestic Direct
ignoreFieldChange: false
});
customerRecord.setValue({
fieldId: 'terms',
value: 8, // Prepayment
ignoreFieldChange: false
});
customerRecord.setValue({
fieldId: 'leadsource',
value: 50270, // 206 WooCommerce
ignoreFieldChange: false
});
customerRecord.setValue({
fieldId: 'email',
value: customerBilling.email,
ignoreFieldChange: false
});
}
}
customerRecord.setValue({
fieldId: 'firstname',
value: customerBilling.first_name,
ignoreFieldChange: false
});
if (checkForParameter(customerBilling.last_name))
customerRecord.setValue({
fieldId: 'lastname',
value: customerBilling.last_name,
ignoreFieldChange: false
});
customerRecord.setValue({
fieldId: 'phone',
value: customerBilling.phone,
ignoreFieldChange: false
});
var selectLine, isAddressExisting;
if (checkForParameter(customerObj)) {
// sa - Shipping Address, ba - Billing Address
isAddressExisting = main.modifyExistingAddress('ba', customerRecord);
log.debug('isAddressExisting for Billing', isAddressExisting);
if (checkForParameter(isAddressExisting.status))
selectLine = customerRecord.selectLine({
sublistId: 'addressbook',
line: isAddressExisting.line
});
else
selectLine = customerRecord.selectNewLine({
sublistId: 'addressbook'
});
} else {
selectLine = customerRecord.selectNewLine({
sublistId: 'addressbook'
});
}
main.setAddressSubRecord(customerRecord, customerBilling, true, false);
isAddressExisting = main.modifyExistingAddress('sa', customerRecord);
log.debug('isAddressExisting for Shipping', isAddressExisting);
if (checkForParameter(isAddressExisting.status))
selectLine = customerRecord.selectLine({
sublistId: 'addressbook',
line: isAddressExisting.line
});
else
selectLine = customerRecord.selectNewLine({
sublistId: 'addressbook'
});
if (checkForParameter(customerShipping.country) && checkForParameter(customerShipping.city) && checkForParameter(customerShipping.postcode))
main.setAddressSubRecord(customerRecord, customerShipping, false, true);
else
main.setAddressSubRecord(customerRecord, customerBilling, false, true);
var recordID = customerRecord.save({
enableSourcing: true,
ignoreMandatoryFields: true
});
log.debug('Customer ID', recordID);
GLOBAL_CUSTOMER_OBJ[customerBilling.email] = recordID;
return ((checkForParameter(recordID)) ? (recordID) : (false));
},
execute: function (scriptContext) {
var currentDate = new Date();
log.debug('EXECUTION STARTS', 'EXECUTION BEGINS AT ' + (currentDate.toUTCString()));
//WooCommerce Authorisation Details
var WOOCOMMERCE_AUTH = main.wooCommerceAPISearch();
if (WOOCOMMERCE_AUTH.length > 0) {
var parameterRecordObj = record.load({
type: 'customrecord_deploymentparameters',
id: 241, //WooCommerce Integration
isDynamic: true
});
var CUSTOMER_FORM_ID = parameterRecordObj.getValue({
fieldId: 'custrecord_deploymentparametervalue' //DEPLOYMENT PARAMETER VALUE 1
});
CUSTOMER_FORM_ID = assignDefaultValue(CUSTOMER_FORM_ID, 169);
var SALES_ORDER_FORM_ID = parameterRecordObj.getValue({
fieldId: 'custrecord_deploymentparametervalue2' //DEPLOYMENT PARAMETER VALUE 2
});
SALES_ORDER_FORM_ID = assignDefaultValue(SALES_ORDER_FORM_ID, 145);
log.debug('CUSTOMER_FORM_ID', CUSTOMER_FORM_ID);
log.debug('SALES_ORDER_FORM_ID', SALES_ORDER_FORM_ID);
var listAllOrders, listOrders, wc_url, wc_auth, wc_cs, wc_ck;
var customerID, salesID;
for (var api_index = 0, api_len = WOOCOMMERCE_AUTH.length; api_index < api_len; api_index++) {
log.debug('WOOCOMMERCE_AUTH[api_index] ', WOOCOMMERCE_AUTH[api_index]);
wc_url = WOOCOMMERCE_AUTH[api_index].Website_URL;
wc_auth = WOOCOMMERCE_AUTH[api_index].API_Authorization;
wc_ck = WOOCOMMERCE_AUTH[api_index].Consumer_Key;
wc_cs = WOOCOMMERCE_AUTH[api_index].Consumer_Secret;
log.debug('PROCCESSING FOR ', wc_url);
//listAllOrders = wooCommerceAPIObj.listOrders(wc_url, wc_auth, 'completed');
listAllOrders = wooCommerceAPIObj.listOrders(wc_url, wc_auth, 'processing', wc_ck, wc_cs);
log.debug('listAllOrders ', listAllOrders);
listOrders = listAllOrders.body;
log.debug('listOrders ', listOrders);
log.debug('Total WooCoomerce Order : ', listOrders.length);
for (var order_index = 0, order_len = listOrders.length; order_index < order_len; order_index++) {
if (main.isSalesOrderExits(listOrders[order_index].id)) {
log.debug('PROCCESSING WooCoomerce Order : ', listOrders[order_index].id);
customerID = main.processCustomer(listOrders[order_index].billing, listOrders[order_index].shipping, CUSTOMER_FORM_ID);
if (checkForParameter(customerID)) {
listOrders[order_index].line_items = main.processItems(listOrders[order_index].line_items, wc_url, wc_auth, wc_ck, wc_cs);
//listOrders[order_index]['Website_URL'] = wc_url;
//log.debug('listOrders[order_index]', listOrders[order_index]);
log.debug('listOrders[order_index].line_items', listOrders[order_index].line_items);
salesID = main.createSalesOrder(customerID, listOrders[order_index], SALES_ORDER_FORM_ID, wc_url);
log.debug('salesID', salesID);
}
customerID = '';
salesID = '';
} else
log.debug('WooCoomerce Order Exits: ', listOrders[order_index].id);
if (main.isReschedule())
break;
}
wc_url = '';
wc_auth = '';
wc_cs = '';
wc_ck = '';
listAllOrders = undefined;
listAllOrders = {};
listOrders = undefined;
listOrders = [];
GLOBAL_CUSTOMER_OBJ = undefined;
GLOBAL_CUSTOMER_OBJ = {};
GLOBAL_ITEMS_OBJ = undefined;
GLOBAL_ITEMS_OBJ = {};
}
} else
log.debug('No API Exists', 'WooCommerce API not found');
currentDate = new Date();
log.debug('FINAL remainingUsage', main.remainingUsage());
log.debug('EXECUTION ENDS', 'EXECUTION ENDS AT ' + (currentDate.toUTCString()));
},
isSalesOrderExits: function (WOOCOMMERCE_ORDER_ID) {
log.debug('WOOCOMMERCE_ORDER_ID', WOOCOMMERCE_ORDER_ID);
WOOCOMMERCE_ORDER_ID = (((WOOCOMMERCE_ORDER_ID).toString()).trim());
var salesorderSearchObj = search.create({
type: "salesorder",
filters: [
["type", "anyof", "SalesOrd"],
"AND", ["custbody_requester", "is", 'WooCommerce'],
"AND", ["custbody_woocommerce_order_id", "is", WOOCOMMERCE_ORDER_ID],
"AND", ["mainline", "is", "T"]
],
columns: [
search.createColumn({
name: "internalid",
sort: search.Sort.ASC,
label: "Internal ID"
}),
search.createColumn({
name: "custbody_woocommerce_order_id",
label: "WOOCOMMERCE ORDER ID"
})
]
}).run().getRange({
start: 0,
end: 2
});
if (salesorderSearchObj.length > 0)
return false; //Sales Order Already Exits
else
return true; //Sales Order Doesn't Exit
},
filterWC_METADATA: function (WC_METADATA, keyName) {
keyName = assignDefaultValue(keyName, 'wpcf-nt-item-id');
for (var obj_index = 0, obj_len = WC_METADATA.length; obj_index < obj_len; obj_index++) {
if (WC_METADATA[obj_index].key == keyName)
return WC_METADATA[obj_index];
}
return false;
},
processItems: function (lineItems, wc_url, wc_auth, wc_ck, wc_cs) {
var WC_itemObj, filtered_METADATA;
for (var item_index = 0, item_len = lineItems.length; item_index < item_len; item_index++) {
if (!checkForParameter(GLOBAL_ITEMS_OBJ[lineItems[item_index].product_id])) {
WC_itemObj = wooCommerceAPIObj.fetchItem(wc_url, wc_auth, lineItems[item_index].product_id, wc_ck, wc_cs);
log.debug('WC_itemObj', WC_itemObj);
filtered_METADATA = main.filterWC_METADATA(WC_itemObj.meta_data);
if (checkForParameter(filtered_METADATA))
GLOBAL_ITEMS_OBJ[lineItems[item_index].product_id] = filtered_METADATA.value;
}
lineItems[item_index]['NS_ID'] = GLOBAL_ITEMS_OBJ[lineItems[item_index].product_id];
}
log.debug('GLOBAL_ITEMS_OBJ', GLOBAL_ITEMS_OBJ)
log.debug('lineItems', lineItems)
return lineItems;
},
retrieveCouponCodeID: function (couponCode) {
couponCode = couponCode.toString().trim();
if (checkForParameter(GLOBAL_COUPON_OBJ[couponCode]))
return GLOBAL_COUPON_OBJ[couponCode];
var promotioncodeSearchObj = search.create({
type: "promotioncode",
filters: [
["code", "is", couponCode]
],
columns: [
search.createColumn({
name: "internalid",
sort: search.Sort.ASC,
label: "Internal ID"
}),
search.createColumn({
name: "name",
label: "Name"
}),
search.createColumn({
name: "code",
label: "Coupon Code"
}),
search.createColumn({
name: "discountrate",
label: "Discount Rate"
}),
search.createColumn({
name: "website",
label: "Websites"
}),
search.createColumn({
name: "custrecord_advpromo_channel",
label: "Site"
})
]
}).run().each(function (result) {
GLOBAL_COUPON_OBJ[couponCode] = result.getValue({
name: "internalid"
})
return false;
});
return GLOBAL_COUPON_OBJ[couponCode];
},
createSalesOrder: function (customerID, orderObj, SALES_ORDER_FORM_ID, Website_URL) {
//Create Sales Order
var salesObjRecord = record.transform({
fromType: record.Type.CUSTOMER,
fromId: parseInt(customerID),
toType: record.Type.SALES_ORDER,
isDynamic: true
});
salesObjRecord.setValue({
fieldId: 'customform',
value: SALES_ORDER_FORM_ID
});
salesObjRecord.setValue({
fieldId: 'orderstatus',
value: 'A' // [{"value":"A","text":"Pending Approval"},{"value":"B","text":"Pending Fulfillment"}]
});
salesObjRecord.setValue({
fieldId: 'custbody_requester',
value: 'WooCommerce'
});
salesObjRecord.setValue({
fieldId: 'location',
value: 1 // Warehouse - Acton
});
salesObjRecord.setValue({
fieldId: 'custbody_woocommerce_order_id', //WOOCOMMERCE ORDER ID
value: (((orderObj.id).toString()).trim())
});
salesObjRecord.setValue({
fieldId: 'custbody_suitesync_authorization_code', //STRIPE TRANSACTION ID
value: (((assignDefaultValue(orderObj.transaction_id, '')).toString()).trim())
});
salesObjRecord.setValue({
fieldId: 'custbody_woocommerce_website_id', //WOOCOMMERCE WEBSITE ID
value: (((assignDefaultValue(Website_URL, '')).toString()).trim())
});
salesObjRecord.setValue({
fieldId: 'shipcarrier', //SHIPPING CARRIER
value: 'nonups' // {"value":"ups","text":"UPS"},{"value":"nonups","text":"More"}
});
salesObjRecord.setValue({
fieldId: 'shipmethod', //SHIP VIA
value: 1494 // Email
});
salesObjRecord.setValue({
fieldId: 'shippingtaxcode', //SHIPPING TAX CODE
value: 685 // {"value":"685","text":"VAT:SR-GB"}
});
if (checkForParameter(orderObj.coupon_lines))
if (checkForParameter(orderObj.coupon_lines[0]))
if (checkForParameter(orderObj.coupon_lines[0].code)) {
salesObjRecord.selectNewLine({
sublistId: 'promotions'
});
salesObjRecord.setCurrentSublistValue({
sublistId: 'promotions',
fieldId: 'promocode',
value: assignDefaultValue(main.retrieveCouponCodeID(orderObj.coupon_lines[0].code), '')
});
salesObjRecord.commitLine({
sublistId: 'promotions'
});
salesObjRecord.setValue({
fieldId: 'custbody_woocommerce_coupon_code', //WOOCOMMERCE COUPON CODE
value: orderObj.coupon_lines[0].code
});
}
var lineItems = orderObj.line_items;
var ticketItems = orderObj.tickets;
var ticket_type_id;
if (checkForParameter(ticketItems)) {
ticketItems.forEach(function (eachTicket, lineTicket) {
salesObjRecord.selectNewLine({
sublistId: 'item'
});
ticket_type_id = eachTicket.ticket_type_id[0];
for (var item_index = 0, item_length = lineItems.length; item_index < item_length; item_index++) {
if ((ticket_type_id).toString().trim() == (lineItems[item_index].product_id).toString().trim()) {
salesObjRecord.setCurrentSublistValue({
sublistId: 'item',
fieldId: 'item',
value: (lineItems[item_index].NS_ID).toString().trim(),
ignoreFieldChange: false
});
if (checkForParameter(eachTicket.first_name))
salesObjRecord.setCurrentSublistValue({
sublistId: 'item',
fieldId: 'custcol_delegate_first_name', //Delegate first name
value: assignDefaultValue(eachTicket.first_name.toString(), ''),
ignoreFieldChange: false
});
if (checkForParameter(eachTicket.last_name))
salesObjRecord.setCurrentSublistValue({
sublistId: 'item',
fieldId: 'custcol_delegate_last_name', //Delegate last name
value: assignDefaultValue(eachTicket.last_name.toString(), ''),
ignoreFieldChange: false
});
if (checkForParameter(eachTicket.tc_ff_gdcnumber_tcfn_9175))
salesObjRecord.setCurrentSublistValue({
sublistId: 'item',
fieldId: 'custcol_delegate_gdc_number', //Delegate GDC no
value: assignDefaultValue(eachTicket.tc_ff_gdcnumber_tcfn_9175.toString(), ''),
ignoreFieldChange: false
});
if (lineTicket == 0) {
if (checkForParameter(eachTicket.tc_ff_gdcnumber_tcfn_9175)) {
var customerRecord = record.load({
type: record.Type.CUSTOMER,
id: parseInt(customerID),
isDynamic: true
});
var GDC_NUMBER = customerRecord.getValue({
fieldId: 'custentity_gdcnumber'
});
if (!checkForParameter(GDC_NUMBER)) {
customerRecord.setValue({
fieldId: 'custentity_gdcnumber',
value: assignDefaultValue(eachTicket.tc_ff_gdcnumber_tcfn_9175.toString(), ''),
ignoreFieldChange: false
});
customerRecord.save({
enableSourcing: true,
ignoreMandatoryFields: true
});
}
}
}
}
}
salesObjRecord.setCurrentSublistValue({
sublistId: 'item',
fieldId: 'quantity',
value: 1,
ignoreFieldChange: false
});
salesObjRecord.setCurrentSublistValue({
sublistId: 'item',
fieldId: 'taxcode',
value: 685, // {"value":"685","text":"VAT:SR-GB"}
ignoreFieldChange: false
});
salesObjRecord.commitLine({
sublistId: 'item'
});
});
}
salesObjRecord.setValue({
fieldId: 'shippingcost', //SHIPPING COST
value: 0.00
});
var salesRecordID = salesObjRecord.save({
enableSourcing: true,
ignoreMandatoryFields: true
});
return ((checkForParameter(salesRecordID)) ? (salesRecordID) : (false));
},
remainingUsage: function () {
//var scriptObj = runtime.getCurrentScript();
var remainingTime = runtime.getCurrentScript().getRemainingUsage();
return remainingTime;
},
rescheduleScript: function () {
var currentDate = new Date();
log.debug('EXECUTION RESCHEDULES', 'EXECUTION RESCHEDULES AT ' + (currentDate.toUTCString()));
var remainingTime = runtime.getCurrentScript().getRemainingUsage();
log.debug("Remaining governance units", remainingTime);
var rescheduleTask = task.create({
taskType: task.TaskType.SCHEDULED_SCRIPT,
scriptId: "customscript_esl4_jj_ss_woocommerce_inte",
deploymentId: "customdeploy_esl4_jj_ss_woocommerce_inte",
params: {}
});
var scriptTaskId = rescheduleTask.submit();
log.debug("reschedule scriptTaskId ", scriptTaskId);
return true;
},
isReschedule: function () {
if (parseInt(main.remainingUsage()) < 500)
return main.rescheduleScript();
else
return false;
}
};
for (var key in main) {
if (typeof main[key] === 'function') {
main[key] = trycatch(main[key], 'main.' + key);
}
}
function trycatch(myfunction, key) {
function logDetails(error) {
log.debug("Error in function " + key, JSON.stringify(error));
log.debug('Error on function ' + key, JSON.stringify(getError(error)));
log.error("Error in function " + key, JSON.stringify(error));
log.error('Error on function ' + key, JSON.stringify(getError(error)));
return false;
}
return function () {
try {
return myfunction.apply(this, arguments);
} catch (error) {
return logDetails(error);
}
};
}
return main; //main <--- function root
});
/*******************************************************************************
* return error
*
* @param e
* @returns
*
*/
function getError(e) {
var stErrMsg = '';
if (e.getDetails != undefined) {
stErrMsg = '_' + e.getCode() + '<br>' + e.getDetails() + '<br>' +
e.getStackTrace();
} else {
stErrMsg = '_' + e.toString();
}
return stErrMsg;
}