Showing posts with label Scriptable Cart. Show all posts
Showing posts with label Scriptable Cart. Show all posts

Monday, August 8, 2011

Scriptable Cart - Full Sample By Jason K

We've MOVED!!!! www.codeboxllc.com/ksc

Hey Guys. I've been meaning to post this up but lost track of time due to extermination work I've been doing.
Couple months ago, I've worked with Jason K from NetSuite to trouble shoot remove/add issues I was having with my particular scriptable cart process. What this code is SUPPOSED to do:
When an item is added with certain country, it pro grammatically adds country specific surcharge item to the cart. In increments existing surcharge item in the cart if it already exists, it adds new country item if it doesn't exists. Removing parent item will also either increments or decrements the surcharge item.
I have not tried out his code personally but he assures me that it worked for him when he was fully testing out the process in his environment.

I'm hoping this will help in your effort to implement Webstore Scriptable Cart/Checkout form:


/*
Summary:  A custom item option is attached to a certificate which allows the shopper to choose a country.
When the shopper does this, a surcharge will be added to the cart based on the country chosen.  The shopper
can also add another certificate to the cart with a different country and there will be a separate line item
for each surcharge for each country.


This script also syncs up quantities for each cert-country combination.  For example, if the shopper increments,
decrements, or adds another Canada certificate to the cart, the quantity of the canadian surcharge will follow
that quantity.  This will NOT affect the quantity of other surcharges that are not the same country.


Finally, when a certificate is removed from the cart, the associated surcharge is also removed.


There are two customizations that were done to the sales order to support this script:


1) a new custom body field "custbody_processing", a text field, was added to ensure that no infinite looping
is seen.


2) a new custom body field "custbody_deletedcountry", a text field, is added and used by the validateDelete
event. The problem with recalc during a deletion is that we don't know what was deleted.  But, in our
custom validateDelete, if a cert was deleted, we save the cert's country in this custom field.  Then, during
recalc, we can just look up what surcharge needs to be removed and remove it.


There are also a couple of utility functions included below, including safeSelectNewLineItem and safeSelectLineItem.
In some cases, I've noticed that selectNewLineItem and selectLineItem throws an error if the script left the current
item row in an uncommitted state.  Using these functions will ensure that a commit will be done if need be before
a new row is selected.  The other functions should be self-explanatory.


*/
var certId = "74"; // ID of the general certificate, will including an item option custcol_certcountry
var certCountry = "custcol_certcountry"; // name of the custom column


// Map to define what surcharge item ID belongs to which country.
// In this case, I've only set up two countries along with two non inventory items.
var surchargeMap = {"US":"76", "CA":"75"};


// In order to make things easier for us, we will track the type of cert
// that is deleted via a validateDelete.  Will get the country
function validateDelete(type)
{
if (type == 'item')
{
var itemId = nlapiGetCurrentLineItemValue('item','item');
if (itemId == certId)
{
// if we get here, we know a certificate is being deleted.  Store the country in our
// custom body field for use in recalc.
var country = nlapiGetCurrentLineItemValue('item', certCountry);
log('Item ID '+itemId+' being deleted for country '+country+' - storing this in custom field');
nlapiSetFieldValue('custbody_deletedcountry', country);
}
}


return true; // Always return either true or false during validation
}


function onRecalc(type, action)
{
if (type != 'item') { return; }


try
{
var processing = nlapiGetFieldValue('custbody_processing');
if (processing != null && processing == 'T')
{
// We are in a secondary recalc, so exit
return;
}


// If we've passed the previous check, we are in the first
// level of recalc, so set processing flag
nlapiSetFieldValue('custbody_processing', 'T');


if (action=='commit')
{
doCommit();
}


if (action=='remove')
{
doRemove();
}
}
catch (err)
{
log("General Error: "+err.message);
}
finally
{
// Now, even with an error, we want to reset the processing flag
// so use a finally-clause to ensure this happens no matter what
nlapiSetFieldValue('custbody_processing', 'F');
}
}




