Send Email to vendor list:
<apex:page standardController="opportunity" extensions="SendEmailtoVendors2" showHeader="false" sidebar="false" id="pg">
<apex:outputpanel >
<apex:actionstatus id="actStatusId">
<apex:facet name="start">
<div class="waitingSearchDiv" id="el_loading" style="background-color: #DCD6D6; height: 100%;opacity:0.65;width:100%;">
<div class="waitingHolder" style="top: 74.2px; width: 91px;">
<img class="waitingImage" src="/img/loading.gif" title="Please Wait..." />
</div>
</div>
</apex:facet>
</apex:actionstatus>
</apex:outputpanel>
<script type="text/javascript">
var sendEmailParam = false;
var successEmailList = '';
function selectRecord(check){
var radioSel = document.getElementsByName('selectRec');
var obj;
for(i = 0; i < radioSel.length; i++){
if(radioSel[i].checked) {
obj = radioSel[i].value;
}
}
if(obj != '' && sendEmailParam === false){
//alert('hi');
paraFunction(obj);
}else{
sendVendorEmail(obj);
}
}
function sendEmail(){
sendEmailParam = true;
selectRecord();
}
function closeWin(successList,successMsg) {
if(successMsg == "success"){
var msg = 'Email Successfully sent to '+successList+'.';
var res = msg.replace(', .', '.');
alert(res);
top.window.opener.location="/{!$CurrentPage.parameters.id}";
window.top.close(); // Closes the new window
window.opener.refreshParent();
}
}
function inputCheckAll(ele) {
var checkboxes = document.getElementsByTagName('input');
if (ele.checked) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = true;
}
}
} else {
for (var i = 0; i < checkboxes.length; i++) {
console.log(i)
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
}
function checkFalse(ele) {
document.getElementById('allSelect').checked = false;
}
</script>
<apex:form title="Available Email Addresses" id="form">
<apex:pageBlock id="pgBlock1">
<apex:pageBlockTable value="{!emailList}" var="add" >
<apex:column headervalue="Select" id="col1">
<input type="radio" name="selectRec" id="radioSelect"
value="{!add.address}" onClick="selectRecord(this);" />
<!-- <apex:inputCheckbox value="{!add.selectEmail}" />-->
</apex:column>
<apex:column value="{!add.strEmail.Name}"/>
<apex:column value="{!add.strEmail.Email__c }"/>
</apex:pageBlockTable>
<!--<apex:commandButton value="Select" onClick="selectRecord(); return true;" id="SelBtn" /> -->
<apex:actionFunction name="paraFunction" action="{!processSelected}" id="actFun" status="actStatusId" reRender="pgBlock2,vendorTable,vendorBtn,msgs">
<apex:param name="EmailAdd" assignTo="{!selectedAddress}" value="" />
</apex:actionFunction>
<apex:inputHidden id="hidden" value="{!selectedAddress}" />
<apex:pageMessages id="msgsblock1"/>
</apex:pageBlock>
<apex:pageBlock id="pgBlock2" title="Available Vendors">
<apex:pageMessages id="msgs"/>
<!--- Vendor List Section ---->
<apex:pageBlockTable value="{!vendList}" rendered="{!vendorListShow}" var="accWrap" id="vendorTable" title="Available Vendors">
<apex:column >
<apex:facet name="header"><input type="checkbox" id="allSelect" onClick="inputCheckAll(this)" /></apex:facet>
<apex:inputCheckbox styleClass="inputCheckone" value="{!accWrap.selectEmail}" onclick="checkFalse(this)" id="inputId"/>
</apex:column>
<apex:column headerValue="Provider Name" value="{!accWrap.acc.Name}" />
</apex:pageBlockTable>
<apex:pageBlockButtons rendered="{!vendorListShow}" id="vendorBtn">
<apex:commandButton value="Send Email" onclick="sendEmail(); return false;" id="SendBtn" />
<apex:actionFunction name="sendVendorEmail" status="actStatusId" action="{!selectedVendorSendEmail}" reRender="msgs,pgBlock2,vendorTable,vendorBtn" Oncomplete="closeWin('{!successEmailList}','{!result1}')">
<apex:param name="EmailAdd" assignTo="{!selectedAddress}" value="" />
</apex:actionFunction>
</apex:pageBlockButtons>
</apex:pageblock>
</apex:form>
</apex:page>
----------
/*********************************************************************************************
Class Name : SendEmailtoVendors.cls
Description : Class to send email notification to vendors associated with selected location on Opportunity (Single/Multiple location).
Created By : venkat
Created Date : 24 May'16
*****************************Version Updates**************************************************
**********************************************************************************************/
global class SendEmailtoVendors2{
static Opportunity opp = new Opportunity();
public Map<String, Account> emailAccMap = new Map<String, Account>();
public Map<String, Set<String>> LocationProviderMap = new Map<String, Set<String>>();
public Set<String> additionalProviders = new Set<String>(); //List of providers added additionally in 'Bandwidth Provider' field on Opportunity.
public Set<String> vendorSet = new Set<String>(); //List of providers to send emails
public Set<String> excludeSet = new Set<String>(); //List of excluded providers
public Opportunity oppt = new Opportunity();
public List<EmailWrapper> emailWrap = new List<EmailWrapper>();
public List<VendorEmailWrapper> vendorEmailWrap = new List<VendorEmailWrapper>();
public List<VendorEmailWrapper> vendList{get;set;}
public static string selectedAddress {get; set;}
public static string result1 {get; set;}
public Boolean vendorListShow {get; set;}
public Id oppIDE;
private final Opportunity opps;
List<String> checkEmailList = new List<String>();
public String successEmailList{ get; set; }
public OrgWideEmailAddress[] oweMa = new OrgWideEmailAddress[]{};
//public static string pgId{get; set;}
//Constructor to extract Opportunity and matching Products using getMatchingProducts() method.
public SendEmailtoVendors2(apexpages.StandardController stdCtrl){ // Constructor defined
this.opps = (Opportunity)stdCtrl.getRecord();
vendorListShow = false;
for(Set_Email_Addresses__c em : Set_Email_Addresses__c.getAll().values()){
emailWrap.add(new EmailWrapper(em));
}
oppIDE = opps.Id;
}
//Method to prepare send email notification for selected Email List.
public string sendEmailNotification(List<string> emailList,String Sub, List<String> txtBody, Id orgwdEmailId){
String resl;
for(Integer i=0; i<10 && i<emailList.size(); i++){
list<Messaging.SingleEmailMessage> lstmail = new list<Messaging.SingleEmailMessage>();
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<String> emailAdd = new List<String>();
emailAdd.add(emailList[i]);
mail.setToAddresses(emailAdd);
mail.setOrgWideEmailAddressId(orgwdEmailId);
mail.setSubject(Sub); //Prepare Subject Line.
mail.setPlainTextBody(txtBody[i]); //Prepate Email Body.
lstmail.add(mail);
try{
messaging.sendEmail(lstmail);
resl = 'Sent';
result1 = 'success';
//Sent Email Successfully to following Vendors: \n'+checkEmailList;
}
catch(Exception e){
resl = e.getMessage();
}
}
return resl;
}
//Future method to send email notification for selected Email List
@future
public static void sendEmailNotificationFuture(List<string> emailList, Integer count,String Sub, List<String> txtBody, Id orgwdEmailId){
for(Integer i=count; i<count+10 && i<emailList.size(); i++){
list<Messaging.SingleEmailMessage> lstmail = new list<Messaging.SingleEmailMessage>();
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<String> emailAdd = new List<String>();
emailAdd.add(emailList[i]);
mail.setToAddresses(emailAdd);
mail.setSaveAsActivity(true);
mail.setOrgWideEmailAddressId(orgwdEmailId);
mail.setSubject(Sub); //Prepare Subject Line.
mail.setPlainTextBody(txtBody[i]); //Prepate Email Body.
lstmail.add(mail);
messaging.sendEmail(lstmail);
}
}
//Method to create Email Subject
public string getEmailSub(){
String subject = 'Quote: '+oppt.Service_Address__r.Name + ', ';
if(oppt.RecordType.Name.contains('IP Transit'))
subject += oppt.Commit__c +', '+ oppt.Auto_Number__c;
else
subject += oppt.Total_Commit__c +', '+ oppt.Auto_Number__c;
return subject;
}
//Method to create Email body
public String getEmailTemp(String emailId){
System.debug(emailAccMap.size());
System.debug('&&&&&&&&&&&&&&'+emailAccMap.get(emailId).Contacts[0]);
String body = 'Hi '+ emailAccMap.get(emailId).Contacts[0].FirstName +', \n\n';
body += 'Can you please provide me a quote for the following:';
if(oppt.RecordType.Name.contains('IP Transit'))
body += '\n\nService: IP Transit \nTotal Commit: '+oppt.Commit__c;
else
body += '\n\nService: IP Transit / Multi Locations \nTotal Commit: '+oppt.Total_Commit__c;
body += '\n"aggregate"';
/*if(opp.Port_Type__c != null)
body += ' \nPort Size: ' + opp.Port_Type__c;
*/
if(oppt.RecordType.Name.contains('IP Transit')){
body += '\n\nService Location: '+ oppt.Service_Address__r.Name +', # of ports: '+ oppt.Number_of_Ports__c;
}
else{
Boolean extraProvider = false;
Integer counter = 1;
if(oppt.Billing_Type__c == 'CDR'){
extraProvider = true;
string provider = emailAccMap.get(emailId).Name;
if(!additionalProviders.contains(provider)){
if(opp.Service_Address__c != null){
Set<String> providerSet = new Set<String>();
providerSet = LocationProviderMap.get(oppt.Service_Address__c);
if(providerSet.contains(provider)){
body += '\n\nService Location '+counter+': '+ oppt.Service_Address__r.Name +', # of ports: '+ oppt.Number_of_Ports_1__c;
extraProvider = false;
counter++;
}
}
if(oppt.Service_Address_2__c != null){
Set<String> providerSet = new Set<String>();
providerSet = LocationProviderMap.get(oppt.Service_Address_2__c);
if(providerSet.contains(provider)){
body += '\n\nService Location '+counter+': '+ oppt.Service_Address_2__r.Name +', # of ports: '+ oppt.Number_of_Ports_2__c ;
extraProvider = false;
counter++;
}
}
if(oppt.Service_Address_3__c != null){
Set<String> providerSet = new Set<String>();
providerSet = LocationProviderMap.get(oppt.Service_Address_3__c);
if(providerSet.contains(provider)){
body += '\n\nService Location '+counter+': '+ oppt.Service_Address_3__r.Name +', # of ports: '+ oppt.Number_of_Ports_3__c ;
extraProvider = false;
counter++;
}
}
if(oppt.Service_Address_4__c != null){
Set<String> providerSet = new Set<String>();
providerSet = LocationProviderMap.get(oppt.Service_Address_4__c);
if(providerSet.contains(provider)){
body += '\n\nService Location '+counter+': '+ oppt.Service_Address_4__r.Name +', # of ports: '+ oppt.Number_of_Ports_4__c ;
extraProvider = false;
counter++;
}
}
if(oppt.Service_Address_5__c != null){
Set<String> providerSet = new Set<String>();
providerSet = LocationProviderMap.get(oppt.Service_Address_5__c);
if(providerSet.contains(provider)){
body += '\n\nService Location '+counter+': '+ oppt.Service_Address_5__r.Name +', # of ports: '+ oppt.Number_of_Ports_5__c ;
extraProvider = false;
counter++;
}
}
}
}
if(oppt.Billing_Type__c == 'Aggregate' || extraProvider){
body += '\n\nService Location 1: '+ oppt.Service_Address__r.Name +', # of ports: '+ oppt.Number_of_Ports_1__c;
if(oppt.Service_Address_2__c != null) body += '\n\"AND/OR\"\n\nService Location 2: '+ oppt.Service_Address_2__r.Name +', # of ports: '+ oppt.Number_of_Ports_2__c;
if(oppt.Service_Address_3__c != null) body += '\n\"AND/OR\"\n\nService Location 3: '+ oppt.Service_Address_3__r.Name +', # of ports: '+ oppt.Number_of_Ports_3__c ;
if(oppt.Service_Address_4__c != null) body += '\n\"AND/OR\"\n\nService Location 4: '+ oppt.Service_Address_4__r.Name +', # of ports: '+ oppt.Number_of_Ports_4__c;
if(oppt.Service_Address_5__c != null) body += '\n\"AND/OR\"\n\nService Location 5: '+ oppt.Service_Address_5__r.Name +', # of ports: '+ oppt.Number_of_Ports_5__c ;
}
}
body += '\n\nTerm: ';
if(oppt.Terms_of_Service__c != null)
body += oppt.Terms_of_Service__c + ' Years';
body += '\n\nItemize any Access/Loop or other Flat Monthly Fees separate from the Commit price/mb.';
body += '\n\nWe are looking to move forwards around '+string.valueOf(oppt.CloseDate).subString(0,10) +'. \nWhat is the turn around for this quote? ';
body += '\n\nIf you have any questions do not hesitate to reach out. \n\nThank you\n\n';//+signature.get(selectedAddress);
for(Set_Email_Addresses__c em : Set_Email_Addresses__c.getAll().values()){
if(em.Email__c == selectedAddress){
body += em.signature__c;
}
}
return body;
}
//Method to preapre List of providers from Selected 'Service Address (Master Service Location)' record.
public void prepareProviderList(Service_Address__c serviceAdd){
Set<String> provList = new Set<String>();
if(serviceAdd.All_Providers_Text__c != null){
for(String str: serviceAdd.All_Providers_Text__c.split(', ')){
if(!excludeSet.contains(str)){
vendorSet.add(str.trim());
provList.add(str.trim());
}
}
}
LocationProviderMap.put(serviceAdd.Id, provList);
}
//Wrapper class to enable multi-select option for products.
public class EmailWrapper{
public Boolean selectEmail{get;set;}
public Set_Email_Addresses__c strEmail{get;set;}
public string address{get;set;}
// public String strName {get; set;}
//Wrapper class Constructor
public EmailWrapper(Set_Email_Addresses__c emailItem){
this.strEmail = emailItem;
// this.strName = emailItem.Name;
this.selectEmail = false;
this.address = emailItem.Email__c ;
}
}
public List<EmailWrapper> getemailList()
{
return emailWrap;
}
public class VendorEmailWrapper{
public Boolean selectEmail{get;set;}
public String strEmail{get;set;}
public String vendorName{get;set;}
public Account acc {get; set;}
//Wrapper class Constructor
public VendorEmailWrapper(Account a){
this.acc = a;
this.selectEmail = false;
}
}
public PageReference processSelected() {
System.debug('--------->'+selectedAddress);
if(selectedAddress != null){
oweMa = [SELECT Id FROM OrgWideEmailAddress WHERE Address =: selectedAddress ];
System.debug('------>'+oweMa);
}
if(oweMa.size() > 0){
vendorListShow = true;
//Extracting fields from Opportunity and Master Service Locations
oppt = [SELECT id, Bandwidth_Provider__c, Excluded_Providers__c,Service_Address__c, Service_Address__r.Name,
Service_Address_2__c, Service_Address_2__r.Name, Service_Address_3__c, Service_Address_3__r.Name, Service_Address_4__c, Service_Address_4__r.Name,
Service_Address_5__c, Service_Address_5__r.Name, Service_Address__r.All_Providers_Text__c, Service_Address_2__r.All_Providers_Text__c, Service_Address_3__r.All_Providers_Text__c, Service_Address_4__r.All_Providers_Text__c, Service_Address_5__r.All_Providers_Text__c,
AccountId, Account.All_ASN_providers__c, Auto_Number__c, Commit__c, Port_Type__c,Billing_Type__c,
Number_of_Ports__c, Number_of_Ports_1__c, Number_of_Ports_2__c, Number_of_Ports_3__c, Number_of_Ports_4__c, Number_of_Ports_5__c,
Terms_of_Service__c, CloseDate,recordtypeId, Total_Commit__c, RecordType.Name FROM Opportunity WHERE Id =: oppIDE];
System.debug(oppt.Excluded_Providers__c);
//Preparing list of excluded providers present on Account ASN
if(oppt.Account.All_ASN_providers__c != null && oppt.Account.All_ASN_providers__c != ''){
for(String str: oppt.Account.All_ASN_providers__c.split(', ')){
excludeSet.add(str.trim());
}
}
//Preparing list of excluded providers present in Excluded providers field on Opportunity
if(oppt.Excluded_Providers__c != null){
for(String str: oppt.Excluded_Providers__c.split(';')){
excludeSet.add(str.trim());
}
}
System.debug('test.... excludeSet..'+ excludeSet);
//Preparing list of Providers and Additional providers from Opportunity record
if(oppt.Bandwidth_Provider__c != null){
for(String str: oppt.Bandwidth_Provider__c.split(';')){
if(!excludeSet.contains(str)){
vendorSet.add(str.trim());
additionalProviders.add(str.trim());
system.debug('additionalProviders size @@@@@@@@@@@@@@@@@@@@@@@@@@@...'+ additionalProviders);
}
}
}
try{
//Preparing list of providers from associated Master Service Location providers for Single Location Opportunity.
if(oppt.RecordType.Name.contains('IP Transit')){
if(oppt.Service_Address__c != null){
prepareProviderList(oppt.Service_Address__r); //Collecting list of providers from Location 1
}
}
//Preparing list of providers from associated Master Service Location providers for Multiple Location Opportunity.
if(oppt.RecordType.Name.contains('IP Transit / Multi Locations')){
if(oppt.Service_Address__c != null){
prepareProviderList(oppt.Service_Address__r); //Collecting list of providers from Location 1
}
if(oppt.Service_Address_2__c != null){
prepareProviderList(oppt.Service_Address_2__r); //Collecting list of providers from Location 2
}
if(oppt.Service_Address_3__c != null){
prepareProviderList(oppt.Service_Address_3__r); //Collecting list of providers from Location 3
}
if(oppt.Service_Address_4__c != null){
prepareProviderList(oppt.Service_Address_4__r); //Collecting list of providers from Location 4
}
if(oppt.Service_Address_5__c != null){
prepareProviderList(oppt.Service_Address_5__r); //Collecting list of providers from Location 5
}
}
//Preparing list for Aggregate Billing type Opportunity. If aggregate, all providers will get notification for all selected locations.
if(oppt.Billing_Type__c == 'Aggregate'){
Integer counter;
for(String vend: vendorSet){
system.debug('vendorSet size @@@@@@@@@@@@@@@@@@@@@@@@@@@...'+ vendorSet);
counter =0;
for(String loc: LocationProviderMap.keySet()){
Set<String> str = LocationProviderMap.get(loc);
if(str.contains(vend)){
counter++;
}
}
if(counter == LocationProviderMap.size()){
additionalProviders.add(vend);
}
}
}
if(vendorSet.size() > 0){
system.debug('vendorSet size @@@@@@@@@@@@@@@@@@@@@@@@@@@...'+ vendorSet);
getVendorListEmails();//vendorSet, excludeSet);
}
else{
}
}catch(Exception exp){
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,exp.getMessage());
}
}else{
vendorListShow = false;
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Selected Email Address: '+selectedAddress+' is not set as Org-Wide Email Address.'));
}
return null;
}
//Method to collect email addresses of selected vendors
public void getVendorListEmails(){
//Set<String> vendorSet, Set<String> excludeSet)
String result;
List<Account> accList = new List<Account>();
List<String> emailList = new List<String>();
vendList = new List<VendorEmailWrapper>();
//If Billing type = 'Aggregate', all providers will get notification for all selected locations.
if(oppt.Billing_Type__c == 'Aggregate' && additionalProviders != null && additionalProviders.size() > 0){
vendorSet.clear();
vendorSet.addAll(additionalProviders);
}
//Remove 'All Providers' from Vendor Set
if(vendorSet.contains('All Providers')){
vendorSet.remove('All Providers');
}
System.debug('Test...'+vendorSet);
System.debug('Test...'+excludeSet);
System.debug('Test...LocationProviderMap'+LocationProviderMap);
system.debug('Test.....Additionalprovider'+ additionalProviders);
//Fetching records of Vendor account and contact to get Name and Email addresses.
accList = [SELECT Id, Name, Email__c, (SELECT Id, Email, FirstName FROM Contacts) FROM Account WHERE NAME IN: vendorSet AND Name NOT IN: excludeSet AND RecordType.Name = 'Vendor Account Record Type'];
System.debug('Test....'+accList.size());
if(accList.size() > 0){
for(Account acc: accList){
vendList.add(new VendorEmailWrapper(acc));
emailList.add(acc.Email__c);
emailAccMap.put(acc.Email__c, acc);
}
}
else{
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Selected Email Address: '+selectedAddress+' is not set as Org-Wide Email Address.'));
}
}
public PageReference selectedVendorSendEmail(){
System.debug(selectedAddress);
// List<String> checkEmailList = new List<String>();
successEmailList = '';
for(VendorEmailWrapper vemWrap : vendList){
if(vemWrap.selectEmail == true){
checkEmailList.add(vemWrap.acc.Email__c);
successEmailList += vemWrap.acc.Name +', ';
system.debug('--------->'+successEmailList );
}
}
String success = '';
System.debug(successEmailList);
List<String> txtBody = new List<String>();
for(Integer k=0; k<checkEmailList.size(); k++){
String textBDY = getEmailTemp(checkEmailList[k]);
txtBody.add(textBDY);
}
if(checkEmailList.size() > 0){
String sbjct = getEmailSub();
success = sendEmailNotification(checkEmailList,sbjct, txtBody, oweMa.get(0).Id); //Calling method to send email notification.
if(checkEmailList.size() > 10){
for(Integer i=10; i<checkEmailList.size(); i=i+10){
sendEmailNotificationFuture(checkEmailList, i, sbjct, txtBody, oweMa.get(0).Id); //Calling Future method to send email notification.
if(i>190)
break;
}
}
if(success == 'Sent'){
ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.CONFIRM, 'Email Sent Successfully!'));
}
else{
ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR, success));
}
}
else{
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Please select atleast 1 row'));
}
return null;
}
}
output:
No comments:
Post a Comment