trying to reschedule the calim but when clicked on button spinner keeps on rotating and unable to reschedule
see the screenshots for the error
Creatfurniturecontroller.js
createFurnitureServiceInfo : function(component) {
var scheduleServiceWrapper = component.get('v.scheduleService');
var scheduleServiceWrappperComments = scheduleServiceWrapper.Comments.replace(/\\/g, '');
var escapedComments = this.encodeSpecialCharacters(scheduleServiceWrappperComments);
scheduleServiceWrapper.Comments = escapedComments;
scheduleServiceWrapper.ButtonLabel = component.get('v.buttonLabel');
component.set('v.isLoading',true);
var isIndependentServicer = component.get('v.isIndependentServicerChecked');
var independentServicer = component.get('v.independentServicer');
var action = component.get('c.createFurnitureServices');
var parameters = {
"scheduleServiceJSON": JSON.stringify(scheduleServiceWrapper),
"independentServicerJSON": JSON.stringify(independentServicer),
"isIndependentServicer": isIndependentServicer
};
//console.log('params: ' + JSON.stringify(parameters));
action.setParams(parameters);
action.setCallback(this, function(response) {
component.set('v.isLoading',false);
var state = response.getState();
if (state === "SUCCESS") {
this.displayToast('Success', 'The service has been successfully scheduled.','success');
var navEvt = $A.get("e.force:navigateToSObject");
navEvt.setParams({
"recordId": response.getReturnValue(),
"slideDevName": "detail"
});
this.closeModal(component);
this.refreshFurnitureServiceRecord();
navEvt.fire();
} else {
console.error(response.getError());
this.displayToast('Error', 'Something went wrong, the service was NOT scheduled. Please verify zip code and additional address fields.','error');
}
});
$A.enqueueAction(action);
},
refreshFurnitureServiceRecord : function() {
window.setTimeout(
$A.getCallback(function() {
var refreshFurnitureServiceEvent = $A.get("e.c:refreshFurnitureServiceEvent");
refreshFurnitureServiceEvent.fire();
}), 2000
);
},
getDayOfWeek : function(serviceDate) {
var momentDate = moment(serviceDate);
var weekDay = momentDate.format('dddd');
return weekDay;
},
formatServiceDate : function(serviceDate) {
return serviceDate.substring(5, 7) + '/' + serviceDate.substring(8, 10) + '/' + serviceDate.substring(0, 4);
},
displayToast : function(title, message, type, mode){
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
title : title,
message: message,
duration:' 5000',
key: 'info_alt',
type: type,
mode: mode ? mode : 'pester'
});
toastEvent.fire();
},
getRelatedCase : function(component, event, helper) {
var workspaceAPI = component.find("workspace");
workspaceAPI.getFocusedTabInfo().then(function(response) {
//console.log(JSON.parse(JSON.stringify(response)));
var parentTabId = response.parentTabId;
workspaceAPI.getTabInfo({
tabId: parentTabId
}).then(function(parentTabResponse) {
var parentTabObjectAPIName = parentTabResponse.pageReference.attributes.objectApiName;
//console.log(parentTabObjectAPIName);
// If the parent tab is a Case record
if(parentTabObjectAPIName === "Case"){
var caseRecord = {
"recordId" : parentTabResponse.recordId,
"label" : parentTabResponse.title
}
component.set('v.caseRecord',caseRecord);
} else {
// If the parent tab is not a Case record
var relatedSubTabs = parentTabResponse.subtabs;
for (let i = 0; i < relatedSubTabs.length; i++) {
var subtab = relatedSubTabs[i];
var subTabObjectAPIName = subtab.pageReference.attributes.objectApiName;
if(subTabObjectAPIName === "Case"){
var caseRecord = {
"recordId" : subtab.recordId,
"label" : subtab.title
}
component.set('v.caseRecord',caseRecord);
}
}
}
helper.fetchCaseData(component, event, helper);
});
})
.catch(function(error) {
console.log(error);
});
},
isValidToSave : function(component, event, helper) {
var validityErrors = [];
var notPopulatedRequiredFields = [];
var isIndependentServicer = component.get('v.isIndependentServicerChecked');
try {
// validation for both: regular and independent servicer scheduling
let serviceDateField = isIndependentServicer ? component.find('serviceDate2') : component.find('serviceDate');
serviceDateField.reportValidity();
if (!serviceDateField.get('v.value')) validityErrors.push('Service Date must be selected.');
let addressField = isIndependentServicer ? component.find('addressField2a') : component.find('addressField');
addressField.reportValidity();
if (!addressField.get('v.value')) notPopulatedRequiredFields.push('address');
let zipCodeField = isIndependentServicer ? component.find('zipCodeField2') : component.find('zipCodeField');
zipCodeField.reportValidity();
if (!zipCodeField.get('v.value')) notPopulatedRequiredFields.push('zip code');
let stateField = isIndependentServicer ? component.find('stateField2') : component.find('stateField');
stateField.reportValidity();
if (!stateField.get('v.value')) notPopulatedRequiredFields.push('state');
let cityField = isIndependentServicer ? component.find('cityField2') : component.find('cityField');
cityField.reportValidity();
if (!cityField.get('v.value')) notPopulatedRequiredFields.push('city');
// validation for independent servicer scheduling
if (isIndependentServicer) {
var caseRecord = component.get('v.caseRecord');
if (!caseRecord || !caseRecord.Id) validityErrors.push('Selecting case related to service is required.');
if (!caseRecord.Independent_Servicer__r) {
validityErrors.push('Independent Servicer needs to be assigned to the selected Case.');
} else if (!caseRecord.Independent_Servicer__r.Servicer_Id__c) {
validityErrors.push('Independent Servicer assigned to the selected Case needs to have Servicer Id value.');
}
let callBackContactField = component.find('callBackContact');
callBackContactField.reportValidity();
if (!callBackContactField.get('v.value')) notPopulatedRequiredFields.push('contact');
let callBackNumberField = component.find('callBackNumber');
callBackNumberField.reportValidity();
if (!callBackNumberField.get('v.value')) {
notPopulatedRequiredFields.push('phone');
} else if (callBackNumberField.get('v.value').length != 10) {
validityErrors.push('Phone field must be 10 digits long.');
}
} else {
// validation for regular scheduling
var routeCode = component.get('v.selectedRouteCode');
if($A.util.isUndefinedOrNull(routeCode) || $A.util.isEmpty(routeCode) || routeCode.trim() == ''){
validityErrors.push('A Route code is required.');
}
var selectedAvailableAppointmentUnits = Number(component.get('v.selectedAppointmentUnits'));
var availableUnits = Number(component.get('v.scheduleService.AppointmentUnits'));
if(availableUnits > selectedAvailableAppointmentUnits){
validityErrors.push('There is not enough appointment units available for the selected service date.');
}
}
if (isIndependentServicer) {
if (notPopulatedRequiredFields.length > 0) validityErrors.push('You need to populate those fields on the selected case: ' + notPopulatedRequiredFields.join(', ') + '.');
} else {
if (notPopulatedRequiredFields.length > 0) validityErrors.push('You need to populate those fields: ' + notPopulatedRequiredFields.join(', ') + '.');
}
} catch(err) {
console.error(err);
}
return validityErrors;
},
isIndependentServicerCheckedChanged : function(component, event, helper) {
let checkboxValue = component.get('v.isIndependentServicerChecked');
try{
// If the checkbox was checked
if(checkboxValue){
// Set service date as current date
component.set('v.selectedServiceDate', new Date().toISOString().slice(0, 10));
let caseRecord = component.get('v.caseRecord');
let scheduleService = component.get('v.scheduleService');
// If this property is already filled, it means the service was already scheduled once, so we should consider data from POPS
if(scheduleService.Servicer){
let independentServicer = {
CustomerName : scheduleService.CustomerName,
Address : scheduleService.Address,
ZipCode : scheduleService.ZipCode,
State : scheduleService.State,
City : scheduleService.City,
ContactPhone : scheduleService.ContactPhone,
ContactPhoneExtension : scheduleService.ContactPhoneExtension,
Servicer : caseRecord.Independent_Servicer__r.Servicer_Id__c,
CaseId : caseRecord.Id
};
component.set('v.independentServicer',independentServicer);
} else {
// This means it's the first time creating the independent servicer furniture service, so we should consider data from the associated Case
let independentServicer = {
CustomerName : caseRecord.Call_Back_Contact__c,
Address : caseRecord.Shipping_Address_1__c,
ZipCode : caseRecord.Shipping_Postal_Code__c,
State : caseRecord.Shipping_State__c,
City : caseRecord.Shipping_City__c,
ContactPhone : caseRecord.Requested_Call_Back_Number__c,
ContactPhoneExtension : caseRecord.Requested_Call_Back_Number_Ext__c,
Servicer : caseRecord.Independent_Servicer__r.Servicer_Id__c,
CaseId : caseRecord.Id
};
component.set('v.independentServicer',independentServicer);
}
} else {
component.set('v.selectedServiceDate', null);
}
} catch (err) {
console.error(err);
}
}
})
Apex class
public without sharing class CreateFurnitureServicesCtrl {
#AuraEnabled
public static ScheduleServiceWrapper getScheduleServiceWrapper(String claimRecordId){
String[] claimFieldsList = new List<String>{
'Id', 'OrderNumber__c','AccountNumber__c', 'ClaimId__c'
};
Map<String,String> claimsFieldValueMap = new Map<String,String>();
claimsFieldValueMap.put('Id',claimRecordId);
Claims__x objClaims = nfm_ExternalClaimRequest.getClaims(claimFieldsList, claimsFieldValueMap, 'Id', 'ASC')[0];
String[] orderDetailsFieldsList = new List<String>{
'Id','CustomerZip__c','CustomerPhone__c','OrderState__c','OrderCity__c','CustomerState__c','CustomerCity__c','DistributionMethod__c',
'AccountNumber__c','OrderNumber__c','OrderZip__c', 'OrderPrimaryCallAhPhExt__c', 'CustomerName__c',
'CustomerAddress1__c','CustomerAddress2__c','OrderAddress1__c','OrderAddress2__c'
};
Map<String,String> orderDetailsFieldValueMap = new Map<String,String>();
orderDetailsFieldValueMap.put('OrderNumber__c',objClaims.OrderNumber__c);
OrderDetails__x objOrderDetails = nfm_ExternalOrderDetailsRequest.getOrders(orderDetailsFieldsList, orderDetailsFieldValueMap, 'Id', 'ASC', false)[0];
ScheduleServiceWrapper objScheduleServiceWrapper = new ScheduleServiceWrapper();
objScheduleServiceWrapper.NumberOfDays = 15;
objScheduleServiceWrapper.AppointmentUnits = 1;
objScheduleServiceWrapper.StartDate = String.valueOf(System.today());
objScheduleServiceWrapper.ClaimId = objClaims.ClaimId__c;
objScheduleServiceWrapper.ServiceDate = 'TBD';
objScheduleServiceWrapper.RouteCode = 'TBD';
objScheduleServiceWrapper.ServiceCode = 'TBD';
objScheduleServiceWrapper.Comments = ' ';
FurnitureServices__x objFurnitureServices = getPreviousFurnitureService(objClaims.ClaimId__c);
Set<String> customerDistributionSet = new Set<String>{'P','T'};
Set<String> orderDistributionSet = new Set<String>{'D','W','I','O'};
// Here we're verifying if a basic field is blank, so that means that the furnite service hasn't been scheduled yet
if(objFurnitureServices.InspectAddress1__c == null){
// In this case, the details are filled according to the Order's Delivery Method
objScheduleServiceWrapper.CustomerName = objOrderDetails.CustomerName__c;
objScheduleServiceWrapper.ContactName = objOrderDetails.CustomerName__c;
objScheduleServiceWrapper.ContactPhone = objOrderDetails.CustomerPhone__c;
if(customerDistributionSet.contains(objOrderDetails.DistributionMethod__c)){ // Customer
objScheduleServiceWrapper.City = objOrderDetails.CustomerCity__c;
objScheduleServiceWrapper.State = objOrderDetails.CustomerState__c;
objScheduleServiceWrapper.ZipCode = objOrderDetails.CustomerZip__c.substring(0,5);
objScheduleServiceWrapper.Address = objOrderDetails.CustomerAddress1__c + ' ' + nfm_Utils.ifNull(objOrderDetails.CustomerAddress2__c,'');
} else if(orderDistributionSet.contains(objOrderDetails.DistributionMethod__c)) { //Order
objScheduleServiceWrapper.City = objOrderDetails.OrderCity__c;
objScheduleServiceWrapper.State = objOrderDetails.OrderState__c;
objScheduleServiceWrapper.ZipCode = objOrderDetails.OrderZip__c.substring(0,5);
objScheduleServiceWrapper.ContactPhoneExtension = objOrderDetails.OrderPrimaryCallAhPhExt__c;
objScheduleServiceWrapper.Address = objOrderDetails.OrderAddress1__c + ' ' + nfm_Utils.ifNull(objOrderDetails.OrderAddress2__c,'');
}
} else {
// In this case, the details are filled according to the previous Furniture Service
objScheduleServiceWrapper.CustomerName = objFurnitureServices.InspectName__c;
objScheduleServiceWrapper.ContactName = objFurnitureServices.ContactDescription__c;
objScheduleServiceWrapper.ContactPhone = objFurnitureServices.ContactPhone__c;
objScheduleServiceWrapper.ContactPhoneExtension = objFurnitureServices.ContactPhoneExtension__c;
objScheduleServiceWrapper.Address = objFurnitureServices.InspectAddress1__c;
objScheduleServiceWrapper.City = objFurnitureServices.InspectCity__c;
objScheduleServiceWrapper.State = objFurnitureServices.InspectState__c;
objScheduleServiceWrapper.ZipCode = objFurnitureServices.InspectZip__c.substring(0,5);
}
objScheduleServiceWrapper.Servicer = nfm_Utils.ifNull(objFurnitureServices.Servicer__c,'');
return objScheduleServiceWrapper;
}
public class ScheduleServiceWrapper{
#AuraEnabled public String ClaimId{get;set;}
#AuraEnabled public String ZipCode{get;set;}
#AuraEnabled public String StartDate{get;set;}
#AuraEnabled public String ServiceDate{get;set;}
#AuraEnabled public String ServiceCode{get;set;}
#AuraEnabled public String RouteCode{get;set;}
#AuraEnabled public Integer NumberOfDays{get;set;}
#AuraEnabled public Integer AppointmentUnits{get;set;}
#AuraEnabled public String CustomerName{get;set;}
#AuraEnabled public String Address{get;set;}
#AuraEnabled public String Servicer{get;set;}
#AuraEnabled public String State{get;set;}
#AuraEnabled public String City{get;set;}
#AuraEnabled public String ContactName{get;set;}
#AuraEnabled public String ContactPhone{get;set;}
#AuraEnabled public String ContactPhoneExtension{get;set;}
#AuraEnabled public String Comments{get;set;}
#AuraEnabled public String ButtonLabel{get;set;}
}
public class IndependentServicerWrapper{
#AuraEnabled public String CustomerName{get;set;}
#AuraEnabled public String Address{get;set;}
#AuraEnabled public String State{get;set;}
#AuraEnabled public String City{get;set;}
#AuraEnabled public String ZipCode{get;set;}
#AuraEnabled public String ContactPhone{get;set;}
#AuraEnabled public String ContactPhoneExtension{get;set;}
#AuraEnabled public String Servicer{get;set;}
#AuraEnabled public String CaseId{get;set;}
}
#AuraEnabled
public static String createFurnitureServices(String scheduleServiceJSON, String independentServicerJSON, Boolean isIndependentServicer){
ScheduleServiceWrapper objScheduleServiceWrapper = (ScheduleServiceWrapper) System.JSON.deserialize(scheduleServiceJSON, ScheduleServiceWrapper.class);
IndependentServicerWrapper objIndependentServicerWrapper = !isIndependentServicer ? null : (IndependentServicerWrapper) System.JSON.deserialize(independentServicerJSON, IndependentServicerWrapper.class);
JSONGenerator jsonGenerator = JSON.createGenerator(false);
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField('ClaimId__c', objScheduleServiceWrapper.ClaimId);
jsonGenerator.writeObjectField('Comments__c','[' + System.today().format() + '][' + nfm_Utils.userAlias + '] ' + objScheduleServiceWrapper.Comments);
String inspectDateYear = objScheduleServiceWrapper.ServiceDate.substring(0,4);
String inspectDateMonth = objScheduleServiceWrapper.ServiceDate.substring(5,7);
String inspectDateDay = objScheduleServiceWrapper.ServiceDate.substring(8,10);
jsonGenerator.writeObjectField('InspectDate__c', inspectDateMonth + '/' + inspectDateDay + '/'+ inspectDateYear);
if (!isIndependentServicer) {
//specific fields
jsonGenerator.writeObjectField('InspectName__c', objScheduleServiceWrapper.CustomerName);
jsonGenerator.writeObjectField('ServiceCode__c', objScheduleServiceWrapper.ServiceCode);
jsonGenerator.writeObjectField('RouteCode__c', objScheduleServiceWrapper.RouteCode);
jsonGenerator.writeObjectField('AppointmentUnits__c', String.valueOf(objScheduleServiceWrapper.AppointmentUnits));
//common fields
jsonGenerator.writeObjectField('InspectAddress1__c', objScheduleServiceWrapper.Address);
jsonGenerator.writeObjectField('InspectAddress2__c', '');
jsonGenerator.writeObjectField('InspectCity__c', objScheduleServiceWrapper.City);
jsonGenerator.writeObjectField('InspectState__c', objScheduleServiceWrapper.State);
jsonGenerator.writeObjectField('InspectZip__c', objScheduleServiceWrapper.ZipCode);
jsonGenerator.writeObjectField('ContactPhone__c', objScheduleServiceWrapper.ContactPhone);
jsonGenerator.writeObjectField('ContactPhoneExtension__c', nfm_Utils.IfNull(objScheduleServiceWrapper.ContactPhoneExtension,''));
}
if (isIndependentServicer) {
//specific fields
String servicerCode = Test.isRunningTest() ? '12345' : objIndependentServicerWrapper.Servicer;
jsonGenerator.writeObjectField('Servicer__c', servicerCode); //servicer 5-digit code
//common fields
jsonGenerator.writeObjectField('InspectAddress1__c', objIndependentServicerWrapper.Address);
jsonGenerator.writeObjectField('InspectAddress2__c', '');
jsonGenerator.writeObjectField();
jsonGenerator.writeObjectField('InspectCity__c', objIndependentServicerWrapper.City);
jsonGenerator.writeObjectField('InspectState__c', objIndependentServicerWrapper.State);
jsonGenerator.writeObjectField('InspectZip__c', objIndependentServicerWrapper.ZipCode);
jsonGenerator.writeObjectField('InspectName__c', objIndependentServicerWrapper.CustomerName);
jsonGenerator.writeObjectField('ContactPhone__c', objIndependentServicerWrapper.ContactPhone);
jsonGenerator.writeObjectField('ContactPhoneExtension__c', nfm_Utils.IfNull(objIndependentServicerWrapper.ContactPhoneExtension,''));
}
String jsonBody = '\'' + jsonGenerator.getAsString() + '\'';
String jsonResult = nfm_FurnitureServicesCallout.upsertFurnitureServicesCallout(jsonBody);
String result = '';
if(!Test.isRunningTest()){
Map<String, Object> jsonResultMap = (Map<String, Object>) JSON.deserializeUntyped(jsonResult);
String[] furnitureServicesFieldsList = new List<String>{ 'ExternalId','Id','AppointmentUnits__c','InspectAddress1__c','InspectName__c','InspectDate__c' };
Map<String,String> furnitureServicesFieldValueMap = new Map<String,String>();
furnitureServicesFieldValueMap.put('ClaimId__c', String.valueOf(jsonResultMap.get('ClaimId')));
FurnitureServices__x objFurnitureServices = nfm_ExternalFurnitureServicesRequest.getFurnitureServices(furnitureServicesFieldsList, furnitureServicesFieldValueMap, 'Id', 'ASC')[0];
UserActivityController.createRecord(objScheduleServiceWrapper.ButtonLabel, 'Claim', objScheduleServiceWrapper.ClaimId);
if(isIndependentServicer){
updateServiceAssignedDate(objIndependentServicerWrapper.CaseId, Date.newInstance(Integer.valueOf(inspectDateYear), Integer.valueOf(inspectDateMonth), Integer.valueOf(inspectDateDay)));
}
return objFurnitureServices.Id;
} else {
result = 'ok';
}
return result;
}
public static FurnitureServices__x getPreviousFurnitureService(String claimId){
Map<String,String> furnitureServicesFieldValueMap = new Map<String,String>();
furnitureServicesFieldValueMap.put('ClaimId__c', claimId);
return nfm_ExternalFurnitureServicesRequest.getFurnitureServices(SObjectUtils.getAllFieldsAPINames('FurnitureServices__x'), furnitureServicesFieldValueMap, 'Id', 'ASC')[0];
}
#AuraEnabled
public static List<FurnitureServiceRoutes__x> getFurnitureServiceRoutes(String startDate,String numberOfDays,String zipCode){
String[] furnitureServiceRoutesFieldsList = new List<String>{
'Id', 'NumberOfDays__c', 'RouteCode__c', 'RouteDescription__c', 'ServiceCode__c', 'StartDate__c', 'ZipCode__c'
};
Map<String,String> furnitureServiceRoutesFieldValueMap = new Map<String,String>();
furnitureServiceRoutesFieldValueMap.put('NumberOfDays__c',numberOfDays);
furnitureServiceRoutesFieldValueMap.put('StartDate__c',startDate);
furnitureServiceRoutesFieldValueMap.put('ZipCode__c',zipCode);
return nfm_ExternalFurnitureServiceRoutesReq.getFurnitureServiceRoutes(furnitureServiceRoutesFieldsList, furnitureServiceRoutesFieldValueMap, 'RouteCode__c', 'ASC');
}
#AuraEnabled
public static List<FurnitureServiceAppointments__x> getFurnitureServiceAppointments(String startDate,String numberOfDays,String zipCode, String routeCode){
String[] furnitureServiceAppointmentsFieldsList = new List<String>{
'Id', 'AppointmentUnits__c', 'ServiceDate__c', 'StartDate__c', 'ZipCode__c','RouteCode__c'
};
Map<String,String> furnitureServiceAppointmentsFieldValueMap = new Map<String,String>();
furnitureServiceAppointmentsFieldValueMap.put('NumberOfDays__c',numberOfDays);
furnitureServiceAppointmentsFieldValueMap.put('StartDate__c',startDate);
furnitureServiceAppointmentsFieldValueMap.put('ZipCode__c',zipCode);
furnitureServiceAppointmentsFieldValueMap.put('RouteCode__c',routeCode);
return nfm_ExternalFurnitureServiceAppRequest.getFurnitureServiceAppointments(furnitureServiceAppointmentsFieldsList, furnitureServiceAppointmentsFieldValueMap, 'RouteCode__c', 'ASC');
}
#AuraEnabled
public static Boolean hasAccessToIndependentServicerPermset(){
Id userId = UserInfo.getUserId();
String permsetApiName = 'Custom_Contact_Center_Support_Team';
return nfm_Utils.isPermsetAssignedToUser(userId, permsetApiName);
}
**#AuraEnabled
public static Case retrieveCaseObject(Id caseId){
return [
SELECT
Id, Shipping_Address_1__c, Shipping_Address_2__c, Shipping_City__c, Shipping_State__c,
Shipping_Postal_Code__c, Call_Back_Contact__c, Requested_Call_Back_Number__c,
Requested_Call_Back_Number_Ext__c ,Independent_Servicer__r.Id, Independent_Servicer__r.Servicer_Id__c, Independent_Servicer__r.Name
FROM Case
WHERE Id = :caseId
LIMIT 1
];
}**
public static void updateServiceAssignedDate(Id caseId, date newDate){
Case objCase = [SELECT Id, Service_Assigned_Date__c FROM Case WHERE Id = :caseId LIMIT 1];
objCase.Service_Assigned_Date__c = newDate;
update objCase;
}
}
method to fetch case record
fetchCaseData : function(component, event, helper) {
var caseRecord = component.get('v.caseRecord');
var newCaseId = caseRecord.recordId;
var retrieveCaseAction = component.get('c.retrieveCaseObject');
var actionParams = {'caseId':newCaseId};
retrieveCaseAction.setParams(actionParams);
retrieveCaseAction.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
var result = response.getReturnValue();
//console.log('RESULT: ' + JSON.stringify(result));
var currentCaseRecord = component.get('v.caseRecord');
result.label = currentCaseRecord.label;
result.recordId = currentCaseRecord.recordId;
component.set('v.caseRecord', result);
component.set('v.isLoading', false);
} else {
console.log(response.getError());
}
});
$A.enqueueAction(retrieveCaseAction);
},
when clicked on reschedule spinner should not spin continuously
enter image description here
enter image description here
should be able to reschedule
Needs more info (but too long for comment).
Which JS function is called when that button (quick action?) is clicked? It doesn't look like you followed the customary {!c.doInit} naming convention.
You pasted a lot of code, servicer_id__c appears in 3 places. Next time try to cut the useless pieces until you're left with Minimal Reproducible Example.
Check Apex Developer Console for errors / problems, maybe one of the functions genuinely returns null / throws error:
lack of permissions to run this apex class
really bad data (Case without some lookup populated?)
maybe you carefully created a wrapper class to hold stuff returned from apex - but you forgot to mark every field as public and #AuraEnabled
I suspect the bad code is around places like caseRecord.Independent_Servicer__r.Servicer_Id__c in isIndependentServicerCheckedChanged. You don't check if the middle part is null. A ternary operator or optional chaining could make it easier to spot.
Enable Setup -> Debug mode (if not done already) and next time just click that error logged in JavaScript console. You'll be taken to the line in source code where it happened. It won't look exactly like your source code (SF transpiles a bit and merges multiple files into 1) but it should be close enough for you to recognise and fix the mistake. Or at least put some breakpoints / watches.
I have created a test class with 51% code coverage till line no 34.
Further, I tried to satisfy if condition but I couldn't. Now I am not getting how to do with 100% code coverage.
Here is the Apex class:
public class AssignProjectController {
public String CaseIds;
public String status {get;set;}
public List<Project__c> activeProjects {get;set;}
public String keyWordSearched {get;set;}
public Id projectId {get;set;}
public AssignProjectController (){
CaseIds = ApexPages.currentPage().getParameters().get('id');
}
public void getProjects(){
status = '';
String searchQuery = 'FIND \'' + keyWordSearched + '*\' IN ALL FIELDS RETURNING Project__c (id,Name,Description__c where Status__c =\'Active\')';
try{
List<List<Project__c >> searchList = search.query(searchQuery);
activeProjects = searchList[0];
if(activeProjects.size() == 0) status = 'No search result found.';
}catch(Exception ex){
system.debug('ex..'+ex.getMessage());
}}}
public PageReference assignProjectToCases(){
List<Case__c> customSettingList = Case__c.getall().values();
List<String> settingRecordTypeList = new List<String>();
for(Case__c caseObj:customSettingList){
settingRecordTypeList.add(caseObj.Name);
}
List<RecordType> recordTypeListData = [SELECT Id FROM RecordType WHERE SObjectType = 'Case' and Name In : settingRecordTypeList];
if(CaseIds != null){
List<String> caseIDList = new List<String>();
caseIDList = CaseIds.split(',');
if([Select id from Case where Id In : caseIDList and RecordType.Id NOT In : recordTypeListData].size() > 0){
status = 'failed';
}else{
List<Case> cases = [Select id,Project__c,RecordType.Name from Case where Id In : caseIDList and RecordType.Id In : recordTypeListData];
if(cases.size() > 0){
for(case caseOb: cases){
caseOb.Project__c = projectId ;
}
try{
update cases ;
status = 'Changes are scheduled';
}catch(Exception ex){
system.debug('AssignProjectController :::'+ex.getMessage());
status = 'Something Went Wrong';
}}}}
return null;
}}
Here is the test class- which I tried to resolve
#isTest public class TestAssignProjectController {
public static Project__c insertProject(){
Project__c proObj = new Project__c();
proObj.Name = 'testProject';
proObj.Status__c = 'Active';
proObj.Description__c = 'for testing';
proObj.Internal_Email_Alias__c = 'a#test.com';
return proObj;
}
public static Account getAccount(){
Account accoObj = new Account();
accoObj.Name = 'testAcc';
accoObj.Location__c = 'testLocation';
accoObj.Type = 'CM';
accoObj.BillingCountry = 'United States';
return accoObj;
}
public static Contact insertContact(Account accObj){
Contact conObj = new Contact();
conObj.FirstName = 'test';
conObj.LastName = 'testLastname';
conObj.AccountId = accObj.Id;
conObj.Email = 'abc#gmail.com';
return conObj;
}
public static Id getTechTypeId(){
return Schema.SObjectType.Case.getRecordTypeInfosByName().get('Tech ').getRecordTypeId();
}
public static Case insertCase(String conId, String proId){
Case caseObj = new Case();
caseObj.Project__c = proId;
caseObj.ContactId = conId;
caseObj.Status = 'Open';
caseObj.Inquiry_Type__c = 'All';
caseObj.Subject = 'TestSubject';
caseObj.Description = 'TestDescription';
caseObj.Case_Is_Reopened__c = false;
caseObj.RecordTypeId = getTechTypeId();
return caseObj;
}
public static testmethod void testMethodExecution(){
AssignController asigncon = new AssignController ();
Project__c proObj = insertProject();
insert proObj;
System.assertEquals(proObj.Status__c,'Active');
Account accObj = getAccount();
insert accObj;
System.assertNotEquals(accObj.Id,null);
Contact conObj = insertContact(accObj);
insert conObj;
System.assertNotEquals(conObj.Id,null);
Case caseObj = insertCase(conObj.Id, proObj.Id);
insert caseObj;
system.debug(caseObj);
//Set baseURL & case ID
PageReference pageRef = Page.Assign;
pageRef.getParameters().put('id',caseObj.id+',');
AssignController asigncon1 = new AssignController ();
asigncon1.getProjects();
asigncon1.assignProjectToCases();
}}
If you are referring if(cases.size() > 0) this statement, then surely there is problem of inserting the case. Make sure that insert caseObj; is working and inserts data in Salesforce backend.
If there is no data in case object, the test method cannot cover the if statement.
I have a class where in I am trying to call a HTTP request. I have created a Mock Test and a Test class.
My Test class is successful with 28% code coverage but it fails in recognizing the call out methods I have used in my class Below is code
My Class -
public class PD_WelcomeMaroPost {
#future(callout=true)
public static void sendEmailThroughMaro(string myInpEmail) {
string successContacts = '';
string failureContacts = '';
List<Stripe_Subscripton__c> subsToUpdate = new List<Stripe_Subscripton__c>();
//List<Case> newCase = new List<Case>();
// SQL to fetch FBO who Joined Today
list<Account> conts = new list<Account> ([SELECT Id, name, Email_FLP_com__c,
(SELECT Id FROM Stripe_Subscriptons__r WHERE Start_Date__c= TODAY
AND Status__c='active'
AND Welcome_Email__C = false LIMIT 1)from account
where ID IN (select Distributor__c from Stripe_Subscripton__c
where Start_Date__c= TODAY AND Status__c='active'
AND Welcome_Email__C = false)
AND Email_FLP_com__c != NULL LIMIT 100]);
system.debug('>>>>>>>>>>' + conts);
overallEmail myEmail = new overallEmail();
for(Account c : conts){
string resultBodyGet = '';
myEmail.email.campaign_id = 172;
myEmail.email.contact.Email = c.Email_FLP_com__c;
myEmail.email.contact.first_name = c.name;
/**MAp<String, String> tags = new Map<String, String>();
tags.put('firstName', c.name);
myEmail.email.tags = tags;**/
system.debug('#### Input JSON: ' + JSON.serialize(myEmail));
try{
String endpoint = 'http://api.maropost.com/accounts/1173/emails/deliver.json?auth_token=j-V4sx8ueUT7eKM8us_Cz5JqXBzoRrNS3p1lEZyPUPGcwWNoVNZpKQ';
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setHeader('Content-type', 'application/json');
req.setbody(JSON.serialize(myEmail));
Http http = new Http();
system.debug('Sending email');
HTTPResponse response = http.send(req);
system.debug('sent email');
resultBodyGet = response.getBody();
system.debug('Output response:' + resultBodyGet);
maroResponse myMaroResponse = new maroResponse();
myMaroResponse = (maroResponse) JSON.deserialize(resultBodyGet, maroResponse.class);
system.debug('#### myMaroResponse: ' + myMaroResponse);
if(myMaroResponse.message == 'Email was sent successfully')
successContacts = successContacts + ';' + c.Email_FLP_com__c;
else
failureContacts = failureContacts + ';' + c.Email_FLP_com__c;
}
catch (exception e) {
failureContacts = failureContacts + ';' + c.Email_FLP_com__c;
system.debug('#### Exception caught: ' + e.getMessage());
}
c.Stripe_Subscriptons__r[0].Welcome_Email__c = true;
c.Stripe_Subscriptons__r[0].Welcome_Email_Sent_Date__c = system.today();
subsToUpdate.add(c.Stripe_Subscriptons__r[0]);
}
Update subsToUpdate;
}
public class maroResponse {
public string message {get;set;}
}
public class overallEmail {
public emailJson email = new emailJson();
}
public class emailJson {
public Integer campaign_id;
public contactJson contact = new contactJson();
//Public Map<String, String> tags;
}
public class contactJson {
public string email;
public string first_name;
}
}
My MockTest Class- I have used this Mockclass to generate Mock response. The documentation does not have a test method thus used the same format
#isTest
Global class PD_WelcomeMaroPostMock implements HttpCalloutMock {
Global HttpResponse respond(HttpRequest req) {
// Create a fake response
//
//System.assertEquals(JSON.serialize(myEmail),req.getbody());
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{"status":"success"}');
res.setStatusCode(200);
return res;
}
}
This is my Test class - This is the class I have used for the response. I have a successful insert job but my HTTP responses are failing.
#IsTest
private class PD_WelcomeMaroPost_test {
public class overallEmail {
public emailJson email = new emailJson();
}
public class emailJson {
public Integer campaign_id;
public contactJson contact = new contactJson();
}
public class contactJson {
public string email;
public string first_name;
}
#IsTest
private static void testemail() {
overallEmail myEmail = new overallEmail();
Account a = new Account();
a.Name ='Test' ;
a.Email_FLP_com__c = 'test#nextsphere.com';
insert a ;
Stripe_Subscripton__c s = new Stripe_Subscripton__c();
// insert subscription --
s.Distributor__c = a.Id;
S.Welcome_Email__c = TRUE;
S.Welcome_Email_Sent_Date__c = system.today();
s.Subscription_Id__c = 'sub_9H0LLYFZkekdMA' ;
INSERT S;
Test.setMock(HttpCalloutMock.class, new PD_WelcomeMaroPostMock());
String endpoint = 'http://api.maropost.com/accounts/1173/emails/deliver.json?auth_token=j-V4sx8ueUT7eKM8us_Cz5JqXBzoRrNS3p1lEZyPUPGcwWNoVNZpKQ';
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setHeader('Content-type', 'application/json');
req.setbody(JSON.serialize(myEmail));
Test.startTest();
PD_WelcomeMaroPost.sendEmailThroughMaro('test#nextsphere.com');
Test.stopTest();
}
}
When declaring a Mock myself, I declare it inside the test start transaction:
Test.startTest();
Test.setMock(WebServiceMock.class, new WebServiceMockImpl());
// Rest of test code here
Test.stopTest();
Also inside your test class you seem to only build the HTTP request and not send it try adding the below:
HttpResponse res = http.send(req);
if (res.getStatusCode() == 200) { } else { }