Sunday 24 February 2019

25th Feb-SendPAcode

/*
Author :  Krishna Yerru
Date Created : 2/25/2018
Purpose : SMB Lightning Day 2
Original Project/Case/Epic : SP-2831
Test Class: SP:830-SendPACodeController_Test
Apex class:SendPACodeController
Change History :
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Change Version   Name              Date                    Task/Case#                 Description
---------------------------------------------------------------------------------------------------------------------------------------------------------------------

*/
@istest
global class SendPACodeController_Test{
    @testSetup
        static void setup() {
          try{ 
                User RSAUSER = [select name,id from User where profile.name='RSA Telesales User' and isactive = true LIMIT 1];
                System.runAs(RSAUSER){
               
                //Creating Account
                Account a = new Account();
                a.name = 'test';
                insert a;

                //Creating Bank
                Bank__c b = new Bank__c(
                    name = 'CITI',
                    street__c = '123 Main Street',
                    city__c = 'My Town',
                    state__c = 'PA',
                    zip__c = '17000',
                    country__c = 'United States',
                    D_U_N_S_Number__c = '123456789'
                );
                insert b;
               
                //Creating Campaign
                Campaign c = new Campaign(
                    name = '58001-FordDealr',
                    StartDate = Date.newInstance(2009, 3, 20),
                    Sub_Type__c = 'Lead Generation',
                    Tactic__c = 'Contest',
                    Type = 'Existing Client'
                );
                insert c;
               
                //Creating User name and password data and custom settings data
                Blob key = Blob.valueOf(System.Label.SecPSD);
                // Generate the data to be encrypted.
                Blob data = Blob.valueOf('apexapiuser@firstdata.com');
                String encodeddata =  EncodingUtil.base64encode(data);
                System.debug('encodeddata ' +encodeddata);
                Blob ecdata = Blob.valueOf(encodeddata);
                // Encrypt the data and have Salesforce.com generate the initialization vector
                Blob encryptedData = Crypto.encryptWithManagedIV('AES256', key, ecdata);
                System.debug('encryptedData ' +encryptedData);
                String encodeddata1 =  EncodingUtil.base64encode(encryptedData);
                System.debug('encodeddata1 ' +encodeddata1);
               
                Blob data1 = Blob.valueOf('aTest1234!');
                String encodeddata3 =  EncodingUtil.base64encode(data1);
                System.debug('encodeddata3 ' +encodeddata3);
                Blob ecdata1 = Blob.valueOf(encodeddata3);
                // Encrypt the data and have Salesforce.com generate the initialization vector
                Blob encryptedData1 = Crypto.encryptWithManagedIV('AES256', key, ecdata1);
                System.debug('encryptedData1 ' +encryptedData1);
                String encodeddata2 =  EncodingUtil.base64encode(encryptedData1);
                System.debug('encodeddata2 ' +encodeddata2);
               
                List<Iwerk_User_Credentials__c> lstIwer = new List<Iwerk_User_Credentials__c>();
               
                Iwerk_User_Credentials__c usrs = new Iwerk_User_Credentials__c(
                Name='UserDetails',
                Username__c = encodeddata1,
                Password__c = encodeddata2,
                WebserviceURL__c = 'http://stage.fpol.werkbench.com/dealerenrollment.asmx',
                Location__c = 'SANDBOX');
               
                lstIwer.add(usrs);
               
                Iwerk_User_Credentials__c usrs2 = new Iwerk_User_Credentials__c(
                Name='UserDetailsProd',
                Username__c = encodeddata1,
                Password__c = encodeddata2,
                WebserviceURL__c = 'https://fpol.iwerkwebservices.com/dealerenrollment.asmx',
                Location__c = 'PRODUCTION');
               
                lstIwer.add(usrs2);
               
                insert lstIwer;
               
                //Getting or fetching record type data
                RecordType opprect1 = [select name,id from RecordType where name = 'RSAG New Account' LIMIT 1];
               
                //Creating Opportunity List and Opportunity data
                List<opportunity> oppList=new List<opportunity>();
               
                //Opporutnity with not valid data
                 Opportunity o = new Opportunity(
                    Name = 'Test Opp - Test Product1',
                    RecordTypeId = opprect1.id,
                    Type = 'New Business',
                    StageName = 'Prospecting',
                    CloseDate = Date.today().addYears(1),
                    Revenue_Start_Date__c = Date.newInstance(2009, 3, 20),
                    Contract_Term__c = '12',
                    QC_Status_c__c = 'New',
                    CurrencyISOCode='USD',
                    Referral_ID__c = '54123',
                    Bank_Lookup__c = b.id,
                    AccountId = a.id);                 
                oppList.add(o);
               
                //Opportunity with valid Parts Data
                Opportunity o1 = new Opportunity(
                    Name = 'Test Opp - Test Parts',
                    RecordTypeId = opprect1.id,
                    Type = 'New Business',
                    StageName = 'Prospecting',
                    CloseDate = Date.today().addYears(1),
                    Revenue_Start_Date__c = Date.newInstance(2009, 3, 20),
                    Contract_Term__c = '12',
                    QC_Status_c__c = 'New',
                    CurrencyISOCode='USD',
                    Referral_ID__c = '54123',
                    Branch_Name__c='Ford GTB',
                    Leadsource='Web',//need to change LeadSource to web
                    Merchant_MID__c = '12345678901',
                    Bank_Lookup__c = b.id,
                    AccountId = a.id);                 
                   
                    oppList.add(o1);
               
                //Opportunity with valid Service Data                 
                Opportunity o2 = new Opportunity(
                    Name = 'Test Opp - Test Service',
                    RecordTypeId = opprect1.id,
                    Type = 'New Business',
                    StageName = 'Prospecting',
                    CloseDate = Date.today().addYears(1),
                    Revenue_Start_Date__c = Date.newInstance(2009, 3, 20),
                    Contract_Term__c = '12',
                    QC_Status_c__c = 'New',
                    CurrencyISOCode='USD',
                    Referral_ID__c = '54123',
                    Branch_Name__c='',
                    Leadsource='Web',//need to change LeadSource to web
                    Merchant_MID__c = '12345678901',                       
                    MRC_Code__c = c.id,
                    Bank_Lookup__c = b.id,
                    AccountId = a.id);
                   
                    oppList.add(o2);

Opportunity o3 = new Opportunity(
                    Name = 'Test Opp - Test Service',
                    RecordTypeId = opprect1.id,
                    Type = 'New Business',
                    StageName = 'Prospecting',
                    CloseDate = Date.today().addYears(1),
                    Revenue_Start_Date__c = Date.newInstance(2009, 3, 20),
                    Contract_Term__c = '12',
                    QC_Status_c__c = 'New',
                    CurrencyISOCode='USD',
                    Referral_ID__c = '54123',
                    Branch_Name__c='',
                    Leadsource='Web',//need to change LeadSource to web
                    Merchant_MID__c = '12345678901',                       
                    MRC_Code__c = c.id,
                    //Bank_Lookup__c = b.id,
                    AccountId = a.id);
                   
                    oppList.add(o3);

Opportunity o4 = new Opportunity(
                    Name = 'Test Opp - Test Service',
                    RecordTypeId = opprect1.id,
                    Type = 'New Business',
                    StageName = 'Prospecting',
                    CloseDate = Date.today().addYears(1),
                    Revenue_Start_Date__c = Date.newInstance(2009, 3, 20),
                    Contract_Term__c = '12',
                    QC_Status_c__c = 'New',
                    CurrencyISOCode='USD',
                    //Referral_ID__c = '54123',
                    Branch_Name__c='',
                    Leadsource='Web',//need to change LeadSource to web
                    Merchant_MID__c = '12345678901',                       
                    MRC_Code__c = c.id,
                    Bank_Lookup__c = b.id,
                    AccountId = a.id);
                   
                    oppList.add(o4);

                       
                    Test.startTest();
                   
                    insert oppList;
                    System.debug('Parts Oppor Test' + o1);
                    System.assertNotEquals(null, o.id);
                    System.assertNotEquals(null, o1.id);
                    System.assertNotEquals(null, o2.id);
                    Test.stopTest();
             
                }
            }
            Catch(Exception e){
                System.debug('Exception ' + e.getMessage());
            }
        }
       
        static TestMethod void testmethod1(){
            String paCode='78948';
            String recordtype='RSAG New Account';
            String partner='CITI';
            test.starttest();
            String output=SendPACodeController.validateOppDetailsForCallout(paCode,recordtype,partner);
            System.assertequals('Error||At present, there is no Parts MID available for this PA Code. \n\nAt present, there is no Service MID available for this PA Code. \n\n',output);
            test.stopTest();
       }
       
        static TestMethod void testFordPartWS(){           
            String paCode='54123';
            String recordtype='RSAG New Account';
            String partner='CITI';                     
            String servMID = '';           
            String servOppID = '';
            System.debug('');
            //need to change LeadSource to web
            Opportunity Oppr = [Select id, name, Merchant_MID__c, recordtypeId FROM Opportunity WHERE Referral_ID__c = :paCode and RecordTypename__c = :recordtype and Bank_Lookup__r.name=:partner and Branch_Name__c='Ford GTB' and Leadsource='Web' and StageName != 'closed lost' order by lastmodifieddate desc LIMIT 1];
           
            String partsOppID = Oppr.Id;
            String partsMID = '12345678901';

            test.starttest();
            String output = SendPACodeController.validateOppDetailsForCallout(paCode, oppr.recordtypeId,partner);
            try{
                WSiwerkCom.UserAuthentication wsusr = new WSiwerkCom.UserAuthentication();
                WSiwerkCom.DealerEnrollmentSoap wsptr = new WSiwerkCom.DealerEnrollmentSoap();
               
                Test.setMock(WebServiceMock.class, new PennyTestMock());
               
                Boolean result = wsptr.PennyTestRequest(pacode,partsMID, servMID,wsusr);
               
                System.assertEquals(true, result);
                string resultOpprPart = SendPACodeController.makeCallout(paCode, partsMID, servMID, partsOppID, servOppID);
            }
            Catch(Exception e){
                System.debug('Exception occured ' +e.getStackTraceString());
            }
           // System.assertEquals('Success', resultOpprPart);
            test.stopTest();
       }
     
       static TestMethod void testFordServiceWS(){           
            String paCode='54123';
            String recordtype='RSAG New Account';
            String partner='CITI';
            String partsOppID = '';
            String partsMID = '';
            Opportunity Oppr = [Select id,recordtypeId, name, Referral_ID__c,StageName,Merchant_MID__c, Bank_Lookup__r.name,Initial_Call_Complete__c  FROM Opportunity WHERE Referral_ID__c = :paCode and RecordTypename__c = :recordtype and Bank_Lookup__r.name=:partner and Branch_Name__c!= 'Ford GTB' AND MRC_Code__r.name ='58001-FordDealr'  and StageName!='closed lost' order by lastmodifieddate desc LIMIT 1];
            String servOppID = Oppr.Id;
            String servMID = '12345678901';
           
            test.starttest();
            String output = SendPACodeController.validateOppDetailsForCallout(paCode,Oppr.recordtypeId,partner);
            try{
                WSiwerkCom.UserAuthentication wsusr = new WSiwerkCom.UserAuthentication();
                WSiwerkCom.DealerEnrollmentSoap wsptr = new WSiwerkCom.DealerEnrollmentSoap();
               
                Test.setMock(WebServiceMock.class, new PennyTestMock());
               
                Boolean result = wsptr.PennyTestRequest(pacode,partsMID, servMID,wsusr);
               
                System.assertEquals(true, result);
                string resultOpprServ = SendPACodeController.makeCallout(paCode, partsMID, servMID, partsOppID, servOppID);
            }
            Catch(Exception e){
                System.debug('Exception occured ' +e.getStackTraceString());
            }
           
           // System.assertEquals('Success', resultOpprServ);
            test.stopTest();
       }
     
   static TestMethod void testFordServiceWS_pacodechk(){           
            String paCode='';
            String recordtype='RSAG New Account';
            String partner='CITI';
            String partsOppID = '';
            String partsMID = '';
            Opportunity Oppr = [Select id,recordtypeId, name, Referral_ID__c,StageName,Merchant_MID__c, Bank_Lookup__r.name,Initial_Call_Complete__c  FROM Opportunity WHERE Referral_ID__c = :paCode and RecordTypename__c = :recordtype and Bank_Lookup__r.name=:partner and Branch_Name__c!= 'Ford GTB' AND MRC_Code__r.name ='58001-FordDealr'  and StageName!='closed lost' order by lastmodifieddate desc LIMIT 1];
            String servOppID = Oppr.Id;
            String servMID = '12345678901';
           
            test.starttest();
Opportunity getOppDatais=SendPACodeController.getOppData(Oppr.Id);
string valdOpprServ = SendPACodeController.ProcessPACode(servOppID);
            String output = SendPACodeController.validateOppDetailsForCallout(paCode,Oppr.recordtypeId,partner);
            try{
                WSiwerkCom.UserAuthentication wsusr = new WSiwerkCom.UserAuthentication();
                WSiwerkCom.DealerEnrollmentSoap wsptr = new WSiwerkCom.DealerEnrollmentSoap();
               
                Test.setMock(WebServiceMock.class, new PennyTestMock());
               
                Boolean result = wsptr.PennyTestRequest(pacode,partsMID, servMID,wsusr);
               
                System.assertEquals(true, result);
                string resultOpprServ = SendPACodeController.makeCallout(paCode, partsMID, servMID, partsOppID, servOppID);
            }
            Catch(Exception e){
                System.debug('Exception occured ' +e.getStackTraceString());
            }
            test.stopTest();
       }
 
   static TestMethod void testFordServiceWS_Partnerchk(){           
            String paCode='54123';
            String recordtype='RSAG New Account';
            String partner='';
            String partsOppID = '';
            String partsMID = '';
            Opportunity Oppr = [Select id,recordtypeId, name, Referral_ID__c,StageName,Merchant_MID__c, Bank_Lookup__r.name,Initial_Call_Complete__c  FROM Opportunity WHERE Referral_ID__c = :paCode and RecordTypename__c = :recordtype and Bank_Lookup__r.name=:partner and Branch_Name__c!= 'Ford GTB' AND MRC_Code__r.name ='58001-FordDealr'  and StageName!='closed lost' order by lastmodifieddate desc LIMIT 1];
            String servOppID = Oppr.Id;
            String servMID = '12345678901';
           
            test.starttest();
Opportunity getOppDatais=SendPACodeController.getOppData(Oppr.Id);
string valdOpprServ = SendPACodeController.ProcessPACode(servOppID);
            String output = SendPACodeController.validateOppDetailsForCallout(paCode,Oppr.recordtypeId,partner);
            try{
                WSiwerkCom.UserAuthentication wsusr = new WSiwerkCom.UserAuthentication();
                WSiwerkCom.DealerEnrollmentSoap wsptr = new WSiwerkCom.DealerEnrollmentSoap();
               
                Test.setMock(WebServiceMock.class, new PennyTestMock());
               
                Boolean result = wsptr.PennyTestRequest(pacode,partsMID, servMID,wsusr);
               
                System.assertEquals(true, result);
                string resultOpprServ = SendPACodeController.makeCallout(paCode, partsMID, servMID, partsOppID, servOppID);
            }
            Catch(Exception e){
                System.debug('Exception occured ' +e.getStackTraceString());
            }
            test.stopTest();
       }
     
       static TestMethod void testFordPartsServiceWS(){           
            String paCode='54123';
            String recordtype='RSAG New Account';
            String partner='CITI';         
           
            Opportunity Oppr = [Select id,recordtypeId, name, Referral_ID__c,StageName,Merchant_MID__c, Bank_Lookup__r.name,Initial_Call_Complete__c  FROM Opportunity WHERE Referral_ID__c = :paCode and RecordTypename__c = :recordtype and Bank_Lookup__r.name=:partner and Branch_Name__c!= 'Ford GTB' AND MRC_Code__r.name ='58001-FordDealr'  and StageName!='closed lost' order by lastmodifieddate desc LIMIT 1];
            String servOppID = Oppr.Id;
            String servMID = '12345678901';
            //need to change LeadSource to web
            Opportunity OpprParts = [Select id, name, Merchant_MID__c, recordtypeId FROM Opportunity WHERE Referral_ID__c = :paCode and RecordTypename__c = :recordtype and Bank_Lookup__r.name=:partner and Branch_Name__c='Ford GTB' and Leadsource='Web' and StageName != 'closed lost' order by lastmodifieddate desc LIMIT 1];
            String partsOppID = OpprParts.Id;
            String partsMID = '12345678901';
           
            test.starttest();
            String output = SendPACodeController.validateOppDetailsForCallout(paCode,OpprParts.recordtypeId,partner);
            try{
                WSiwerkCom.UserAuthentication wsusr = new WSiwerkCom.UserAuthentication();
                WSiwerkCom.DealerEnrollmentSoap wsptr = new WSiwerkCom.DealerEnrollmentSoap();
               
                Test.setMock(WebServiceMock.class, new PennyTestMock());
               
                Boolean result = wsptr.PennyTestRequest(pacode,partsMID, servMID,wsusr);
               
                System.assertEquals(true, result);
                string resultOppPartServ = SendPACodeController.makeCallout(paCode, partsMID, servMID, partsOppID, servOppID);
            }
            Catch(Exception e){
                System.debug('Exception occured ' +e.getStackTraceString());
            }
            test.stopTest();
       }
       //ProcessPACode
      static TestMethod void testProcessPACode(){
            String paCode='54123';
            String recordtype='RSAG New Account';
            String partner='CITI';         
            test.starttest();
            Opportunity Oppr = [Select id,recordtypeId, name, Referral_ID__c,StageName,Merchant_MID__c, Bank_Lookup__r.name,Initial_Call_Complete__c  FROM Opportunity WHERE Referral_ID__c = :paCode and RecordTypename__c = :recordtype and Bank_Lookup__r.name=:partner and Branch_Name__c!= 'Ford GTB' AND MRC_Code__r.name ='58001-FordDealr'  and StageName!='closed lost' order by lastmodifieddate desc LIMIT 1];
            String servOppID = Oppr.Id;
            String servMID = '12345678901';
            //need to change LeadSource to web
            Opportunity OpprParts = [Select id, name, Merchant_MID__c, recordtypeId FROM Opportunity WHERE Referral_ID__c = :paCode and RecordTypename__c = :recordtype and Bank_Lookup__r.name=:partner and Branch_Name__c='Ford GTB' and Leadsource='Web' and StageName != 'closed lost' order by lastmodifieddate desc LIMIT 1];
            ID partsOppID = OpprParts.Id;
            String partsMID = '12345678901';
            String output = SendPACodeController.ProcessPACode(partsOppID);
System.assertNotEquals(null, OpprParts.id);
             test.stopTest();
      }
     
      static TestMethod void testUpdateOpp(){
            String paCode='54123';
            String recordtype='RSAG New Account';
            String partner='CITI';         
            test.starttest();
            Opportunity Oppr = [Select id,recordtypeId, name, Referral_ID__c,StageName,Merchant_MID__c, Bank_Lookup__r.name,Initial_Call_Complete__c  FROM Opportunity WHERE Referral_ID__c = :paCode and RecordTypename__c = :recordtype and Bank_Lookup__r.name=:partner and Branch_Name__c!= 'Ford GTB' AND MRC_Code__r.name ='58001-FordDealr'  and StageName!='closed lost' order by lastmodifieddate desc LIMIT 1];
            String servOppID = Oppr.Id;
            String servMID = '12345678901';
            //need to change LeadSource to web
            Opportunity OpprParts = [Select id, name, Merchant_MID__c, recordtypeId FROM Opportunity WHERE Referral_ID__c = :paCode and RecordTypename__c = :recordtype and Bank_Lookup__r.name=:partner and Branch_Name__c='Ford GTB' and Leadsource='Web' and StageName != 'closed lost' order by lastmodifieddate desc LIMIT 1];
            String partsOppID = OpprParts.Id;
            String partsMID = '12345678901';
            String nullval='';
             SendPACodeController.UpdateOpp(partsOppID,servOppID,true);
             SendPACodeController.UpdateOpp(nullval,servOppID,true);
             SendPACodeController.UpdateOpp(partsOppID,nullval,true);
System.assertNotEquals(null, OpprParts.id);
             test.stopTest();
      }
}



