I've made a basic script, user event before submit that runs on sales orders. We have a custom markup field we use for certain customers, so it just applies a cost + x% markup to all items. The script first looks for an average cost and, if it has one it uses that value. If not, it uses purchase price from the item record. What's happening is, the script changes the cost estimate type to average cost. In the ui, this would automatically load the new est. unit cost from the item record for the average cost (for that particular location). However, in the user event script, it doesn't seem to work. After I sent the cost estimate type and pull the unit cost, it still uses the default purchase price cost estimate type value.
If you save the sales order and run the script again it works as it's already using the average cost value. Any ideas on how to make this work, i.e. check for location average cost value before submit? Here is the current code (the code IS Before Submit even the the name of function says otherwise):
function afterSubmit_setASIPrice(type){
var context = nlapiGetContext();
if((type== 'create' || type=='edit') && context.getExecutionContext() == 'userinterface'){
var asiPriceUpdate = nlapiGetFieldValue('custbody_asi_price_update');
if (asiPriceUpdate == "T") {
var itemCount = nlapiGetLineItemCount('item');
var cost = 0.0;
var markup = parseFloat(nlapiGetFieldValue('custbody_asi_solaris_markup'));
markup = markup / 100;
if (itemCount > 0) {
for (var j = 1; j <= itemCount; j++) {
nlapiSelectLineItem('item', j);
id = nlapiGetLineItemValue('item', 'item', j);
if (id != '' && (id!='-3') && (id!='4686')) {
quantity = nlapiGetCurrentLineItemValue('item', 'quantity');
if ((id !='-3') && (id !='4686')) {
nlapiSetCurrentLineItemValue('item', 'costestimatetype', 'AVGCOST', true, true);
}
cost = nlapiGetLineItemValue('item', 'costestimaterate', j);
nlapiLogExecution('debug','cost', cost);
if (cost == '0.00' || cost == '') {
nlapiSetCurrentLineItemValue('item', 'costestimatetype', 'PURCHPRICE', true, true);
cost = nlapiGetLineItemValue('item', 'costestimaterate', j); // why is this here?
cost = nlapiLookupField('item', id, 'cost');
}
cost = parseFloat(cost);
price = cost * markup + cost;
total = quantity * price;
nlapiSetCurrentLineItemValue('item', 'price', '-1', true);
nlapiSetCurrentLineItemValue('item', 'rate', price, true);
//nlapiSetCurrentLineItemValue('item', 'amount', total, true);
nlapiCommitLineItem('item');
nlapiSetFieldValue('custbody_asi_price_update', 'F');
nlapiLogExecution("debug", "J, ID, Rate, Amount, Cost", j + ", " + id + ", " + price + ", " + total + ", " + cost);
}
}
}
}
}
}