Change Opportunity Status based on Estimate
Hi,
I created UE script on afterSubmit function to get status for all Quotes/Estimates that related to Opportunity and based on each Quote/Estimate status will decide to close opportunity or still it open, but the status after changed to Closed it was back to Issued Quote.
and this is script
/**
*@NApiVersion 2.1
*@NScriptType UserEventScript
*/
define([‘N/record’, ‘N/search’], function (record, search) {
function afterSubmit(context) {
try {
if (context.type == ‘edit’) {
let objNewRecord = context.newRecord;
let objOldRecord = context.oldRecord;
let intRecordId = objNewRecord.id;
let intNewQuoteStatusReason = objNewRecord.getValue(‘custbody_asafe_status_reasons’);
let intOldQuoteStatusReason = objOldRecord.getValue(‘custbody_asafe_status_reasons’);
if (intNewQuoteStatusReason != intOldQuoteStatusReason) {
let intOppId = objNewRecord.getValue(‘opportunity’);
let objLoadOppRecord = record.load({
type: record.Type.OPPORTUNITY,
id: intOppId,
isDynamic: true
});
let intLineCount = objLoadOppRecord.getLineCount(‘estimates’);
let arrQuoteStatus = [];
let blnWon = false;
let blnLose = false;
let blnElse = false;
if (intLineCount > 0) {
for (let i = 0; i < intLineCount; i++) {
let intQuoteId = objLoadOppRecord.getSublistValue({
sublistId: ‘estimates’,
fieldId: ‘id’,
line: i
});
if (intQuoteId == intRecordId) {
continue;
}
else {
let intQuoteStatusReason = getQuotesData(intQuoteId);
arrQuoteStatus.push(intQuoteStatusReason);
}
}
arrQuoteStatus.push(intNewQuoteStatusReason);
for (let j = 0; j < arrQuoteStatus.length; j++) {
if (arrQuoteStatus[j] == 8) {
blnWon = true;
}
else if (arrQuoteStatus[j] == 11) {
blnLose = true;
}
else {
blnElse = true;
}
}
if (blnWon == true && blnLose == true && blnElse == false) {
log.debug(‘won status’, blnWon);
objLoadOppRecord.setValue({
fieldId: ‘winlossreason’,
value: 8,
// ignoreFieldChange: true
});
objLoadOppRecord.setValue({
fieldId: ‘probability’,
value: 100,
// ignoreFieldChange: true
});
}
else if (blnWon == false && blnLose == true && blnElse == false) {
log.debug(‘lose status’, blnLose);
objLoadOppRecord.setValue({
fieldId: ‘winlossreason’,
value: 11,
// ignoreFieldChange: true
});
objLoadOppRecord.setValue({
fieldId: ‘probability’,
value: 0,
// ignoreFieldChange: true
});
}
else if (blnWon == false && blnLose == false && blnElse == true) {
log.debug(‘else status’, ‘Not Won/Lose’);
}
}
objLoadOppRecord.save();
}
}
} catch (errAfterSubmit) {
log.debug(‘errAfterSubmit’, errAfterSubmit);
}
}
function getQuotesData(intQuoteRecordId) {
try {
if (intQuoteRecordId) {
let objQuoteSearch = search.lookupFields({
type: search.Type.ESTIMATE,
id: intQuoteRecordId,
columns: [‘custbody_asafe_status_reasons’]
});
let intQuoteStatusReason = objQuoteSearch[‘custbody_asafe_status_reasons’][0].value;
return intQuoteStatusReason;
}
} catch (errGetQuotesData) {
log.debug(‘errGetQuotesData’, errGetQuotesData);
}
}
return {
afterSubmit: afterSubmit
}
});