*****************

({
    doInit : function(component, event, helper) {
        
        var oppid;
        var initial;
        var msg = '';
var msgOppVal = '';
        var pMid='';
        var sMid='';
        var partsOppID='';
        var servOppID='';
        var partValue;
        var servValue;
        var err = false;
        var retValue;
        var oppPacode;
        var action = component.get("c.ProcessPACode");
        
        action.setParams({
            "oppId": component.get("v.recordId")
        });
        
        action.setCallback(this, function(response) {            
            var state = response.getState();
            if (state === "SUCCESS") {
                var resp = response.getReturnValue();
                if(resp=='This functionality applies only to Ford Dealers' ||
                   resp=='The Opportunity has no PA Code available. Call cannot be made.')
                { 
msgOppVal=resp;
component.set('v.message', msgOppVal);
component.set('v.Iwerkscall', false);
/*msg =resp; 
alert(msg);
                    var showToast=$A.get('e.force:showToast');                
                    showToast.setParams({
                        type : 'error',
                        message : msg
                    });
                    showToast.fire();
                    $A.get("e.force:closeQuickAction").fire();
*/
                }
                else{
                    console.log('@@resp : ' + resp);
                    retValue = resp.split("||");
                    console.log('@@retValue : ' + retValue.length);
                    if(retValue != 'undefined')
                    {
                        if(retValue.length > 0)
                        {
                            if(retValue[0] == 'Valid')
                            {
                                console.log('@@Valid : ' + retValue[0]);
                                if(retValue.length == 4){
                                    pMid = retValue[1].split(":")[1];
                                    component.set("v.partsMID", pMid);
                                    partsOppID = retValue[1].split(":")[2];
                                    component.set("v.partsOppID", partsOppID);
                                    
                                    oppPacode = retValue[1].split(":")[3];
                                    component.set("v.PaCode", oppPacode);
                                    
                                    sMid = retValue[2].split(":")[1];
                                    component.set("v.servMID", sMid);
                                    servOppID=retValue[2].split(":")[2];
                                    component.set("v.servOppID", servOppID);
                                    console.log('@@oppPacode 0: ' + oppPacode);
                                    msg = 'The below details will be sent to iWerks. \n\n PA Code: ' + oppPacode + ' , ' +
                                        'Parts MID: ' + pMid + ' & Service MID: ' + sMid + '\n\n Do you want to continue sending the details?';
                                    component.set('v.message', msg);
                                }
                                else if(retValue.length == 3){
                                    if(retValue[1].split(":")[0] != 'S')
                                    {
msgOppVal=retValue[retValue.length - 1];
component.set('v.message', msgOppVal);
/*
alert(retValue[retValue.length - 1]);
                                        var showToast = $A.get('e.force:showToast');                
                                        showToast.setParams({
                                            type : 'warning',
                                            message : retValue[retValue.length - 1]   
                                        });
                                        showToast.fire();
                                        */
                                        console.log('@@retValue arr: ' + retValue[1].split(":"));
                                        
                                        pMid = retValue[1].split(":")[1];
component.set("v.partsMID", pMid);
                                        partsOppID = retValue[1].split(":")[2];
component.set("v.partsOppID", partsOppID);
                                        oppPacode = retValue[1].split(":")[3];
component.set("v.PaCode", oppPacode);
                                        console.log('@@oppPacode 1: ' + oppPacode);
                                        msg = msgOppVal+'\n\n'+ 'Now, the below details will be sent to iWerks. \n\n PA Code: ' + oppPacode + ' & ' +
                                            'Parts MID: ' + pMid + '\n\n Do you want to continue sending the details?';
                                        component.set('v.message', msg);
                                    }
                                    else if(retValue[1].split(":")[0] == 'S')
                                    {
msgOppVal=retValue[retValue.length - 1];
component.set('v.message', msgOppVal);
/*
alert(retValue[retValue.length - 1]);
                                        var showToast = $A.get('e.force:showToast');                
                                        showToast.setParams({
                                            type : 'warning',
                                            message : retValue[retValue.length - 1]
                                        });
                                        showToast.fire();
                                        */
                                        sMid = retValue[1].split(":")[1];
component.set("v.servMID", sMid);
                                        servOppID = retValue[1].split(":")[2];
component.set("v.servOppID", servOppID);
                                        oppPacode = retValue[1].split(":")[3];
component.set("v.PaCode", oppPacode);
                                        console.log('@@oppPacode 2: ' + oppPacode);
                                        msg = msgOppVal+ '\n\n'+ 'Now, the below details will be sent to iWerks. \n\n PA Code: ' + oppPacode + ' & ' +
                                            'Service MID: ' + sMid + '\n\n Do you want to continue sending the details?';
                                        component.set('v.message', msg);
                                    }
                                }
                                    else if(retValue.length == 2){
                                        if(retValue[1].split(":")[0] != 'P' && retValue[1].split(":")[0] != 'S'){
msgOppVal=retValue[retValue.length - 1];
component.set('v.message', msgOppVal);
/*
alert(retValue[retValue.length - 1]);
var showToast = $A.get('e.force:showToast');                
                                            showToast.setParams({
                                                type : 'warning',
                                                message : retValue[retValue.length - 1]
                                            });
                                            showToast.fire();
*/
                                        }
                                        if(retValue[1].split(":")[0] == 'P')
                                        {
                                            pMid = retValue[1].split(":")[1];
component.set("v.partsMID", pMid);
                                            partsOppID = retValue[1].split(":")[2];
component.set("v.partsOppID", partsOppID);
                                            oppPacode = retValue[1].split(":")[3];
component.set("v.PaCode", oppPacode);
                                            console.log('@@oppPacode 3: ' + oppPacode);
                                            msg = 'The below details will be sent to iWerks. \n\n PA Code: ' + oppPacode + ' & ' +
                                                'Parts MID: ' + pMid + '\n\n Do you want to continue sending the details?';
                                            component.set('v.message', msg);
                                        }
                                        else if(retValue[1].split(":")[0] == 'S')
                                        {
                                            sMid = retValue[1].split(":")[1];
component.set("v.servMID", sMid);
                                            servOppID = retValue[1].split(":")[2];
component.set("v.servOppID", servOppID);
                                            oppPacode = retValue[1].split(":")[3];
component.set("v.PaCode", oppPacode);
                                            console.log('@@oppPacode 4: ' + oppPacode);
                                            msg = 'The below details will be sent to iWerks. \n\n PA Code: ' + oppPacode + ' & ' +
                                                'Service MID: ' + sMid + '\n\n Do you want to continue sending the details?';
                                            component.set('v.message', msg);
                                        }
                                    }
                                //To do : The commented code will go in
                            }
                            else
                            {
msgOppVal=retValue[1];
component.set('v.message', msgOppVal);
component.set('v.Iwerkscall', false);
console.log('@@opp Not valid: ' + msgOppVal);
/*
alert(retValue[1]);
var showToast = $A.get('e.force:showToast');                
                                showToast.setParams({
                                    type : 'warning',
                                    message : retValue[1]
                                });
                                showToast.fire();
                                $A.get("e.force:closeQuickAction").fire();
*/
                            }
                        }
                    }
                }
            }
            else{
msgOppVal='No response from the Server. Please try again.';
component.set('v.message', msgOppVal);
component.set('v.Iwerkscall', false);
/*
alert('No response from the Server. Please try again.');
msg = 'No response from the Server. Please try again.';
                var showToast=$A.get('e.force:showToast');                
                showToast.setParams({
                    type : 'error',//success
                    message : msg
                });
                showToast.fire();
                $A.get("e.force:closeQuickAction").fire(); 
*/
            }
        });
        // Invoke the service
        $A.enqueueAction(action);
    },
    
    //This method closes the lightning modal
    closeComponent : function(cmp, evt, helper){
var msg = 'You have selected to stop';
cmp.set('v.message', msg);
        $A.get("e.force:closeQuickAction").fire();
    },
    
    FinalCallout : function(cmp, evt, helper)
    {
        var action = cmp.get("c.makeCallout");
        action.setParams({
            "paCode": cmp.get("v.PaCode"),
"partsMID": cmp.get("v.partsMID"),
"servMID": cmp.get("v.servMID"),
"partsOppID": cmp.get("v.partsOppID"),
"servOppID": cmp.get("v.servOppID")
        });
        
        action.setCallback(this, function(response) {            
            var state = response.getState();
            if (state === "SUCCESS") {
                var resp = response.getReturnValue();
                console.log('Makecallout  ' + resp);
var msg='';
msg = 'You have confirmed to submit the Penny Test request';
cmp.set('v.message', msg);
if(resp=='Success'){  
msg = 'Penny Test request has been submitted successfully';
cmp.set('v.message', msg);
cmp.set('v.Iwerkscall', false);
else if(resp=='Failed') 
{  
msg = 'There was an error in confirming the PA code. Please Contact SFDCOPS or SF Admin Team.';
cmp.set('v.message', msg);
cmp.set('v.Iwerkscall', false);
else if(resp == 'ErrorConn') 
{
msg = 'There was a connection error in sending the PA code. Please Contact SFDCOPS or SF Admin Team.';
cmp.set('v.message', msg);
cmp.set('v.Iwerkscall', false);
else if(resp == 'ErrorSF') 
{
msg = 'Error occured while updating Data in Salesforce. Please Contact SFDCOPS or SF Admin Team.';
cmp.set('v.message', msg);
cmp.set('v.Iwerkscall', false);
}
            }
        });
        $A.enqueueAction(action);
    }
})


Thursday 21 February 2019

SendPACODE

*****1*****

/*
Author :  Krishna Yerru
Date Created : 2/10/2018
Purpose : SMB Lightning Day 2
Original Project/Case/Epic : SP-2831
Test Class: SP:830

Change History :
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Change Version   Name              Date                    Task/Case#                 Description
---------------------------------------------------------------------------------------------------------------------------------------------------------------------

*/

global with sharing class SendPACodeController {
    @AuraEnabled
    public static String ProcessPACode(Id oppId){
        String retValue = '';
        Boolean isValid = true;
        Opportunity opp = getOppData(oppId);
        String partner = opp.Bank_Lookup__r.Name;
        String PAcode=opp.Referral_ID__c;
        System.debug('partner is'+partner);
        System.debug('opp.Referral_ID__c is'+opp.Referral_ID__c);
        if(opp.Referral_ID__c == '' || opp.Referral_ID__c == null)
        {
            isValid = false;
             retValue = 'The Opportunity has no PA Code available. Call cannot be made.';
            //retValue = 'The Opportunity(' +opp.Name + ')has no PA Code available. Call cannot be made.';
         
         
        }
        else if(partner != 'CITI' ||(PAcode != '' && PAcode.length()!=5))
        {
            isValid = false;
             retValue = 'This functionality applies only to Ford Dealers';
        }
        if(isValid)
            retValue = validateOppDetailsForCallout(opp.Referral_ID__c, opp.RecordTypeId, partner);
       
        return retValue;
    }
   
    public static Opportunity getOppData(Id oppId){
        system.debug('Opportunity Id'+oppId);
        Opportunity opp=[Select Id,Name,Referral_ID__c,Bank_Lookup__r.Name,RecordTypeId from opportunity where id=:oppid limit 1];           
        system.debug('opp Data is'+opp);
        return Opp;
    }
   
    /*
Method Name: validateOppDetailsForCallout
Description: Validates the opportunity details

*/
    webservice static String validateOppDetailsForCallout(String paCode, String recordtype, String partner){       
        List<Opportunity> oppServlist;
        List<Opportunity> oppPartsList;
        Opportunity oppServ;
        Opportunity oppParts;
        boolean partsOppflag;
        boolean serviceOppflag;
        boolean partsInitialCheck = false;
        boolean servInitialCheck = false;
        String partsMID='';
        String servMID='';
        string mids = '';
        String strMsg='';
        String creditchkMsg='';
        String midchkMsg='';
        String PacodeMsg='';
        System.debug('**Current_PA Code**'+paCode);
       
        try{
            //Checking if any PA code exist
            System.debug('**PA Code**'+paCode);     
            partsOppflag = false;
            //Fetching one parts record with same PA code based on last modified date
            oppPartsList = [Select id, name, Referral_ID__c,StageName, Merchant_MID__c, Bank_Lookup__r.name, Initial_Call_Complete__c,Credit_Status__c FROM Opportunity WHERE Referral_ID__c = :paCode and RecordTypeId= :recordtype and Bank_Lookup__r.name=:partner and Branch_Name__c='Ford GTB' and Leadsource='Web' and StageName != 'closed lost' order by lastmodifieddate desc];
           
            //checking Parts conditions for validating
            if(oppPartsList.isEmpty()){
                PacodeMsg+='At present, there is no Parts MID available for this PA Code. \n\n';
            }
            else{
                oppParts = oppPartsList[0];
                for(Opportunity o:oppPartsList){
                    if(o.Initial_Call_Complete__c == true){
                        partsInitialCheck = true;
                        partsMID += o.Merchant_MID__c;
                        break;
                    }
                }
                if(partsInitialCheck == false){                       
                    System.debug('**Parts Initial Call**'+oppParts.Initial_Call_Complete__c);
                    System.debug('**Parts MID**'+oppParts.Merchant_MID__c);
                    if(oppParts.Initial_Call_Complete__c == true){
                        strMsg+='Call is already made for the Parts Opportunity '+oppParts.name+'.\n\n';
                    }
                    else{
                        if((oppParts.Credit_Status__c != 'Approved')&&(oppParts.Merchant_MID__c == '' || oppParts.Merchant_MID__c == NULL)){
                            creditchkMsg+='Credit Status is not yet Approved and MID is not available for the Parts Opportunity '+oppParts.name+'.\n\n';
                        }
                        else if(oppParts.Credit_Status__c != 'Approved'){
                            creditchkMsg+='Credit Status is not yet Approved for the Parts Opportunity '+oppParts.name+'.\n\n';
                        }
                        else if(oppParts.Merchant_MID__c == '' || oppParts.Merchant_MID__c == NULL){
                            midchkMsg+='MID is not available for the Parts Opportunity '+oppParts.name+'.\n\n';
                        }
                        else{
                            partsOppflag = true; 
                            if(mids != ''){
                                mids = '||' + 'P:' + oppParts.Merchant_MID__c + ':' + oppParts.id + ':' + paCode;
                            }
                            else
                                mids ='P:' + oppParts.Merchant_MID__c + ':' + oppParts.id + ':' + paCode;
                        }
                    }
                }
               
            }
           
            //Fetching one service record with  same PA code and based on last modified date
            oppServlist = [Select id, name, Referral_ID__c,StageName,Merchant_MID__c, Bank_Lookup__r.name,Initial_Call_Complete__c,Credit_Status__c FROM Opportunity WHERE Referral_ID__c = :paCode and RecordTypeId= :recordtype and Bank_Lookup__r.name=:partner and Branch_Name__c!= 'Ford GTB' AND MRC_Code__r.name ='58001-FordDealr'  and StageName!='closed lost' order by lastmodifieddate desc ];
           
            //checking Service conditions for validating
            if(oppServlist.isEmpty()){
                PacodeMsg+='At present, there is no Service MID available for this PA Code. \n\n';
            }
            else{
                oppServ = oppServlist[0];
                for(Opportunity o:oppServlist){
                    if(o.Initial_Call_Complete__c == true){
                        servInitialCheck = true;
                        servMID+=o.Merchant_MID__c;
                        System.debug('Flag check service'+servInitialCheck);
                        break;
                    }
                }
               
                if(servInitialCheck == false){                       
                    System.debug('**Service Initial Call**'+oppServ.Initial_Call_Complete__c);
                    System.debug('**Service MID**'+oppServ.Merchant_MID__c);
                    if(oppServ.Initial_Call_Complete__c==true){
                        strMsg+='Call is already made for the Service Opportunity '+oppServ.name+'.\n\n';
                    }
                    else{
                        if((oppServ.Credit_Status__c != 'Approved')&&(oppServ.Merchant_MID__c == '' || oppServ.Merchant_MID__c == NULL)){
                            creditchkMsg+='Credit Status is not yet Approved and MID is not available for the Service Opportunity '+oppServ.name+'.\n\n';
                        }
                        else if(oppServ.Credit_Status__c != 'Approved'){
                            creditchkMsg+='Credit Status is not yet Approved for the Service Opportunity '+oppServ.name+'.\n\n';
                        }
                        else if (oppServ.Merchant_MID__c == '' || oppServ.Merchant_MID__c == NULL){
                            midchkMsg+='MID is not available for the Service Opportunity '+oppServ.name+'.\n\n';
                        }
                        else{
                            serviceOppflag = true;
                            if(mids != ''){
                                mids += '||' + 'S:' + oppServ.Merchant_MID__c + ':' + oppServ.id + ':' + paCode;
                            }
                            else
                                mids +='S:' + oppServ.Merchant_MID__c + ':' + oppServ.id + ':' + paCode;
                        }
                    }
                }
            }
           
            if(partsInitialCheck == true && servInitialCheck == true)
                strMsg = 'The Parts MID: ' + partsMID + ' & Service MID: ' + servMID +' for this PA Code: ' + oppServ.Referral_ID__c + ' have already been sent to iWerks. \n\n';
            else if(partsInitialCheck == true && servInitialCheck == false)
                strMsg = 'The Parts MID: ' + partsMID +' for this PA Code: ' + oppParts.Referral_ID__c + ' has already been sent to iWerks. Please get the Initial Call Complete checkbox field unchecked on the opportunity record specific to the above MID, so that the Parts MID specific outbound call could be submitted for this PA code again, if needed. \n\n';
            else if(partsInitialCheck == false && servInitialCheck == true)
                strMsg = 'The Service MID: ' + servMID +' for this PA Code: ' + oppServ.Referral_ID__c + ' has already been sent to iWerks. Please get the Initial Call Complete checkbox field unchecked on the opportunity record specific to the above MID, so that the Service MID specific outbound call could be submitted for this PA code again, if needed. \n\n';
        }
        catch(Exception e){
            System.debug('Validation failed : ' + e.getMessage());
            return 'Error';
        }
       
        if(partsOppflag == true || serviceOppflag == true)
        {
            strMsg='Valid' + '||' + mids + '||' + strMsg;
            System.debug('**right***'+strMsg);
        }
        else{
            strMsg = 'Error' + '||' + strMsg;
            System.debug('**error***'+strMsg);
        }
        if(!String.isBlank(creditchkMsg)){
            strMsg+=creditchkMsg;
        }
        if(!String.isBlank(midchkMsg)){
            strMsg+=midchkMsg;
        }
        if(!String.isBlank(PacodeMsg)){
            strMsg+=PacodeMsg;
        }
        return strMsg;
    }
    /*
Method Name: makeCallout
Description: Makes  Call to iWerks
*/
    @AuraEnabled
    public static String makeCallout(String paCode,String partsMID, String servMID, String partsOppID, String servOppID){
        String USERNAME ,PASSWORD;
        Boolean isSandbox; 
        Boolean result;
        List<opportunity> oppList=new List<opportunity>(); 
        String webserviceUrl;
        System.debug('PA Code:'+paCode);
        System.debug('Parts MID:'+partsMID);
        System.debug('Service MID:'+servMID);
        System.debug('Parts OppID:'+partsOppID);
        System.debug('Service OPpid:'+servOppID);
        try{
            isSandbox = runningInASandbox();
            Iwerk_User_Credentials__c usercrdns;
            //Checking SF Sandbox or Production
            if(isSandbox){ //Sandbox
                usercrdns = Iwerk_User_Credentials__c.getinstance('UserDetails');
                System.debug(usercrdns);               
            }
            else{ //Production
                usercrdns = Iwerk_User_Credentials__c.getinstance('UserDetailsProd');
                System.debug(usercrdns);               
            }
            System.debug('usercrdns.Username__c: '+usercrdns.Username__c);
            System.debug('usercrdns.Password__c: '+usercrdns.Password__c);
            System.debug('usercrdns.WebserviceURL__c: '+usercrdns.WebserviceURL__c);
            Blob encodedEncryptedBlob1 = EncodingUtil.base64Decode(usercrdns.Username__c);             
            Blob encodedEncryptedBlob2 = EncodingUtil.base64Decode(usercrdns.Password__c);
            webserviceUrl=usercrdns.WebserviceURL__c;
           
            Blob key = Blob.valueOf(System.Label.SecPSD);
           
            //Username decryption
            Blob decryptedData = Crypto.decryptWithManagedIV('AES256', key, encodedEncryptedBlob1);
            System.debug('decryptedData ' +decryptedData);
            String decryptedDataString = decryptedData.toString();
            System.debug('decryptedDataString ' +decryptedDataString);
            Blob bdata  = EncodingUtil.base64Decode(decryptedDataString);
            String decryptedClearText1 = bdata.toString();
            System.debug('decrypted username  ' +decryptedClearText1);
           
            //Password decryption
           
            Blob decryptedData1 = Crypto.decryptWithManagedIV('AES256', key, encodedEncryptedBlob2);
            System.debug('decryptedData1 ' +decryptedData1);
            String decryptedDataString1 = decryptedData1.toString();
            System.debug('decryptedDataString1 ' +decryptedDataString1);
            Blob bdata1 = EncodingUtil.base64Decode(decryptedDataString1);
            String decryptedClearText2 = bdata1.toString();
            System.debug('decrypted password  ' +decryptedClearText2);                       
           
            USERNAME = decryptedClearText1;
            PASSWORD = decryptedClearText2;
           
            WSiwerkCom.UserAuthentication wsusr = new WSiwerkCom.UserAuthentication();
            wsusr.UserName = USERNAME;
            wsusr.Password = PASSWORD;
           
            WSiwerkCom.DealerEnrollmentSoap wsptr = new WSiwerkCom.DealerEnrollmentSoap();
           
            wsptr.endpoint_x = usercrdns.WebserviceURL__c;
            try{
                result = wsptr.PennyTestRequest(pacode,partsMID,servMID,wsusr);
                System.debug('$$$$$ result ' + result);               
            }
            Catch(Exception e){
                System.debug('Exception: Callout: ' + e.getMessage());
                return 'ErrorConn';
            }
            try{
                updateopp(partsOppID,servOppID, result);
            }Catch(Exception e){
                System.debug('Exception: DML: ' + e.getMessage());
                return 'ErrorSF';
            }
        }
        Catch(Exception e){
            System.debug('Exception occured : ' +e.getMessage());
            return 'Error';
        }
       
        if(result == true)
            return 'Success';
        else if(result == false)
            return 'Failed';
        else
            return 'nothing';
       
    }
    /*
Method Name: updateopp
Description: Updating Opportunity and creating task for parts or service opportunity
*/
    @auraenabled
    public static void updateopp(String pOppid,String sOppid,Boolean status){
        System.debug('**in updateopp');
        List<opportunity> oppList=new List<opportunity>();
        List<Task> taskList = new list<Task>();
        String subject = '';
       
        if(status == true)
        {
            subject = 'FordPennyTestRequest Completed';
        }
        else{
            subject = 'FordPennyTestRequest Not Completed';
        }
       
        if(pOppid != '' && sOppid != '')
        {
           
            opportunity oppparts=new opportunity(id=pOppid,Initial_Call_Complete__c=true);
            opportunity oppserv=new opportunity(id=sOppid,Initial_Call_Complete__c=true);
            oppList.add(oppparts);
            oppList.add(oppserv);
           
            Task partsTask = new Task();
            partsTask.OwnerId = UserInfo.getUserId();
            partsTask.Subject = subject;
            partsTask.Status = 'Completed';
            partsTask.RecordTypeId = [Select Id,SobjectType,Name From RecordType WHERE Name ='Standard Task' and SobjectType ='Task'  limit 1].Id;
            partsTask.WhatId = pOppid;
            taskList.add(partsTask);
           
            Task servTask = new Task();
            servTask.OwnerId = UserInfo.getUserId();
            servTask.Subject = subject;
            servTask.Status = 'Completed';
            servTask.RecordTypeId = [Select Id,SobjectType,Name From RecordType WHERE Name ='Standard Task' and SobjectType ='Task'  limit 1].Id;
            servTask.WhatId = sOppid;
            taskList.add(servTask);
        }
        else if(pOppid != '' && sOppid == ''){
            opportunity oppparts=new opportunity(id=pOppid,Initial_Call_Complete__c=true);
            oppList.add(oppparts);
           
            Task partsTask = new Task();
            partsTask.OwnerId = UserInfo.getUserId();
            partsTask.Subject = subject;
            partsTask.Status = 'Completed';
            partsTask.RecordTypeId = [Select Id,SobjectType,Name From RecordType WHERE Name ='Standard Task' and SobjectType ='Task'  limit 1].Id;
            partsTask.WhatId = pOppid;
            taskList.add(partsTask);
        }
        else if(pOppid == '' && sOppid != ''){
            opportunity oppserv=new opportunity(id=sOppid,Initial_Call_Complete__c=true);
            oppList.add(oppserv);
           
            Task servTask = new Task();
            servTask.OwnerId = UserInfo.getUserId();
            servTask.Subject = subject;
            servTask.Status = 'Completed';
            servTask.RecordTypeId = [Select Id,SobjectType,Name From RecordType WHERE Name ='Standard Task' and SobjectType ='Task'  limit 1].Id;
            servTask.WhatId = sOppid;
            taskList.add(servTask);
        }
        if(status == true)
        {
            update oppList;
        }       
        insert taskList;
    }
   
    //checking if the environment is Sandbox or Production
    @auraenabled
    public static Boolean runningInASandbox() {
        return [SELECT IsSandbox FROM Organization LIMIT 1].IsSandbox;
    }
   
   
}


******2*******JS


({
    doInit : function(component, event, helper) {
       
        var oppid;
        var initial;
        var msg = '';
var msgOppVal = '';
        var pMid='';
        var sMid='';
        var partsOppID='';
        var servOppID='';
        var partValue;
        var servValue;
        var err = false;
        var retValue;
        var oppPacode;
        var action = component.get("c.ProcessPACode");
       
        action.setParams({
            "oppId": component.get("v.recordId")
        });
       
        action.setCallback(this, function(response) {           
            var state = response.getState();
            if (state === "SUCCESS") {
                var resp = response.getReturnValue();
                if(resp=='This functionality applies only to Ford Dealers' ||
                   resp=='The Opportunity has no PA Code available. Call cannot be made.')
                {
                    msgOppVal = resp;
//alert(msg);
component.set('v.message', msgOppVal);
/*
                    var showToast=$A.get('e.force:showToast');               
                    showToast.setParams({
                        type : 'error',
                        message : msg
                    });
                    showToast.fire();
                    $A.get("e.force:closeQuickAction").fire();
*/
                }
                else{
                    console.log('@@resp : ' + resp);
                    retValue = resp.split("||");
                    console.log('@@retValue : ' + retValue.length);
                    if(retValue != 'undefined')
                    {
                        if(retValue.length > 0)
                        {
                            if(retValue[0] == 'Valid')
                            {
                                console.log('@@Valid : ' + retValue[0]);
                                if(retValue.length == 4){
                                    pMid = retValue[1].split(":")[1];
                                    component.set("v.partsMID", pMid);

                                    partsOppID = retValue[1].split(":")[2];
                                    component.set("v.partsOppID", partsOppID);
                                   
                                    oppPacode = retValue[1].split(":")[3];
                                    component.set("v.PaCode", oppPacode);
                                   
                                    sMid = retValue[2].split(":")[1];
                                    component.set("v.servMID", sMid);

                                    servOppID=retValue[2].split(":")[2];
                                    component.set("v.servOppID", servOppID);

                                    console.log('@@oppPacode 0: ' + oppPacode);
                                    msg = 'The below details will be sent to iWerks. \n\n PA Code: ' + oppPacode + ' , ' +
                                        'Parts MID: ' + pMid + ' & Service MID: ' + sMid + '\n\n Do you want to continue sending the details?';
                                    component.set('v.message', msg);
                                }
                                else if(retValue.length == 3){
                                    if(retValue[1].split(":")[0] != 'S')
                                    {
msgOppVal =retValue[retValue.length - 1];
//component.set('v.message', msg1);
//alert(retValue[retValue.length - 1]);
/*
                                        var showToast = $A.get('e.force:showToast');               
                                        showToast.setParams({
                                            type : 'warning',
                                            message : retValue[retValue.length - 1] 
                                        });
                                        showToast.fire();
                                        */
                                        console.log('@@retValue arr: ' + retValue[1].split(":"));
                                       
                                        pMid = retValue[1].split(":")[1];
component.set("v.partsMID", pMid);

                                        partsOppID = retValue[1].split(":")[2];
component.set("v.partsOppID", partsOppID);

                                        oppPacode = retValue[1].split(":")[3];
component.set("v.PaCode", oppPacode);

                                        console.log('@@oppPacode 1: ' + oppPacode);
                                        msg = msgOppVal+ '\n\n'+'Now, the below details will be sent to iWerks. \n\n PA Code: ' + oppPacode + ' & ' +
                                            'Parts MID: ' + pMid + '\n\n Do you want to continue sending the details?';
                                        component.set('v.message', msg);
                                    }
                                    else if(retValue[1].split(":")[0] == 'S')
                                    {
msgOppVal =retValue[retValue.length - 1];
//component.set('v.message', msg1);
//alert(retValue[retValue.length - 1]);
/*
                                        var showToast = $A.get('e.force:showToast');               
                                        showToast.setParams({
                                            type : 'warning',
                                            message : retValue[retValue.length - 1]
                                        });
                                        showToast.fire();
                                        */
                                        sMid = retValue[1].split(":")[1];
component.set("v.servMID", sMid);

                                        servOppID = retValue[1].split(":")[2];
component.set("v.servOppID", servOppID);

                                        oppPacode = retValue[1].split(":")[3];
component.set("v.PaCode", oppPacode);

                                        console.log('@@oppPacode 2: ' + oppPacode);
                                        msg = msgOppVal+'\n\n' +'Now, the below details will be sent to iWerks. \n\n PA Code: ' + oppPacode + ' & ' +
                                            'Service MID: ' + sMid + '\n\n Do you want to continue sending the details?';
                                        component.set('v.message', msg);
                                    }
                                }
                                    else if(retValue.length == 2){
                                        if(retValue[1].split(":")[0] != 'P' && retValue[1].split(":")[0] != 'S'){
msgOppVal =retValue[retValue.length - 1];
component.set('v.message', msgOppVal);
//alert(retValue[retValue.length - 1]);
                                            /*
var showToast = $A.get('e.force:showToast');               
                                            showToast.setParams({
                                                type : 'warning',
                                                message : retValue[retValue.length - 1]
                                            });
                                            showToast.fire();
*/
                                        }
                                        if(retValue[1].split(":")[0] == 'P')
                                        {
                                            pMid = retValue[1].split(":")[1];
component.set("v.partsMID", pMid);

                                            partsOppID = retValue[1].split(":")[2];
component.set("v.partsOppID", partsOppID);

                                            oppPacode = retValue[1].split(":")[3];
component.set("v.PaCode", oppPacode);

                                            console.log('@@oppPacode 3: ' + oppPacode);
                                            msg = 'The below details will be sent to iWerks. \n\n PA Code: ' + oppPacode + ' & ' +
                                                'Parts MID: ' + pMid + '\n\n Do you want to continue sending the details?';
                                            component.set('v.message', msg);
                                        }
                                        else if(retValue[1].split(":")[0] == 'S')
                                        {
                                            sMid = retValue[1].split(":")[1];
component.set("v.servMID", sMid);

                                            servOppID = retValue[1].split(":")[2];
component.set("v.servOppID", servOppID);

                                            oppPacode = retValue[1].split(":")[3];
component.set("v.PaCode", oppPacode);

                                            console.log('@@oppPacode 4: ' + oppPacode);
                                            msg = 'The below details will be sent to iWerks. \n\n PA Code: ' + oppPacode + ' & ' +
                                                'Service MID: ' + sMid + '\n\n Do you want to continue sending the details?';
                                            component.set('v.message', msg);
                                        }
                                    }
                                //To do : The commented code will go in
                            }
                            else
                            {
msgOppVal =retValue[1];
component.set('v.message', msgOppVal);
//alert(retValue[1]);
                                /*
var showToast = $A.get('e.force:showToast');               
                                showToast.setParams({
                                    type : 'warning',
                                    message : retValue[1]
                                });
                                showToast.fire();
                                $A.get("e.force:closeQuickAction").fire();
*/
                            }
                        }
                    }
                }
            }
            else{
msgOppVal ='No response from the Server. Please try again.';
component.set('v.message', msgOppVal);
//alert('No response from the Server. Please try again.');
                /*
msg = 'No response from the Server. Please try again.';
                var showToast=$A.get('e.force:showToast');               
                showToast.setParams({
                    type : 'error',//success
                    message : msg
                });
                showToast.fire();
                $A.get("e.force:closeQuickAction").fire();
*/
            }
        });
        // Invoke the service
        $A.enqueueAction(action);
    },
   
    //This method closes the lightning modal
    closeComponent : function(cmp, evt, helper){
        $A.get("e.force:closeQuickAction").fire();
    },
   
    FinalCallout : function(cmp, evt, helper)
    {
        var action = cmp.get("c.makeCallout");
        action.setParams({
            "paCode": cmp.get("v.PaCode"),
"partsMID": cmp.get("v.partsMID"),
"servMID": cmp.get("v.servMID"),
"partsOppID": cmp.get("v.partsOppID"),
"servOppID": cmp.get("v.servOppID")
        });
       
        action.setCallback(this, function(response) {           
            var state = response.getState();
var msg='';
            if (state === "SUCCESS") {
                var resp = response.getReturnValue();
                console.log('Makecallout  ' + resp);
if(resp=='Success'){
msg = 'Penny Test request has been submitted successfully';
cmp.set('v.message', msg);
}
else if(resp=='Failed')
{
msg = 'There was an error in confirming the PA code. Please Contact SFDCOPS or SF Admin Team.';
cmp.set('v.message', msg);
}
else if(resp == 'ErrorConn')
{
msg = 'There was a connection error in sending the PA code. Please Contact SFDCOPS or SF Admin Team.';
cmp.set('v.message', msg);
}
else if(resp == 'ErrorSF')
{
msg = 'Error occured while updating Data in Salesforce. Please Contact SFDCOPS or SF Admin Team.';
cmp.set('v.message', msg);
}
            }
        });
        $A.enqueueAction(action);
    }
})


*****3****CMP****
<!--
Author :  Krishna Nagendra Rao.Yerru
Date Created : 02/07/2019
Purpose : SMB Lightning Day 2
Original Project/Case/Epic : SP-830
Test Class:

Change History :
 *****************************************************************************************************************************
Change Version   Name              Date                    Task/Case#                 Description
 *****************************************************************************************************************************

-->

<aura:component controller="SendPACodeController" implements="force:lightningQuickActionWithoutHeader,force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId">
    <aura:attribute name="PaCode" type="String" />
    <aura:attribute name="partsMID" type="String" />
    <aura:attribute name="servMID" type="String" />
    <aura:attribute name="partsOppID" type="ID" />
    <aura:attribute name="servOppID" type="ID" />
       
    <aura:attribute name="message" type="String" />   
   
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
   
    <lightning:card title="Penny Test Request" variant="Narrow" iconName="utility:new_direct_message">
        <lightning:layout horizontalAlign="centre" multipleRows="true">
            <lightning:layoutItem padding="around-small" size="12" flexibility="auto">
                <!-- Display Lightning Data Service errors, if any -->
                <aura:if isTrue="{!not(empty(v.message))}">
                    <div class="slds-box slds-theme_info">
                        {!v.message}</div>
                </aura:if>
            </lightning:layoutItem>
        </lightning:layout>
        <lightning:layout horizontalAlign="right" multipleRows="true">
            <lightning:layoutItem padding="around-small" size="12" flexibility="auto">
                <lightning:button iconName="action:close" variant="brand" label="Cancel" onclick="{!c.closeComponent}"/>
                <lightning:button iconName="action:submit_for_approval" variant="brand" label="Ok" onclick="{!c.FinalCallout}"/>
            </lightning:layoutItem>
        </lightning:layout>
    </lightning:card>
</aura:component>


****************