- Rahavan Arumugam Alamelu
- NEWBIE
- 0 Points
- Member since 2017
-
ChatterFeed
-
0Best Answers
-
0Likes Received
-
0Likes Given
-
6Questions
-
25Replies
Test class for csv upload functionality with comma included in the column value
Hi All,
Can someone help me in writing the test class to cover the scenraio of uploading the data from the csv file. Few columns has the comma within their values.
Below is my code:
public class fileUpload
{
public Boolean btndis
{
get;set;
}
public Blob csvFileBody
{
get;set;
}
public string csvAsString
{
get;set;
}
public list<Wrapper> wrapList
{
get;set;
}
public Map<string, List<Wrapper>> wrapmap
{
get;set;
}
public string[] FileLines = new string[]{};
public set<string> StoreName = new set<string>();
public List<Store__c> StoreList = new List<Store__c>();
public Map<string, Id> StoreMap = new Map<string, Id>();
public List<Analyst_Schedule__c> AnalystList = new List<Analyst_Schedule__c>();
public List<Analyst_Schedule__c> FinalAnalystList = new List<Analyst_Schedule__c>();
Integer startIndex, endIndex;
public CSVUpload(ApexPages.StandardController controller)
{
}
public class Wrapper
{
public string AnalystName
{
get;set;
}
public string StoreName
{
get;set;
}
public Date StartDate
{
get;set;
}
public Date EndDate
{
get;set;
}
public string ScheduleConfirmed
{
get;set;
}
public string comments
{
get;set;
}
public string Activity
{
get;set;
}
}
public void ImportSchedule()
{
try
{
if(csvFileBody == null)
{
ApexPages.Message Message1 = new ApexPages.Message(ApexPages.severity.INFO, 'Please attach Attendees List');
ApexPages.addMessage(Message1);
}
else
{
btndis = true;
wrapList = new List<Wrapper>();
wrapmap = new map<string, List<Wrapper>>();
csvAsString = csvFileBody.toString();
FileLines = csvAsString.split('\n');
system.debug('file size is ' + FileLines.size());
if(FileLines.size() > 1)
{
system.debug('inside line 57 loop');
string[] csvRecordDataB = FileLines[0].split(',');
if(csvRecordDataB[0].contains('Chain') && csvRecordDataB[1].contains('Location') && csvRecordDataB[2].contains('Schedule Confirmed') && csvRecordDataB[3].contains('Region') && csvRecordDataB[4].contains('Analyst') && csvRecordDataB[5].contains('Activity') && csvRecordDataB[6].contains('Comments') && csvRecordDataB[7].contains('Start Date') && csvRecordDataB[8].contains('End Date'))
{
system.debug('FileLines size: ' + FileLines.size());
for(Integer i = 1; i < FileLines.size(); i++)
{
if(FileLines[i].replaceAll(',', '').trim().length() == 0)
{
break;
}
while (FileLines[i].indexof('"') > -1)
{
if(startIndex == null)
{
startIndex = FileLines[i].indexof('"');
FileLines[i] = FileLines[i].subString(0, startIndex) + ':quotes:' + FileLines[i].subString(startIndex + 1, FileLines[i].length());
}
else
{
if(endIndex == null)
{
endIndex = FileLines[i].indexof('"');
FileLines[i] = FileLines[i].subString(0, endIndex) + ':quotes:' + FileLines[i].subString(endIndex + 1, FileLines[i].length());
}
}
if(startIndex != null && endIndex != null)
{
string sub = FileLines[i].substring(startIndex, endIndex);
sub = sub.replaceall(',', ':comma:');
FileLines[i] = FileLines[i].substring(0, startIndex) + sub + FileLines[i].substring(endIndex, FileLines[i].length());
startIndex = null;
endIndex = null;
}
}
string[] csvRecordData = FileLines[i].split(',');
Wrapper wrap = new Wrapper();
wrap.StoreName = csvRecordData[1].replaceAll(':quotes:', '').replaceAll(':comma:', ',');
wrap.AnalystName = csvRecordData[4];
wrap.Activity = csvRecordData[5].replaceAll(':quotes:', '').replaceAll(':comma:', ',');
wrap.Comments = csvRecordData[6].replaceAll(':quotes:', '').replaceAll(':comma:', ',');
string[] startDate = string.valueof(csvRecordData[7].trim()).split('/');
wrap.StartDate = Date.parse(startDate[0] + '/' + startDate[1] + '/' + startDate[2]);
string[] endDate = string.valueof(csvRecordData[8].trim()).split('/');
wrap.EndDate = Date.parse(endDate[0] + '/' + endDate[1] + '/' + endDate[2]);
if(wrapMap.containsKey(wrap.StoreName))
{
wrapmap.get(wrap.StoreName).add(wrap);
}
else
{
wraplist.add(wrap);
wrapMap.put(wrap.StoreName, new List<Wrapper>(wraplist));
wraplist.clear();
}
StoreName.add(wrap.StoreName);
system.debug(wrapMap.size());
system.debug(wrapMap.values());
}
StoreList = [SELECT id,Name FROM Store__c WHERE Name = : StoreName];
for(Store__c s: StoreList)
{
StoreMap.put(s.Name, s.Id);
system.debug(StoreMap.values());
}
for(string StoreName: wrapMap.keyset())
{
for(Wrapper wr: wrapMap.get(StoreName))
{
Analyst_Schedule__c An = new Analyst_Schedule__c();
An.Name = wr.AnalystName;
An.Store__c = StoreMap.get(wr.StoreName);
An.Comments__c = wr.comments;
An.Start_Date__c = wr.StartDate;
An.End_Date__c = wr.EndDate;
An.Activity__c = wr.Activity;
AnalystList.add(An);
}
FinalAnalystList.addall(AnalystList);
AnalystList.clear();
}
if(FinalAnalystList.size() > 0)
{
Insert FinalAnalystList;
ApexPages.Message Message2 = new ApexPages.Message(ApexPages.severity.CONFIRM, 'Analysts Data Imported successfully');
ApexPages.addMessage(Message2);
}
}
else
{
btndis = true;
ApexPages.Message Message5 = new ApexPages.Message(ApexPages.severity.ERROR, 'Template format mismatch. Please use this <a href="https://hon-pmt--fpsrs--c.cs7.content.force.com/sfc/servlet.shepherd/version/download/068M0000000LqrH?asPdf=false&operationContext=CHATTER" target="_blank"><font color="darkblue"><b>template</b></font></a> to upload the users.');
ApexPages.addMessage(Message5);
}
}
else
{
btndis = true;
ApexPages.Message Message3 = new ApexPages.Message(ApexPages.severity.INFO, 'Uploaded file is Empty');
ApexPages.addMessage(Message3);
}
}
}
catch(Exception ex)
{
ApexPages.Message Message7 = new ApexPages.Message(ApexPages.severity.ERROR, 'You have encountered an error. Please );
}
}
}
Can someone help me in writing the test class to cover the scenraio of uploading the data from the csv file. Few columns has the comma within their values.
Below is my code:
public class fileUpload
{
public Boolean btndis
{
get;set;
}
public Blob csvFileBody
{
get;set;
}
public string csvAsString
{
get;set;
}
public list<Wrapper> wrapList
{
get;set;
}
public Map<string, List<Wrapper>> wrapmap
{
get;set;
}
public string[] FileLines = new string[]{};
public set<string> StoreName = new set<string>();
public List<Store__c> StoreList = new List<Store__c>();
public Map<string, Id> StoreMap = new Map<string, Id>();
public List<Analyst_Schedule__c> AnalystList = new List<Analyst_Schedule__c>();
public List<Analyst_Schedule__c> FinalAnalystList = new List<Analyst_Schedule__c>();
Integer startIndex, endIndex;
public CSVUpload(ApexPages.StandardController controller)
{
}
public class Wrapper
{
public string AnalystName
{
get;set;
}
public string StoreName
{
get;set;
}
public Date StartDate
{
get;set;
}
public Date EndDate
{
get;set;
}
public string ScheduleConfirmed
{
get;set;
}
public string comments
{
get;set;
}
public string Activity
{
get;set;
}
}
public void ImportSchedule()
{
try
{
if(csvFileBody == null)
{
ApexPages.Message Message1 = new ApexPages.Message(ApexPages.severity.INFO, 'Please attach Attendees List');
ApexPages.addMessage(Message1);
}
else
{
btndis = true;
wrapList = new List<Wrapper>();
wrapmap = new map<string, List<Wrapper>>();
csvAsString = csvFileBody.toString();
FileLines = csvAsString.split('\n');
system.debug('file size is ' + FileLines.size());
if(FileLines.size() > 1)
{
system.debug('inside line 57 loop');
string[] csvRecordDataB = FileLines[0].split(',');
if(csvRecordDataB[0].contains('Chain') && csvRecordDataB[1].contains('Location') && csvRecordDataB[2].contains('Schedule Confirmed') && csvRecordDataB[3].contains('Region') && csvRecordDataB[4].contains('Analyst') && csvRecordDataB[5].contains('Activity') && csvRecordDataB[6].contains('Comments') && csvRecordDataB[7].contains('Start Date') && csvRecordDataB[8].contains('End Date'))
{
system.debug('FileLines size: ' + FileLines.size());
for(Integer i = 1; i < FileLines.size(); i++)
{
if(FileLines[i].replaceAll(',', '').trim().length() == 0)
{
break;
}
while (FileLines[i].indexof('"') > -1)
{
if(startIndex == null)
{
startIndex = FileLines[i].indexof('"');
FileLines[i] = FileLines[i].subString(0, startIndex) + ':quotes:' + FileLines[i].subString(startIndex + 1, FileLines[i].length());
}
else
{
if(endIndex == null)
{
endIndex = FileLines[i].indexof('"');
FileLines[i] = FileLines[i].subString(0, endIndex) + ':quotes:' + FileLines[i].subString(endIndex + 1, FileLines[i].length());
}
}
if(startIndex != null && endIndex != null)
{
string sub = FileLines[i].substring(startIndex, endIndex);
sub = sub.replaceall(',', ':comma:');
FileLines[i] = FileLines[i].substring(0, startIndex) + sub + FileLines[i].substring(endIndex, FileLines[i].length());
startIndex = null;
endIndex = null;
}
}
string[] csvRecordData = FileLines[i].split(',');
Wrapper wrap = new Wrapper();
wrap.StoreName = csvRecordData[1].replaceAll(':quotes:', '').replaceAll(':comma:', ',');
wrap.AnalystName = csvRecordData[4];
wrap.Activity = csvRecordData[5].replaceAll(':quotes:', '').replaceAll(':comma:', ',');
wrap.Comments = csvRecordData[6].replaceAll(':quotes:', '').replaceAll(':comma:', ',');
string[] startDate = string.valueof(csvRecordData[7].trim()).split('/');
wrap.StartDate = Date.parse(startDate[0] + '/' + startDate[1] + '/' + startDate[2]);
string[] endDate = string.valueof(csvRecordData[8].trim()).split('/');
wrap.EndDate = Date.parse(endDate[0] + '/' + endDate[1] + '/' + endDate[2]);
if(wrapMap.containsKey(wrap.StoreName))
{
wrapmap.get(wrap.StoreName).add(wrap);
}
else
{
wraplist.add(wrap);
wrapMap.put(wrap.StoreName, new List<Wrapper>(wraplist));
wraplist.clear();
}
StoreName.add(wrap.StoreName);
system.debug(wrapMap.size());
system.debug(wrapMap.values());
}
StoreList = [SELECT id,Name FROM Store__c WHERE Name = : StoreName];
for(Store__c s: StoreList)
{
StoreMap.put(s.Name, s.Id);
system.debug(StoreMap.values());
}
for(string StoreName: wrapMap.keyset())
{
for(Wrapper wr: wrapMap.get(StoreName))
{
Analyst_Schedule__c An = new Analyst_Schedule__c();
An.Name = wr.AnalystName;
An.Store__c = StoreMap.get(wr.StoreName);
An.Comments__c = wr.comments;
An.Start_Date__c = wr.StartDate;
An.End_Date__c = wr.EndDate;
An.Activity__c = wr.Activity;
AnalystList.add(An);
}
FinalAnalystList.addall(AnalystList);
AnalystList.clear();
}
if(FinalAnalystList.size() > 0)
{
Insert FinalAnalystList;
ApexPages.Message Message2 = new ApexPages.Message(ApexPages.severity.CONFIRM, 'Analysts Data Imported successfully');
ApexPages.addMessage(Message2);
}
}
else
{
btndis = true;
ApexPages.Message Message5 = new ApexPages.Message(ApexPages.severity.ERROR, 'Template format mismatch. Please use this <a href="https://hon-pmt--fpsrs--c.cs7.content.force.com/sfc/servlet.shepherd/version/download/068M0000000LqrH?asPdf=false&operationContext=CHATTER" target="_blank"><font color="darkblue"><b>template</b></font></a> to upload the users.');
ApexPages.addMessage(Message5);
}
}
else
{
btndis = true;
ApexPages.Message Message3 = new ApexPages.Message(ApexPages.severity.INFO, 'Uploaded file is Empty');
ApexPages.addMessage(Message3);
}
}
}
catch(Exception ex)
{
ApexPages.Message Message7 = new ApexPages.Message(ApexPages.severity.ERROR, 'You have encountered an error. Please );
}
}
}
- Rahavan Arumugam Alamelu
- August 06, 2018
- Like
- 0
how to pass multiple parameters(arguments) in the action functions oncomplete event
Hi,
Am trying to pass the multiple parameters in oncomplete event in the actionfunction component in visualforce. The oncomplete calls the javascirpt function. Trying to pass the recordid as one of the parameter(argument) in the oncomplete event.
But it is not working. Please advise.
In the command button onclick we are able to pass the record id(syssupportid) to the javascirpt:
<apex:commandButton reRender="detailsHeader1,detailsHeader2, detailsHeader3,CompDetBlockOther" value="Update" id="btnUpdateCert" styleClass="open-DeployDialog button btn btn-primary btn-right ahover" onClick="uploadFileDetails(1,'{!syssupportid}');" status="attachCertification1"/>
<apex:param name="systemIDSumm" value="{!sysSupportId}" assignTo="{!systemIDSumm}"/>
But unable to do the same in the oncomplete event of action function:
<apex:actionFunction name="AttachCertFile2" action="{!AssignCertSum}" status="uploadCertfile1" onComplete="uploadFileDetails(3,'{!sysSupportId}');">
Please advise.
Thanks
Am trying to pass the multiple parameters in oncomplete event in the actionfunction component in visualforce. The oncomplete calls the javascirpt function. Trying to pass the recordid as one of the parameter(argument) in the oncomplete event.
But it is not working. Please advise.
In the command button onclick we are able to pass the record id(syssupportid) to the javascirpt:
<apex:commandButton reRender="detailsHeader1,detailsHeader2, detailsHeader3,CompDetBlockOther" value="Update" id="btnUpdateCert" styleClass="open-DeployDialog button btn btn-primary btn-right ahover" onClick="uploadFileDetails(1,'{!syssupportid}');" status="attachCertification1"/>
<apex:param name="systemIDSumm" value="{!sysSupportId}" assignTo="{!systemIDSumm}"/>
But unable to do the same in the oncomplete event of action function:
<apex:actionFunction name="AttachCertFile2" action="{!AssignCertSum}" status="uploadCertfile1" onComplete="uploadFileDetails(3,'{!sysSupportId}');">
Please advise.
Thanks
- Rahavan Arumugam Alamelu
- May 03, 2018
- Like
- 0
how to set fontsize for pageblock title
HI
Can anyone advise how to apply font-size for pageblock title value.
<apex:outputPanel id="outputpanel" layout="block">
<apex:pageblock title="Title"">
Thanks
Can anyone advise how to apply font-size for pageblock title value.
<apex:outputPanel id="outputpanel" layout="block">
<apex:pageblock title="Title"">
Thanks
- Rahavan Arumugam Alamelu
- March 01, 2018
- Like
- 0
how to split the value of output text in multiple lines
Hi
am populatig the value from the wrapper class list ito the column in pageblock table. It works perfectly if the comment field !SD.syscomment has less characters.
The table is breaking and causig mis-alignment in the div if the comment has long values. Below is the code. please advise how to break the long comments into multiple lines within the outputtext
am populatig the value from the wrapper class list ito the column in pageblock table. It works perfectly if the comment field !SD.syscomment has less characters.
The table is breaking and causig mis-alignment in the div if the comment has long values. Below is the code. please advise how to break the long comments into multiple lines within the outputtext
<div id="syshoverPanel" style="width: 300px;height: auto;position: fixed;background-color: #FFFFFF;overflow-y: auto;border: 1px solid #C8C8C8;border-radius: 2px;z-index:9999;display:none;"> <apex:outputpanel > <apex:pageblock id="sysdetailpb"> <apex:pageblocktable value="{!SystemDetails}" var="SD" style="color:#555;"> <apex:column Style="text-align:right;"> <apex:outputText value="{!SD.sysNumber}:"></apex:outputText><br/> <apex:outputtext value="Comments:" style="font-weight:bold"> </apex:outputtext><br/> <apex:outputText value="Entitlement Number:" style="font-weight:bold"> </apex:outputText><br/> <apex:outputText value="Manufacturer:" style="font-weight:bold"></apex:outputText><br/> <apex:outputText value="Manufacturer Ref:" style="font-weight:bold"></apex:outputText><br/> <apex:outputText value="Reseller:" style="font-weight:bold"></apex:outputText><br/> <apex:outputText value="MSP:" style="font-weight:bold"></apex:outputText><br/> <apex:outputText value="L1 Support Provider:" style="font-weight:bold"></apex:outputText> </apex:column> <apex:column > <apex:outputText value="{!SD.sysAccName}"></apex:outputtext><br/> <apex:outputText value="{!SD.syscomment}"> </apex:outputText><br/> <apex:outputText value="{!SD.sysEntId}"> </apex:outputText><br/> <apex:outputText value="{!SD.sysMFG}"> </apex:outputText><br/> <apex:outputText value="{!SD.sysMFGRef}"> </apex:outputText><br/> <apex:outputText value="{!SD.sysreseller}"> </apex:outputText><br/> <apex:outputText value="{!SD.MSP}"> </apex:outputText><br/> <apex:outputText value="{!SD.sysSuppBy}"> </apex:outputText><br/> </apex:column> </apex:pageblocktable> </apex:pageblock>
- Rahavan Arumugam Alamelu
- January 13, 2018
- Like
- 0
Help on trigger for quote update to generate case for quote line item
HI All,
Currently we havfe update trigger which genreate cases for all quote line items satisfying certain condition in prodcut description on items and the status of the quote.
We need to update it, so that the only one case generated per quote. For ex: if we have more than one quote line items satisfying the condition, then the trigger should generate only one case ( not for all line items).
We have PRoduct description and quoteline item no fields on quote line items number. If more than quote line item exists, then we should get one case generated where the case description would append each quote line item number to the product description.
Below is the current code. Can you please help
if (Trigger.isUpdate && Trigger.isAfter)
{
// create ps cases
List<Id> acceptedQuoteIds = new List<Id>();
for (Quote q : Trigger.New)
{
if (q.Status == 'Accepted' && Trigger.oldMap.get(q.Id).Status != 'Accepted')
{
acceptedQuoteIds.add(q.Id);
}
}
System.debug('***** accepted Quote Ids : ' +acceptedQuoteIds);
if (acceptedQuoteIds.size() > 0) {
//Fetching the assignment rules on case
AssignmentRule AR = new AssignmentRule();
AR = [select id from AssignmentRule where SobjectType = 'Case' and Active = true limit 1];
RecordType rt = [SELECT Id FROM RecordType WHERE developername = 'Pre_Sales_Case' limit 1];
//Creating the DMLOptions for "Assign using active assignment rules" checkbox
Database.DMLOptions dmlOpts = new Database.DMLOptions();
dmlOpts.assignmentRuleHeader.assignmentRuleId = AR.id;
List<QuoteLineItem> qlis = [SELECT Product_Description__c, QuoteId, Quote.Ship_To_Account__c, Quote.Opportunity.AccountId, Id, TotalPrice FROM QuoteLineItem where (Product_Description__c like 'Service%' or pricebookentry.productcode like 'SVCPS%' or pricebookentry.productcode like 'MHASOL%' or Product_Type__c = 'Service') and QuoteId in :acceptedQuoteIds];
System.debug('***** quote line item : ***** ' +qlis);
List<Case> cases = new List<Case>();
for (QuoteLineItem qli : qlis)
{
Case c = new Case();
c.Subject = 'PS engagement - q: ' + Trigger.newMap.get(qli.QuoteId).QuoteNumber;
c.PS_Quote__c = qli.QuoteId;
c.Quote_Line_Item__c = qli.Id;
c.Status = 'INT';
c.INT_department__c = 'Professional Services';
c.Severity__c = 'Sev4 – Informational';
c.Reported_Version__c = 'N/A';
c.Description = qli.Product_Description__c;
// c.AccountId = Trigger.newMap.get(qli.QuoteId).Ship_To_Account__c;
// c.Partner_Account__c = qli.Quote.Ship_To_Account__c;
c.Partner_Account__c = Trigger.newMap.get(qli.QuoteId).Ship_To_Account__c;
c.AccountId = qli.Quote.Opportunity.AccountId;
c.Reason = 'Professional Services';
c.Origin = 'Web';
c.Category__c = 'Professional Services';
c.Type = 'PS';
c.RecordTypeId = rt.id;
c.setOptions(dmlOpts);
//c.OwnerId =
cases.add(c);
System.debug('cases to create ***** ' + cases);
}
insert cases;
System.debug('case inserted succesfully ***** ' + cases);
}
Thanks
Currently we havfe update trigger which genreate cases for all quote line items satisfying certain condition in prodcut description on items and the status of the quote.
We need to update it, so that the only one case generated per quote. For ex: if we have more than one quote line items satisfying the condition, then the trigger should generate only one case ( not for all line items).
We have PRoduct description and quoteline item no fields on quote line items number. If more than quote line item exists, then we should get one case generated where the case description would append each quote line item number to the product description.
Below is the current code. Can you please help
if (Trigger.isUpdate && Trigger.isAfter)
{
// create ps cases
List<Id> acceptedQuoteIds = new List<Id>();
for (Quote q : Trigger.New)
{
if (q.Status == 'Accepted' && Trigger.oldMap.get(q.Id).Status != 'Accepted')
{
acceptedQuoteIds.add(q.Id);
}
}
System.debug('***** accepted Quote Ids : ' +acceptedQuoteIds);
if (acceptedQuoteIds.size() > 0) {
//Fetching the assignment rules on case
AssignmentRule AR = new AssignmentRule();
AR = [select id from AssignmentRule where SobjectType = 'Case' and Active = true limit 1];
RecordType rt = [SELECT Id FROM RecordType WHERE developername = 'Pre_Sales_Case' limit 1];
//Creating the DMLOptions for "Assign using active assignment rules" checkbox
Database.DMLOptions dmlOpts = new Database.DMLOptions();
dmlOpts.assignmentRuleHeader.assignmentRuleId = AR.id;
List<QuoteLineItem> qlis = [SELECT Product_Description__c, QuoteId, Quote.Ship_To_Account__c, Quote.Opportunity.AccountId, Id, TotalPrice FROM QuoteLineItem where (Product_Description__c like 'Service%' or pricebookentry.productcode like 'SVCPS%' or pricebookentry.productcode like 'MHASOL%' or Product_Type__c = 'Service') and QuoteId in :acceptedQuoteIds];
System.debug('***** quote line item : ***** ' +qlis);
List<Case> cases = new List<Case>();
for (QuoteLineItem qli : qlis)
{
Case c = new Case();
c.Subject = 'PS engagement - q: ' + Trigger.newMap.get(qli.QuoteId).QuoteNumber;
c.PS_Quote__c = qli.QuoteId;
c.Quote_Line_Item__c = qli.Id;
c.Status = 'INT';
c.INT_department__c = 'Professional Services';
c.Severity__c = 'Sev4 – Informational';
c.Reported_Version__c = 'N/A';
c.Description = qli.Product_Description__c;
// c.AccountId = Trigger.newMap.get(qli.QuoteId).Ship_To_Account__c;
// c.Partner_Account__c = qli.Quote.Ship_To_Account__c;
c.Partner_Account__c = Trigger.newMap.get(qli.QuoteId).Ship_To_Account__c;
c.AccountId = qli.Quote.Opportunity.AccountId;
c.Reason = 'Professional Services';
c.Origin = 'Web';
c.Category__c = 'Professional Services';
c.Type = 'PS';
c.RecordTypeId = rt.id;
c.setOptions(dmlOpts);
//c.OwnerId =
cases.add(c);
System.debug('cases to create ***** ' + cases);
}
insert cases;
System.debug('case inserted succesfully ***** ' + cases);
}
Thanks
- Rahavan Arumugam Alamelu
- September 15, 2017
- Like
- 0
ExecuteBatchApex
Am unable to execute the apex batch class. Getting error as "Method does not exist or incorrect signature: void executeBatch(UserDeactivation_batchable) from the type Database"
Apex batchable class:
global class UserDeactivation_Batchable implements Database.Batchable<sObject>
{
Batch_Job_Settings__c batchJobSettings = Batch_Job_Settings__c.getInstance('Batch Job Settings');
Decimal DAYS_IN_THE_PAST = batchJobSettings.UD_Days_After_Last_Modified__c;
String ERROR_EMAIL= batchJobSettings.batchJobSettings;
String PROFILE_NAME = batchJobSettings.UD_Profile_Name__c;
String INACTIVE_TEXT = batchJobSettings.UD_Inactive_Text__c;
Date thresholdDate = System.today().addDays(-DAYS_IN_THE_PAST.intValue());
Integer year = thresholdDate.year();
String month;
if (thresholdDate.month() < 10) {month = '0' + thresholdDate.month();}
else
{
month = thresholdDate.month().format();
}
String day;
if (thresholdDate.day() < 10) {
day = '0' + thresholdDate.day();
} else {
day = thresholdDate.day().format();
}
String thresholdDateString = year +'-'+ month +'-'+ day + 'T23:59:59Z';
query='SELECT Id, isActive, ProfileId, Email, UserName, CommunityNickname, FederationIdentifier, Federation_Id_2__c User WHERE Profile.Name = \'' + PROFILE_NAME + '\ AND isActive = true AND LastModifiedDate <= ' + thresholdDateString;
global Database.QueryLocator start(Database.BatchableContext BC)
{
System.debug(System.LoggingLevel.DEBUG, '##DEBUG: START - query: ' + query);
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<User> users)
{
System.debug(System.LoggingLevel.DEBUG, '##DEBUG: execute begin. Number of users to process: ' + users.size());
for (User inactiveProfileUser : users)
{
inactiveProfileUser.isActive=false;
inactiveProfileUser.Username=INACTIVE_TEXT + inactiveProfileUser.UserName;
}
System.debug(System.LoggingLevel.DEBUG,'##DEBUG: Database Update List of Users: ' + users.size());
List<Database.SaveResult> userSaveResults=Database.update(users, false);
System.debug(System.LoggingLevel.DEBUG, 'Loop through list of saved results'+ userSaveResults.size());
List<String> userDeactivationUpdateErrors =new List<String>();
for(Integer counter=0;counter<userSaveResults.size();counter++)
{
Database.SaveResult userSaveResult=userSaveResults[counter];
if(!userSaveResult.isSuccess())
System.debug(System.LoggingLevel.DEBUG,'##DEBUG: Errors exist for this userSave: ' + userSaveResult);
for(Database.Error error:userSaveResult.getErrors())
{
String errorMessageAndCode = 'User Deactivation Errors for User: ' + users[counter].Id + ': ';
errorMessageAndCode += error.getStatusCode() +':'+ error.getMessage();
userDeactivationUpdateErrors.add(errorMessageAndCode);
}
}
if(!userDeactivationUpdateErrors.isEmpty())
{
System.debug('##DEBUG: userDeactivationUpdateErrors exist: ' + userDeactivationUpdateErrors);
Messaging.SingleEmailmessage mail=new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] {ERROR_EMAIL});
mail.setSubject('User Deactivation Batch Errors:' +System.now()+':Batch Job Id:' + BC.getJobId());
String messageHtmlBody='<h2>User Deactivation Errors</h2> <br/>';
for (String userDeactivationUpdateError:userDeactivationUpdateErrors)
{
messageHtmlBody+= userDeactivationUpdateError + '<br/>'
}
mail.setHtmlBody('<p>The User Deactivation batch Apex job ' + BC.getJobId() +' had the following errors:</p>' + messageHtmlBody);
Messaging.SingleEmailMessage[mail];
}
}
global void finish(Database.BatchableContext BC) {}
}
Kindly advise.
Thanks
Rahavan
Apex batchable class:
global class UserDeactivation_Batchable implements Database.Batchable<sObject>
{
Batch_Job_Settings__c batchJobSettings = Batch_Job_Settings__c.getInstance('Batch Job Settings');
Decimal DAYS_IN_THE_PAST = batchJobSettings.UD_Days_After_Last_Modified__c;
String ERROR_EMAIL= batchJobSettings.batchJobSettings;
String PROFILE_NAME = batchJobSettings.UD_Profile_Name__c;
String INACTIVE_TEXT = batchJobSettings.UD_Inactive_Text__c;
Date thresholdDate = System.today().addDays(-DAYS_IN_THE_PAST.intValue());
Integer year = thresholdDate.year();
String month;
if (thresholdDate.month() < 10) {month = '0' + thresholdDate.month();}
else
{
month = thresholdDate.month().format();
}
String day;
if (thresholdDate.day() < 10) {
day = '0' + thresholdDate.day();
} else {
day = thresholdDate.day().format();
}
String thresholdDateString = year +'-'+ month +'-'+ day + 'T23:59:59Z';
query='SELECT Id, isActive, ProfileId, Email, UserName, CommunityNickname, FederationIdentifier, Federation_Id_2__c User WHERE Profile.Name = \'' + PROFILE_NAME + '\ AND isActive = true AND LastModifiedDate <= ' + thresholdDateString;
global Database.QueryLocator start(Database.BatchableContext BC)
{
System.debug(System.LoggingLevel.DEBUG, '##DEBUG: START - query: ' + query);
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<User> users)
{
System.debug(System.LoggingLevel.DEBUG, '##DEBUG: execute begin. Number of users to process: ' + users.size());
for (User inactiveProfileUser : users)
{
inactiveProfileUser.isActive=false;
inactiveProfileUser.Username=INACTIVE_TEXT + inactiveProfileUser.UserName;
}
System.debug(System.LoggingLevel.DEBUG,'##DEBUG: Database Update List of Users: ' + users.size());
List<Database.SaveResult> userSaveResults=Database.update(users, false);
System.debug(System.LoggingLevel.DEBUG, 'Loop through list of saved results'+ userSaveResults.size());
List<String> userDeactivationUpdateErrors =new List<String>();
for(Integer counter=0;counter<userSaveResults.size();counter++)
{
Database.SaveResult userSaveResult=userSaveResults[counter];
if(!userSaveResult.isSuccess())
System.debug(System.LoggingLevel.DEBUG,'##DEBUG: Errors exist for this userSave: ' + userSaveResult);
for(Database.Error error:userSaveResult.getErrors())
{
String errorMessageAndCode = 'User Deactivation Errors for User: ' + users[counter].Id + ': ';
errorMessageAndCode += error.getStatusCode() +':'+ error.getMessage();
userDeactivationUpdateErrors.add(errorMessageAndCode);
}
}
if(!userDeactivationUpdateErrors.isEmpty())
{
System.debug('##DEBUG: userDeactivationUpdateErrors exist: ' + userDeactivationUpdateErrors);
Messaging.SingleEmailmessage mail=new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] {ERROR_EMAIL});
mail.setSubject('User Deactivation Batch Errors:' +System.now()+':Batch Job Id:' + BC.getJobId());
String messageHtmlBody='<h2>User Deactivation Errors</h2> <br/>';
for (String userDeactivationUpdateError:userDeactivationUpdateErrors)
{
messageHtmlBody+= userDeactivationUpdateError + '<br/>'
}
mail.setHtmlBody('<p>The User Deactivation batch Apex job ' + BC.getJobId() +' had the following errors:</p>' + messageHtmlBody);
Messaging.SingleEmailMessage[mail];
}
}
global void finish(Database.BatchableContext BC) {}
}
Kindly advise.
Thanks
Rahavan
- Rahavan Arumugam Alamelu
- August 24, 2017
- Like
- 0
Test class for csv upload functionality with comma included in the column value
Hi All,
Can someone help me in writing the test class to cover the scenraio of uploading the data from the csv file. Few columns has the comma within their values.
Below is my code:
public class fileUpload
{
public Boolean btndis
{
get;set;
}
public Blob csvFileBody
{
get;set;
}
public string csvAsString
{
get;set;
}
public list<Wrapper> wrapList
{
get;set;
}
public Map<string, List<Wrapper>> wrapmap
{
get;set;
}
public string[] FileLines = new string[]{};
public set<string> StoreName = new set<string>();
public List<Store__c> StoreList = new List<Store__c>();
public Map<string, Id> StoreMap = new Map<string, Id>();
public List<Analyst_Schedule__c> AnalystList = new List<Analyst_Schedule__c>();
public List<Analyst_Schedule__c> FinalAnalystList = new List<Analyst_Schedule__c>();
Integer startIndex, endIndex;
public CSVUpload(ApexPages.StandardController controller)
{
}
public class Wrapper
{
public string AnalystName
{
get;set;
}
public string StoreName
{
get;set;
}
public Date StartDate
{
get;set;
}
public Date EndDate
{
get;set;
}
public string ScheduleConfirmed
{
get;set;
}
public string comments
{
get;set;
}
public string Activity
{
get;set;
}
}
public void ImportSchedule()
{
try
{
if(csvFileBody == null)
{
ApexPages.Message Message1 = new ApexPages.Message(ApexPages.severity.INFO, 'Please attach Attendees List');
ApexPages.addMessage(Message1);
}
else
{
btndis = true;
wrapList = new List<Wrapper>();
wrapmap = new map<string, List<Wrapper>>();
csvAsString = csvFileBody.toString();
FileLines = csvAsString.split('\n');
system.debug('file size is ' + FileLines.size());
if(FileLines.size() > 1)
{
system.debug('inside line 57 loop');
string[] csvRecordDataB = FileLines[0].split(',');
if(csvRecordDataB[0].contains('Chain') && csvRecordDataB[1].contains('Location') && csvRecordDataB[2].contains('Schedule Confirmed') && csvRecordDataB[3].contains('Region') && csvRecordDataB[4].contains('Analyst') && csvRecordDataB[5].contains('Activity') && csvRecordDataB[6].contains('Comments') && csvRecordDataB[7].contains('Start Date') && csvRecordDataB[8].contains('End Date'))
{
system.debug('FileLines size: ' + FileLines.size());
for(Integer i = 1; i < FileLines.size(); i++)
{
if(FileLines[i].replaceAll(',', '').trim().length() == 0)
{
break;
}
while (FileLines[i].indexof('"') > -1)
{
if(startIndex == null)
{
startIndex = FileLines[i].indexof('"');
FileLines[i] = FileLines[i].subString(0, startIndex) + ':quotes:' + FileLines[i].subString(startIndex + 1, FileLines[i].length());
}
else
{
if(endIndex == null)
{
endIndex = FileLines[i].indexof('"');
FileLines[i] = FileLines[i].subString(0, endIndex) + ':quotes:' + FileLines[i].subString(endIndex + 1, FileLines[i].length());
}
}
if(startIndex != null && endIndex != null)
{
string sub = FileLines[i].substring(startIndex, endIndex);
sub = sub.replaceall(',', ':comma:');
FileLines[i] = FileLines[i].substring(0, startIndex) + sub + FileLines[i].substring(endIndex, FileLines[i].length());
startIndex = null;
endIndex = null;
}
}
string[] csvRecordData = FileLines[i].split(',');
Wrapper wrap = new Wrapper();
wrap.StoreName = csvRecordData[1].replaceAll(':quotes:', '').replaceAll(':comma:', ',');
wrap.AnalystName = csvRecordData[4];
wrap.Activity = csvRecordData[5].replaceAll(':quotes:', '').replaceAll(':comma:', ',');
wrap.Comments = csvRecordData[6].replaceAll(':quotes:', '').replaceAll(':comma:', ',');
string[] startDate = string.valueof(csvRecordData[7].trim()).split('/');
wrap.StartDate = Date.parse(startDate[0] + '/' + startDate[1] + '/' + startDate[2]);
string[] endDate = string.valueof(csvRecordData[8].trim()).split('/');
wrap.EndDate = Date.parse(endDate[0] + '/' + endDate[1] + '/' + endDate[2]);
if(wrapMap.containsKey(wrap.StoreName))
{
wrapmap.get(wrap.StoreName).add(wrap);
}
else
{
wraplist.add(wrap);
wrapMap.put(wrap.StoreName, new List<Wrapper>(wraplist));
wraplist.clear();
}
StoreName.add(wrap.StoreName);
system.debug(wrapMap.size());
system.debug(wrapMap.values());
}
StoreList = [SELECT id,Name FROM Store__c WHERE Name = : StoreName];
for(Store__c s: StoreList)
{
StoreMap.put(s.Name, s.Id);
system.debug(StoreMap.values());
}
for(string StoreName: wrapMap.keyset())
{
for(Wrapper wr: wrapMap.get(StoreName))
{
Analyst_Schedule__c An = new Analyst_Schedule__c();
An.Name = wr.AnalystName;
An.Store__c = StoreMap.get(wr.StoreName);
An.Comments__c = wr.comments;
An.Start_Date__c = wr.StartDate;
An.End_Date__c = wr.EndDate;
An.Activity__c = wr.Activity;
AnalystList.add(An);
}
FinalAnalystList.addall(AnalystList);
AnalystList.clear();
}
if(FinalAnalystList.size() > 0)
{
Insert FinalAnalystList;
ApexPages.Message Message2 = new ApexPages.Message(ApexPages.severity.CONFIRM, 'Analysts Data Imported successfully');
ApexPages.addMessage(Message2);
}
}
else
{
btndis = true;
ApexPages.Message Message5 = new ApexPages.Message(ApexPages.severity.ERROR, 'Template format mismatch. Please use this <a href="https://hon-pmt--fpsrs--c.cs7.content.force.com/sfc/servlet.shepherd/version/download/068M0000000LqrH?asPdf=false&operationContext=CHATTER" target="_blank"><font color="darkblue"><b>template</b></font></a> to upload the users.');
ApexPages.addMessage(Message5);
}
}
else
{
btndis = true;
ApexPages.Message Message3 = new ApexPages.Message(ApexPages.severity.INFO, 'Uploaded file is Empty');
ApexPages.addMessage(Message3);
}
}
}
catch(Exception ex)
{
ApexPages.Message Message7 = new ApexPages.Message(ApexPages.severity.ERROR, 'You have encountered an error. Please );
}
}
}
Can someone help me in writing the test class to cover the scenraio of uploading the data from the csv file. Few columns has the comma within their values.
Below is my code:
public class fileUpload
{
public Boolean btndis
{
get;set;
}
public Blob csvFileBody
{
get;set;
}
public string csvAsString
{
get;set;
}
public list<Wrapper> wrapList
{
get;set;
}
public Map<string, List<Wrapper>> wrapmap
{
get;set;
}
public string[] FileLines = new string[]{};
public set<string> StoreName = new set<string>();
public List<Store__c> StoreList = new List<Store__c>();
public Map<string, Id> StoreMap = new Map<string, Id>();
public List<Analyst_Schedule__c> AnalystList = new List<Analyst_Schedule__c>();
public List<Analyst_Schedule__c> FinalAnalystList = new List<Analyst_Schedule__c>();
Integer startIndex, endIndex;
public CSVUpload(ApexPages.StandardController controller)
{
}
public class Wrapper
{
public string AnalystName
{
get;set;
}
public string StoreName
{
get;set;
}
public Date StartDate
{
get;set;
}
public Date EndDate
{
get;set;
}
public string ScheduleConfirmed
{
get;set;
}
public string comments
{
get;set;
}
public string Activity
{
get;set;
}
}
public void ImportSchedule()
{
try
{
if(csvFileBody == null)
{
ApexPages.Message Message1 = new ApexPages.Message(ApexPages.severity.INFO, 'Please attach Attendees List');
ApexPages.addMessage(Message1);
}
else
{
btndis = true;
wrapList = new List<Wrapper>();
wrapmap = new map<string, List<Wrapper>>();
csvAsString = csvFileBody.toString();
FileLines = csvAsString.split('\n');
system.debug('file size is ' + FileLines.size());
if(FileLines.size() > 1)
{
system.debug('inside line 57 loop');
string[] csvRecordDataB = FileLines[0].split(',');
if(csvRecordDataB[0].contains('Chain') && csvRecordDataB[1].contains('Location') && csvRecordDataB[2].contains('Schedule Confirmed') && csvRecordDataB[3].contains('Region') && csvRecordDataB[4].contains('Analyst') && csvRecordDataB[5].contains('Activity') && csvRecordDataB[6].contains('Comments') && csvRecordDataB[7].contains('Start Date') && csvRecordDataB[8].contains('End Date'))
{
system.debug('FileLines size: ' + FileLines.size());
for(Integer i = 1; i < FileLines.size(); i++)
{
if(FileLines[i].replaceAll(',', '').trim().length() == 0)
{
break;
}
while (FileLines[i].indexof('"') > -1)
{
if(startIndex == null)
{
startIndex = FileLines[i].indexof('"');
FileLines[i] = FileLines[i].subString(0, startIndex) + ':quotes:' + FileLines[i].subString(startIndex + 1, FileLines[i].length());
}
else
{
if(endIndex == null)
{
endIndex = FileLines[i].indexof('"');
FileLines[i] = FileLines[i].subString(0, endIndex) + ':quotes:' + FileLines[i].subString(endIndex + 1, FileLines[i].length());
}
}
if(startIndex != null && endIndex != null)
{
string sub = FileLines[i].substring(startIndex, endIndex);
sub = sub.replaceall(',', ':comma:');
FileLines[i] = FileLines[i].substring(0, startIndex) + sub + FileLines[i].substring(endIndex, FileLines[i].length());
startIndex = null;
endIndex = null;
}
}
string[] csvRecordData = FileLines[i].split(',');
Wrapper wrap = new Wrapper();
wrap.StoreName = csvRecordData[1].replaceAll(':quotes:', '').replaceAll(':comma:', ',');
wrap.AnalystName = csvRecordData[4];
wrap.Activity = csvRecordData[5].replaceAll(':quotes:', '').replaceAll(':comma:', ',');
wrap.Comments = csvRecordData[6].replaceAll(':quotes:', '').replaceAll(':comma:', ',');
string[] startDate = string.valueof(csvRecordData[7].trim()).split('/');
wrap.StartDate = Date.parse(startDate[0] + '/' + startDate[1] + '/' + startDate[2]);
string[] endDate = string.valueof(csvRecordData[8].trim()).split('/');
wrap.EndDate = Date.parse(endDate[0] + '/' + endDate[1] + '/' + endDate[2]);
if(wrapMap.containsKey(wrap.StoreName))
{
wrapmap.get(wrap.StoreName).add(wrap);
}
else
{
wraplist.add(wrap);
wrapMap.put(wrap.StoreName, new List<Wrapper>(wraplist));
wraplist.clear();
}
StoreName.add(wrap.StoreName);
system.debug(wrapMap.size());
system.debug(wrapMap.values());
}
StoreList = [SELECT id,Name FROM Store__c WHERE Name = : StoreName];
for(Store__c s: StoreList)
{
StoreMap.put(s.Name, s.Id);
system.debug(StoreMap.values());
}
for(string StoreName: wrapMap.keyset())
{
for(Wrapper wr: wrapMap.get(StoreName))
{
Analyst_Schedule__c An = new Analyst_Schedule__c();
An.Name = wr.AnalystName;
An.Store__c = StoreMap.get(wr.StoreName);
An.Comments__c = wr.comments;
An.Start_Date__c = wr.StartDate;
An.End_Date__c = wr.EndDate;
An.Activity__c = wr.Activity;
AnalystList.add(An);
}
FinalAnalystList.addall(AnalystList);
AnalystList.clear();
}
if(FinalAnalystList.size() > 0)
{
Insert FinalAnalystList;
ApexPages.Message Message2 = new ApexPages.Message(ApexPages.severity.CONFIRM, 'Analysts Data Imported successfully');
ApexPages.addMessage(Message2);
}
}
else
{
btndis = true;
ApexPages.Message Message5 = new ApexPages.Message(ApexPages.severity.ERROR, 'Template format mismatch. Please use this <a href="https://hon-pmt--fpsrs--c.cs7.content.force.com/sfc/servlet.shepherd/version/download/068M0000000LqrH?asPdf=false&operationContext=CHATTER" target="_blank"><font color="darkblue"><b>template</b></font></a> to upload the users.');
ApexPages.addMessage(Message5);
}
}
else
{
btndis = true;
ApexPages.Message Message3 = new ApexPages.Message(ApexPages.severity.INFO, 'Uploaded file is Empty');
ApexPages.addMessage(Message3);
}
}
}
catch(Exception ex)
{
ApexPages.Message Message7 = new ApexPages.Message(ApexPages.severity.ERROR, 'You have encountered an error. Please );
}
}
}
- Rahavan Arumugam Alamelu
- August 06, 2018
- Like
- 0
how to set fontsize for pageblock title
HI
Can anyone advise how to apply font-size for pageblock title value.
<apex:outputPanel id="outputpanel" layout="block">
<apex:pageblock title="Title"">
Thanks
Can anyone advise how to apply font-size for pageblock title value.
<apex:outputPanel id="outputpanel" layout="block">
<apex:pageblock title="Title"">
Thanks
- Rahavan Arumugam Alamelu
- March 01, 2018
- Like
- 0
how to split the value of output text in multiple lines
Hi
am populatig the value from the wrapper class list ito the column in pageblock table. It works perfectly if the comment field !SD.syscomment has less characters.
The table is breaking and causig mis-alignment in the div if the comment has long values. Below is the code. please advise how to break the long comments into multiple lines within the outputtext
am populatig the value from the wrapper class list ito the column in pageblock table. It works perfectly if the comment field !SD.syscomment has less characters.
The table is breaking and causig mis-alignment in the div if the comment has long values. Below is the code. please advise how to break the long comments into multiple lines within the outputtext
<div id="syshoverPanel" style="width: 300px;height: auto;position: fixed;background-color: #FFFFFF;overflow-y: auto;border: 1px solid #C8C8C8;border-radius: 2px;z-index:9999;display:none;"> <apex:outputpanel > <apex:pageblock id="sysdetailpb"> <apex:pageblocktable value="{!SystemDetails}" var="SD" style="color:#555;"> <apex:column Style="text-align:right;"> <apex:outputText value="{!SD.sysNumber}:"></apex:outputText><br/> <apex:outputtext value="Comments:" style="font-weight:bold"> </apex:outputtext><br/> <apex:outputText value="Entitlement Number:" style="font-weight:bold"> </apex:outputText><br/> <apex:outputText value="Manufacturer:" style="font-weight:bold"></apex:outputText><br/> <apex:outputText value="Manufacturer Ref:" style="font-weight:bold"></apex:outputText><br/> <apex:outputText value="Reseller:" style="font-weight:bold"></apex:outputText><br/> <apex:outputText value="MSP:" style="font-weight:bold"></apex:outputText><br/> <apex:outputText value="L1 Support Provider:" style="font-weight:bold"></apex:outputText> </apex:column> <apex:column > <apex:outputText value="{!SD.sysAccName}"></apex:outputtext><br/> <apex:outputText value="{!SD.syscomment}"> </apex:outputText><br/> <apex:outputText value="{!SD.sysEntId}"> </apex:outputText><br/> <apex:outputText value="{!SD.sysMFG}"> </apex:outputText><br/> <apex:outputText value="{!SD.sysMFGRef}"> </apex:outputText><br/> <apex:outputText value="{!SD.sysreseller}"> </apex:outputText><br/> <apex:outputText value="{!SD.MSP}"> </apex:outputText><br/> <apex:outputText value="{!SD.sysSuppBy}"> </apex:outputText><br/> </apex:column> </apex:pageblocktable> </apex:pageblock>
- Rahavan Arumugam Alamelu
- January 13, 2018
- Like
- 0
Help on trigger for quote update to generate case for quote line item
HI All,
Currently we havfe update trigger which genreate cases for all quote line items satisfying certain condition in prodcut description on items and the status of the quote.
We need to update it, so that the only one case generated per quote. For ex: if we have more than one quote line items satisfying the condition, then the trigger should generate only one case ( not for all line items).
We have PRoduct description and quoteline item no fields on quote line items number. If more than quote line item exists, then we should get one case generated where the case description would append each quote line item number to the product description.
Below is the current code. Can you please help
if (Trigger.isUpdate && Trigger.isAfter)
{
// create ps cases
List<Id> acceptedQuoteIds = new List<Id>();
for (Quote q : Trigger.New)
{
if (q.Status == 'Accepted' && Trigger.oldMap.get(q.Id).Status != 'Accepted')
{
acceptedQuoteIds.add(q.Id);
}
}
System.debug('***** accepted Quote Ids : ' +acceptedQuoteIds);
if (acceptedQuoteIds.size() > 0) {
//Fetching the assignment rules on case
AssignmentRule AR = new AssignmentRule();
AR = [select id from AssignmentRule where SobjectType = 'Case' and Active = true limit 1];
RecordType rt = [SELECT Id FROM RecordType WHERE developername = 'Pre_Sales_Case' limit 1];
//Creating the DMLOptions for "Assign using active assignment rules" checkbox
Database.DMLOptions dmlOpts = new Database.DMLOptions();
dmlOpts.assignmentRuleHeader.assignmentRuleId = AR.id;
List<QuoteLineItem> qlis = [SELECT Product_Description__c, QuoteId, Quote.Ship_To_Account__c, Quote.Opportunity.AccountId, Id, TotalPrice FROM QuoteLineItem where (Product_Description__c like 'Service%' or pricebookentry.productcode like 'SVCPS%' or pricebookentry.productcode like 'MHASOL%' or Product_Type__c = 'Service') and QuoteId in :acceptedQuoteIds];
System.debug('***** quote line item : ***** ' +qlis);
List<Case> cases = new List<Case>();
for (QuoteLineItem qli : qlis)
{
Case c = new Case();
c.Subject = 'PS engagement - q: ' + Trigger.newMap.get(qli.QuoteId).QuoteNumber;
c.PS_Quote__c = qli.QuoteId;
c.Quote_Line_Item__c = qli.Id;
c.Status = 'INT';
c.INT_department__c = 'Professional Services';
c.Severity__c = 'Sev4 – Informational';
c.Reported_Version__c = 'N/A';
c.Description = qli.Product_Description__c;
// c.AccountId = Trigger.newMap.get(qli.QuoteId).Ship_To_Account__c;
// c.Partner_Account__c = qli.Quote.Ship_To_Account__c;
c.Partner_Account__c = Trigger.newMap.get(qli.QuoteId).Ship_To_Account__c;
c.AccountId = qli.Quote.Opportunity.AccountId;
c.Reason = 'Professional Services';
c.Origin = 'Web';
c.Category__c = 'Professional Services';
c.Type = 'PS';
c.RecordTypeId = rt.id;
c.setOptions(dmlOpts);
//c.OwnerId =
cases.add(c);
System.debug('cases to create ***** ' + cases);
}
insert cases;
System.debug('case inserted succesfully ***** ' + cases);
}
Thanks
Currently we havfe update trigger which genreate cases for all quote line items satisfying certain condition in prodcut description on items and the status of the quote.
We need to update it, so that the only one case generated per quote. For ex: if we have more than one quote line items satisfying the condition, then the trigger should generate only one case ( not for all line items).
We have PRoduct description and quoteline item no fields on quote line items number. If more than quote line item exists, then we should get one case generated where the case description would append each quote line item number to the product description.
Below is the current code. Can you please help
if (Trigger.isUpdate && Trigger.isAfter)
{
// create ps cases
List<Id> acceptedQuoteIds = new List<Id>();
for (Quote q : Trigger.New)
{
if (q.Status == 'Accepted' && Trigger.oldMap.get(q.Id).Status != 'Accepted')
{
acceptedQuoteIds.add(q.Id);
}
}
System.debug('***** accepted Quote Ids : ' +acceptedQuoteIds);
if (acceptedQuoteIds.size() > 0) {
//Fetching the assignment rules on case
AssignmentRule AR = new AssignmentRule();
AR = [select id from AssignmentRule where SobjectType = 'Case' and Active = true limit 1];
RecordType rt = [SELECT Id FROM RecordType WHERE developername = 'Pre_Sales_Case' limit 1];
//Creating the DMLOptions for "Assign using active assignment rules" checkbox
Database.DMLOptions dmlOpts = new Database.DMLOptions();
dmlOpts.assignmentRuleHeader.assignmentRuleId = AR.id;
List<QuoteLineItem> qlis = [SELECT Product_Description__c, QuoteId, Quote.Ship_To_Account__c, Quote.Opportunity.AccountId, Id, TotalPrice FROM QuoteLineItem where (Product_Description__c like 'Service%' or pricebookentry.productcode like 'SVCPS%' or pricebookentry.productcode like 'MHASOL%' or Product_Type__c = 'Service') and QuoteId in :acceptedQuoteIds];
System.debug('***** quote line item : ***** ' +qlis);
List<Case> cases = new List<Case>();
for (QuoteLineItem qli : qlis)
{
Case c = new Case();
c.Subject = 'PS engagement - q: ' + Trigger.newMap.get(qli.QuoteId).QuoteNumber;
c.PS_Quote__c = qli.QuoteId;
c.Quote_Line_Item__c = qli.Id;
c.Status = 'INT';
c.INT_department__c = 'Professional Services';
c.Severity__c = 'Sev4 – Informational';
c.Reported_Version__c = 'N/A';
c.Description = qli.Product_Description__c;
// c.AccountId = Trigger.newMap.get(qli.QuoteId).Ship_To_Account__c;
// c.Partner_Account__c = qli.Quote.Ship_To_Account__c;
c.Partner_Account__c = Trigger.newMap.get(qli.QuoteId).Ship_To_Account__c;
c.AccountId = qli.Quote.Opportunity.AccountId;
c.Reason = 'Professional Services';
c.Origin = 'Web';
c.Category__c = 'Professional Services';
c.Type = 'PS';
c.RecordTypeId = rt.id;
c.setOptions(dmlOpts);
//c.OwnerId =
cases.add(c);
System.debug('cases to create ***** ' + cases);
}
insert cases;
System.debug('case inserted succesfully ***** ' + cases);
}
Thanks
- Rahavan Arumugam Alamelu
- September 15, 2017
- Like
- 0
ExecuteBatchApex
Am unable to execute the apex batch class. Getting error as "Method does not exist or incorrect signature: void executeBatch(UserDeactivation_batchable) from the type Database"
Apex batchable class:
global class UserDeactivation_Batchable implements Database.Batchable<sObject>
{
Batch_Job_Settings__c batchJobSettings = Batch_Job_Settings__c.getInstance('Batch Job Settings');
Decimal DAYS_IN_THE_PAST = batchJobSettings.UD_Days_After_Last_Modified__c;
String ERROR_EMAIL= batchJobSettings.batchJobSettings;
String PROFILE_NAME = batchJobSettings.UD_Profile_Name__c;
String INACTIVE_TEXT = batchJobSettings.UD_Inactive_Text__c;
Date thresholdDate = System.today().addDays(-DAYS_IN_THE_PAST.intValue());
Integer year = thresholdDate.year();
String month;
if (thresholdDate.month() < 10) {month = '0' + thresholdDate.month();}
else
{
month = thresholdDate.month().format();
}
String day;
if (thresholdDate.day() < 10) {
day = '0' + thresholdDate.day();
} else {
day = thresholdDate.day().format();
}
String thresholdDateString = year +'-'+ month +'-'+ day + 'T23:59:59Z';
query='SELECT Id, isActive, ProfileId, Email, UserName, CommunityNickname, FederationIdentifier, Federation_Id_2__c User WHERE Profile.Name = \'' + PROFILE_NAME + '\ AND isActive = true AND LastModifiedDate <= ' + thresholdDateString;
global Database.QueryLocator start(Database.BatchableContext BC)
{
System.debug(System.LoggingLevel.DEBUG, '##DEBUG: START - query: ' + query);
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<User> users)
{
System.debug(System.LoggingLevel.DEBUG, '##DEBUG: execute begin. Number of users to process: ' + users.size());
for (User inactiveProfileUser : users)
{
inactiveProfileUser.isActive=false;
inactiveProfileUser.Username=INACTIVE_TEXT + inactiveProfileUser.UserName;
}
System.debug(System.LoggingLevel.DEBUG,'##DEBUG: Database Update List of Users: ' + users.size());
List<Database.SaveResult> userSaveResults=Database.update(users, false);
System.debug(System.LoggingLevel.DEBUG, 'Loop through list of saved results'+ userSaveResults.size());
List<String> userDeactivationUpdateErrors =new List<String>();
for(Integer counter=0;counter<userSaveResults.size();counter++)
{
Database.SaveResult userSaveResult=userSaveResults[counter];
if(!userSaveResult.isSuccess())
System.debug(System.LoggingLevel.DEBUG,'##DEBUG: Errors exist for this userSave: ' + userSaveResult);
for(Database.Error error:userSaveResult.getErrors())
{
String errorMessageAndCode = 'User Deactivation Errors for User: ' + users[counter].Id + ': ';
errorMessageAndCode += error.getStatusCode() +':'+ error.getMessage();
userDeactivationUpdateErrors.add(errorMessageAndCode);
}
}
if(!userDeactivationUpdateErrors.isEmpty())
{
System.debug('##DEBUG: userDeactivationUpdateErrors exist: ' + userDeactivationUpdateErrors);
Messaging.SingleEmailmessage mail=new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] {ERROR_EMAIL});
mail.setSubject('User Deactivation Batch Errors:' +System.now()+':Batch Job Id:' + BC.getJobId());
String messageHtmlBody='<h2>User Deactivation Errors</h2> <br/>';
for (String userDeactivationUpdateError:userDeactivationUpdateErrors)
{
messageHtmlBody+= userDeactivationUpdateError + '<br/>'
}
mail.setHtmlBody('<p>The User Deactivation batch Apex job ' + BC.getJobId() +' had the following errors:</p>' + messageHtmlBody);
Messaging.SingleEmailMessage[mail];
}
}
global void finish(Database.BatchableContext BC) {}
}
Kindly advise.
Thanks
Rahavan
Apex batchable class:
global class UserDeactivation_Batchable implements Database.Batchable<sObject>
{
Batch_Job_Settings__c batchJobSettings = Batch_Job_Settings__c.getInstance('Batch Job Settings');
Decimal DAYS_IN_THE_PAST = batchJobSettings.UD_Days_After_Last_Modified__c;
String ERROR_EMAIL= batchJobSettings.batchJobSettings;
String PROFILE_NAME = batchJobSettings.UD_Profile_Name__c;
String INACTIVE_TEXT = batchJobSettings.UD_Inactive_Text__c;
Date thresholdDate = System.today().addDays(-DAYS_IN_THE_PAST.intValue());
Integer year = thresholdDate.year();
String month;
if (thresholdDate.month() < 10) {month = '0' + thresholdDate.month();}
else
{
month = thresholdDate.month().format();
}
String day;
if (thresholdDate.day() < 10) {
day = '0' + thresholdDate.day();
} else {
day = thresholdDate.day().format();
}
String thresholdDateString = year +'-'+ month +'-'+ day + 'T23:59:59Z';
query='SELECT Id, isActive, ProfileId, Email, UserName, CommunityNickname, FederationIdentifier, Federation_Id_2__c User WHERE Profile.Name = \'' + PROFILE_NAME + '\ AND isActive = true AND LastModifiedDate <= ' + thresholdDateString;
global Database.QueryLocator start(Database.BatchableContext BC)
{
System.debug(System.LoggingLevel.DEBUG, '##DEBUG: START - query: ' + query);
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<User> users)
{
System.debug(System.LoggingLevel.DEBUG, '##DEBUG: execute begin. Number of users to process: ' + users.size());
for (User inactiveProfileUser : users)
{
inactiveProfileUser.isActive=false;
inactiveProfileUser.Username=INACTIVE_TEXT + inactiveProfileUser.UserName;
}
System.debug(System.LoggingLevel.DEBUG,'##DEBUG: Database Update List of Users: ' + users.size());
List<Database.SaveResult> userSaveResults=Database.update(users, false);
System.debug(System.LoggingLevel.DEBUG, 'Loop through list of saved results'+ userSaveResults.size());
List<String> userDeactivationUpdateErrors =new List<String>();
for(Integer counter=0;counter<userSaveResults.size();counter++)
{
Database.SaveResult userSaveResult=userSaveResults[counter];
if(!userSaveResult.isSuccess())
System.debug(System.LoggingLevel.DEBUG,'##DEBUG: Errors exist for this userSave: ' + userSaveResult);
for(Database.Error error:userSaveResult.getErrors())
{
String errorMessageAndCode = 'User Deactivation Errors for User: ' + users[counter].Id + ': ';
errorMessageAndCode += error.getStatusCode() +':'+ error.getMessage();
userDeactivationUpdateErrors.add(errorMessageAndCode);
}
}
if(!userDeactivationUpdateErrors.isEmpty())
{
System.debug('##DEBUG: userDeactivationUpdateErrors exist: ' + userDeactivationUpdateErrors);
Messaging.SingleEmailmessage mail=new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] {ERROR_EMAIL});
mail.setSubject('User Deactivation Batch Errors:' +System.now()+':Batch Job Id:' + BC.getJobId());
String messageHtmlBody='<h2>User Deactivation Errors</h2> <br/>';
for (String userDeactivationUpdateError:userDeactivationUpdateErrors)
{
messageHtmlBody+= userDeactivationUpdateError + '<br/>'
}
mail.setHtmlBody('<p>The User Deactivation batch Apex job ' + BC.getJobId() +' had the following errors:</p>' + messageHtmlBody);
Messaging.SingleEmailMessage[mail];
}
}
global void finish(Database.BatchableContext BC) {}
}
Kindly advise.
Thanks
Rahavan
- Rahavan Arumugam Alamelu
- August 24, 2017
- Like
- 0
How to write a trigger on Case Object whenever a case is identified in case object and it should create a issue in JIra..??
I am having a issue in Trigger. Its unable to fire..
trigger CreateWithJIRAIssue on Case (after insert) {
List<Case> escCases = new List<Case>();
for (Case c : Trigger.new){
// all the cases that have status as abc' is added to a list called xCases
if(c.Status == 'abc'){
xCases.add(c);
}
}
if(xCases != null && xCases.size()>0){
// now iterate over the selected cases and call the web service
for(Case c : xCases){
//call webservice
system.debug('inside case ' + c.CaseNumber);
//Define parameters to be used in calling Apex Class
String jiraURL = 'http://jira';
String systemId = '2';
String objectType ='Case';
String objectId = c.id;
String projectKey = 'LEV';
String issueType = 'BUG';
System.debug('\n\n status is escalated');
//Execute the web service call
JIRAConnectorWebserviceCallout.CreateIssue(jiraURL, systemId ,objectType,objectId,projectKey,issueType);
}
}
}
}
}
trigger CreateWithJIRAIssue on Case (after insert) {
List<Case> escCases = new List<Case>();
for (Case c : Trigger.new){
// all the cases that have status as abc' is added to a list called xCases
if(c.Status == 'abc'){
xCases.add(c);
}
}
if(xCases != null && xCases.size()>0){
// now iterate over the selected cases and call the web service
for(Case c : xCases){
//call webservice
system.debug('inside case ' + c.CaseNumber);
//Define parameters to be used in calling Apex Class
String jiraURL = 'http://jira';
String systemId = '2';
String objectType ='Case';
String objectId = c.id;
String projectKey = 'LEV';
String issueType = 'BUG';
System.debug('\n\n status is escalated');
//Execute the web service call
JIRAConnectorWebserviceCallout.CreateIssue(jiraURL, systemId ,objectType,objectId,projectKey,issueType);
}
}
}
}
}
- abhishek g 16
- December 04, 2015
- Like
- 0
Creating Custom Popup Window
Hi Folks,
Can anyone tell me how to create custom popup window in visualforce with sample code
Thanks in advance
Karthick
Can anyone tell me how to create custom popup window in visualforce with sample code
Thanks in advance
Karthick
- SS Karthick
- September 02, 2014
- Like
- 0