// Called when a commit is done for recalc
function doCommit()
{
var thisItem = nlapiGetCurrentLineItemValue('item','item');


// Ignore any add-to-carts that are not certifications
if (thisItem != certId) { return; }


var thisQty = nlapiGetCurrentLineItemValue('item','quantity');
log("Current qty of cert = "+thisQty);


var thisCountry = nlapiGetCurrentLineItemValue('item', certCountry);
log("Current country of cert: "+thisCountry);


var surchargeId = surchargeMap[thisCountry];


if (isEmpty(surchargeId))
{
log("No surcharge ID found for country "+thisCountry+" - skipping processing");
return;
}


var surchargeLine = findItem(surchargeId);


if (surchargeLine == -1)
{
// We need to add a surcharge here
log("surcharge not found - adding surcharge");
addItem(surchargeId, thisQty);
}
else
{
surchargeQty = nlapiGetLineItemValue('item', 'quantity', surchargeLine);
log("Surcharge found - current Surcharge qty "+surchargeQty);


if (surchargeQty != thisQty)
{
log("updating quantity of surcharge");
safeSelectLineItem(surchargeLine);
nlapiSetCurrentLineItemValue('item', 'quantity', thisQty);
nlapiCommitLineItem('item');
}
}
}


// Called when a remove is done for recalc.  We have tracked the country that was
// deleted in the custom field, so this should be straightforward.  If there's no
// value in the custom field, don't do anything.
function doRemove()
{
// First, we get the deleted country from custbody_deleteditem
var deletedCountry= nlapiGetFieldValue('custbody_deletedcountry');


// If it's empty, this means that the item that was deleted was not a cert, so ignore.
if (isEmpty(deletedCountry))
{
return;
}


// Start a try-block here so after the remove we are sure that custbody_deletedcountry
// is cleared out even during an error
try
{
log('Country '+deletedCountry+' has been deleted, finding related surcharge');


var surchargeId = surchargeMap[deletedCountry];
var surchargeLine = findItem(surchargeId);


// only delete if appropriate surcharge is found
if (surchargeLine > 0)
{
log('Surcharge item for country '+deletedCountry+' found on line '+surchargeLine+' - removing');
safeSelectLineItem(surchargeLine);
nlapiRemoveLineItem('item', surchargeLine);
}
}
finally
{
nlapiSetFieldValue('custbody_deletedcountry', '');
}
}


// This function adds the given item to the order
function addItem(itemID, qty)
{
safeSelectNewLineItem();
nlapiSetCurrentLineItemValue('item', 'item', itemID);
nlapiSetCurrentLineItemValue('item', 'quantity', qty);
nlapiCommitLineItem('item');
}




// Sometimes, a selectNewLineItem results in an error if there's uncommitted
// values in the item list.  This makes sure this does not happen.
function safeSelectNewLineItem()
{
if (notEmpty(nlapiGetCurrentLineItemValue('item','item')))
{
nlapiCommitLineItem('item');
}


nlapiSelectNewLineItem('item');
}


// Sometimes, a selectLineItem results in an error if there's uncommitted
// values in the item list.  This makes sure this does not happen.
function safeSelectLineItem(itemLine)
{
if (notEmpty(nlapiGetCurrentLineItemValue('item','item')))
{
nlapiCommitLineItem('item');
}


nlapiSelectLineItem('item', itemLine);
}


// General find function for the item list
function findItem(itemID)
{
var cnt = nlapiGetLineItemCount('item');
for (var i=1; i <= cnt; i++)
{
if (nlapiGetLineItemValue('item','item',i) == itemID)
{
return i;
}
}


return -1; // -1 means not found
}




function isEmpty(tmp)
{
return tmp == null || tmp == '';
}


function notEmpty(tmp)
{
return !isEmpty(tmp);
}




function log(msg)
{
alert(msg);
}


Saturday, May 28, 2011

Alternate more efficient way to Debug Webstore Scriptable Cart

We've MOVED!!!! www.codeboxllc.com/ksc

Recently, I had a nice email conversation with Jason K. from NetSuite. He thought my workaround for debugging scriptable cart/checkout was very clever. It means alot coming from him. However, he actually came up with even better way of debugging scriptable cart/checkout. Jason, you are the MAN!

His method resolves the issue of eating away at script metering in my version of workaround. Using nlapiRequestURL() eats 10 governance from allowance and it causes issue during form testing. He also mentioned something very important as well. With v2011.1, NetSuite relaxed the rules on type of Sales Order form that can be used for scriptable cart/checkout. This means, you are not restricted to using External Sales Order. You can customize Standard Sales Order and use it for the scriptable cart.

Here is how you go about doing this: Thank you Jason K. for coming up with this workaround!

Step 1: Create custom sales order forms for both Invoice and CashSales from standard invoice sales order and standard cashsale sales order.
Setup > Customization > Transaction Forms
** Make sure you do NOT put anything under custom code tab for both forms!!!
After you create the two new forms, make a note of their Internal IDs. You will need them in step 2.

Step 2: Create alternate version of your scriptable cart script. Keep currently working version as your backup. You may need it.
At the top of every event functions, add following line of code:
if (nlapiGetFieldValue('customform') != '[InternalID of SO Invoice from Step 1]'
&&   nlapiGetFieldValue('customform') != 'InternalID of SO CashSale from Step 1') {
  return;
}
This ensures that script only fires for the sales order forms you are using on Webstore.
Make sure every time you want to print debugging message, you use nlapiLogExecution() call to do so.

Step 3: Create new "Client Script" file and deploy it for all Sales Order.
Creating new script file: Set > Customization > Script > New > Client Script
Don't for get to fill out all your event functions and attach any library scripts. Deploying this script for Sales order is up to your preference. I usually do "Save & Deploy".
When you are deploying your client script for sales order, make sure list of audience includes Customer Center and perhaps most obvious thing, make sure it Applies to Sales Order.

Step 4: Attach newly created Sales Order forms to your webstore
Setup > Web Site > Set up web site. 
Under the Setup Tab > Preferences section, select new invoice sales order for Scripting Template (Invoice) and new cash sale sales order for Scripting Template (Credit Card).

That's it! To view execution logs, you can to go Script or Script Deployment record and click Execution Log tab.

Hope this works out for you guys. Thank you again Jason K for this workaround!

Thursday, May 19, 2011

Working with Scriptable Cart in NetSuite Webstore - Lessons Learned

We've MOVED!!!! www.codeboxllc.com/ksc

It's been a while since my last post. I have a good reason. I've been struggling with Scriptable Cart feature in NetSuite advanced Webstore. After close to 9 days of none stop work, I think I've finally have it working.

This is new feature NetSuite released and it's still in an infant stage yet very powerful when coded correctly.
First thing I struggled with the most was not being able to see scripts' behavior when executed from the Webstore. You can read about on "How to debug NetSuite Webstore Scriptable Cart".

This gave me some major insight as to how NetSuite Webstore processes each addition/subtraction of items in the cart.

I want to give shout out to Jason K. for providing massive assistance in getting my cart script to work properly!

Here are some things I've found out that could help you:
  1. You can get execution environment variable using nlapiGetContext().getEnvironment() call. I didn't think this was possible but using this in your cart script actually returns SANDBOX, BETA or PRODUCTION from webstore.
     This will be very handy if you have to switch item ID depending on the environments.

  2. nlapiCommitLineItem('item') Is a MUST Call if you want your recalc to correctly recalculate totals. I tried taking the easy way out by not calling commit. What a newb mistake that was.

  3. nlapiLookupField() call can not be used. Obviously right? Well, I made this mistake as well. You may have an instance where you need to create item list table to add pro grammatically. I highly recommend using JSON object to create your item look up table.

  4. User selected items will ALWAYS be at line number 1 of the cart. The order of items may change after you've been to check out summary page but when it's added to the cart by the user; not script, it'll always be on the first line of item list.

  5. Jason K's trick 1: nlapiSelectLineItem results in an error if there's uncommitted values in the item list. He recommended to commit all items before adding new.
    I especially had issues with this. My work around was to use nlapiInsertLineItem with nlapiSetCurrentLinetItemValue method.

  6. Not sure if this will apply to everyone but IF you end up getting NetSuite Script Notice page during your execution of cart script or you end up getting Webstore maint. screen, it usually means there is an error in your script. For me, it was infinite loop issue. If you see your form re-initializing, it usually indicates error.

  7. Jason K's trick 2: Using global variable in the cart script sometimes fails. The workaround is to create custom body field on your form and use that as temporary global field that you set and get using nlapiGetFieldValue() call.
  8. Jason K's trick 3: When doing extra commit, always check for valid item in the current row. 
Some quick sample code from Jason K on safeSelectLine and safeSelectNewLine

** notEmpty is a custom function which simply checks to see if passed in value is null or empty string

safeSelectNewLine function:
function safeSelectNewLineItem() {
  if (notEmpty(nlapiGetCurrentLineItemValue('item','item'))) {
    nlapiCommitLineItem('item');
  }
  nlapiSelectNewLineItem('item');
}
safeSelectLine function:
function safeSelectLineItem(itemLine) {
  if (notEmpty(nlapiGetCurrentLineItemValue('item','item'))) {
    nlapiCommitLineItem('item');
  }
  nlapiSelectLineItem('item', itemLine);
}
Most important lesson I've learned is that cart script behaves differently in webstore. Do test your code on the external form but be extra careful not to fully trust the result. When testing on webstore, keep close eye on your log execution files. If you ever see page init more than once, you know you have an error somewhere.

As I mentioned before on my previous post, turning on logging on webstore will slow down your cart since it's calling to your external suitelet so keep that in mind as well. 

Hope this helps you. Let me know if you get stuck. I'll try my best to help you out.

Saturday, May 14, 2011

How to debug Netsuite Webstore Scriptable Cart

We've MOVED!!!! www.codeboxllc.com/ksc


Notice:
Blogspot had issues with their server and post I originally wrote got deleted. I do apologize for missing link:

Important Update on this Post: 5/17/2011:
nlapiRequestURL() eats up API Governance meter by 10 points. Testing on External Form, if you have this turned on, you only have 1000 limit. On Webstore, you seem to have 2147483647. Don't ask me where that number came from.

So, Here I go again. How DO you debug scriptable cart executing on webstore? The script itself is attached to the External Sales Order form you create which implies is client level script. You can't use Firebug to step through it either.So how do you debug when your script is not returning the results you want?

I began using this workaround and it has helped me alot.
Workaround: Create Suitelet (Available without Login) to track printing of debug messages and call it using nlapiRequestURL() from your scriptable cart script.

Write Suitelet Script: Save as "sl_writelog.js" and push out to Netsuite 
** Please note, for simplicity, I've written my script to use GET event.
function slExecLog(request, response){
  if (request.getMethod() == 'GET') {
    var log = filterUserInput(request.getParameter('log'));
    var title=filterUserInput(request.getParameter('title'));
    writeLog('DEBUG',title,log);
    response.write('called back');
  }
}
Deploy your script:
  1. Login to Netsuite and go to Setup > Customization > Scripts > Click New
  2. Select Suitelet as script type
  3. Provide Name and ID for this script.
  4. Under Scripts tab, select "sl_writelog.js" for Script File and "slExecLog" as Function
  5. Select "Save and Deploy" option.
  6. Provide Name and ID for this script deployment
  7. Check "Available Without Login" 
  8. Select GET Request as Event Type.
    If you choose to use Post, you should change your script to check for POST and also select POST Request as Event Type
  9. Under Audience tab, select "All Roles"
  10. Save
Once you've deployed your script, copy the External URL for this deployment. According to NetSuite documentation, nlapiRequestURL() does NOT send User Session information. 

Link to your Suitelet from Scriptable cart script:
Open your scriptable cart script and create a function which will call your suitelet. This is how I did it:
Please note that anything enclosed in [ and ] is to be replaced by your code including the brackets.
function wslog(_txt) {
  if (!_txt) {
    return;
  }
  var loginUrl = '[External URL for your Suitelet]&title=[Value of title]&log='+_txt;
  if (wsdebug) {
    nlapiRequestURL(loginUrl, null, null);
    return;
  }else{
    alert(_txt);
  }
}
You will notice above that I check for wsdebug value. This is global boolean value I created so that I can turn on/off calling of my debug suitelet.
When I'm testing on the form, I set this value to false so that I can see the alert messages. Testing/deployment on webstore, I set this value to true.
Check your debug messages:
Once everything is doen, go to your Webstore and add items to your cart so that your scriptable cart script will fire.
To check the log messages, open your Suitelet script record and click on Execution Log.