问题描述
vf页面
<apex:page id="myPage" standardController="Campaign" extensions="Campaignbulk" showHeader="true" sidebar="true" lightningStylesheets="true" tabStyle="Campaign" docType="html-5.0">
<!-- This page must be accessed with an Account-->
<apex:includeScript value="https://code.jquery.com/jquery-2.1.1.min.js"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="{!URLFOR($Resource.charCounter)}" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.countable1').jqEasyCounter({
'maxChars': 160,'maxCharsWarning': 150
});
});
</script>
<!-- Base styles -->
<style type="text/css">
.dateFormat{
visibility:hidden;
Format: 'h:mm p';
}
</style>
<script type="text/javascript">
function displaymessage(){
// document.location.reload(true)
window.location ='/apex/displayMsg';
}
</script>
<div style="background-color:#4B79A1;font-size:15px;font-color:#FFFFFF;width:815px;text-align:center;padding:5px 5px 5px 5px">
<center>
<div style="font-size: 20px; font-color:#FFFFFF; text-align:Right;">
<apex:sectionHeader title="Bulk Schedule"/>
</div>
<apex:form style="font-size:14px;" id="myForm" html-autocomplete="off" >
<apex:pageBlock id="thePage">
<apex:pageMessages ></apex:pageMessages>
<apex:panelGrid >
<apex:pageBlockSection id="pb" columns="1" rendered="{!firstPanel}">
<apex:outputText label="Campaign Name :">{!campaign.name}</apex:outputText>
<apex:outputText label="Count :"> {!cnt} </apex:outputText>
<apex:inputTextarea label="Message" value="{!campaign.Message__c}" styleClass="countable1"/>
<apex:panelGrid >
<apex:pageBlockSection columns="3" id="pb2">
<apex:commandButton value="SendNow" oncomplete="displaymessage()" action="{!SendNow}"/>
<apex:inputCheckBox value="{!checkBox}" label="Schedule Later" onclick="check()" id="chk">
<apex:actionSupport event="onchange" reRender="ScheduleCheck" action="{!click}"/>
</apex:inputCheckBox>
</apex:pageBlockSection>
<apex:outputPanel id="ScheduleCheck" >
<apex:outputPanel id="ScheduleSection" rendered="{!checkBox}">
Schedule Date: <apex:inputField id="dateId" value="{!Campaign.Schedule_Date__c}" showDatePicker="true" label="Schedule Date">
<apex:actionsupport event="onchange" action="{!sendbulk}" rerender="thePage"/>
</apex:inputField>
Schedule Time: <apex:inputField id="timeid" value="{!Campaign.Schedule_SMS_Time__c}" label="Schedule Time">
<apex:actionSupport event="onchange" action="{!sendbulk}" rerender="thePage"/>
</apex:inputField>
<apex:commandButton id="submitbtn" disabled="{!campaign.Message__c = null || Campaign.Schedule_Date__c==null || Campaign.Schedule_Date__c < Today() || Campaign.Schedule_SMS_Time__c==null}"
style="height:40px; width:100px;border-radius:10px;background-color:#008ae6;color:#FFFFFF;" value="Send Later" oncomplete="displaymessage()" action="{!SendLater}"/>
<br/><br/>
</apex:outputPanel>
</apex:outputPanel>
</apex:panelGrid>
</apex:pageBlockSection>
</apex:panelGrid>
<apex:pageBlockSection rendered="{!secondPanel}" >
<h1>
<apex:outputText label="{!cnt}">"Thank you for submit"</apex:outputText>
</h1>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</center>
</div>
</apex:page>
顶点类
public with sharing class Campaignbulk {
// Form fields
public boolean firstPanel{get;set;}
public boolean secondPanel{get;set;}
public String currentRecordId{get;set;}
public Boolean checkBox{get; set;}
public Date startdate{get;set;}
public time starttime{get;set;}
static final String SMS_CHANNEL = 'sms';
//static final String API_ENDPOINT = 'https://api.nexmo.com/v0.1/messages';
public campaign camp;
public integer cnt{get;set;}
public string smsText {get;set;}
public string ac {get;set;}
//create list Collection
public Campaignbulk (ApexPages.StandardController stdController)
{
this.camp =(Campaign)stdController.getRecord();
cnt=[ SELECT count() FROM Campaignmember WHERE CampaignId =:camp.Id];
List<Campaignmember> camplist=[ SELECT phone,FirstName FROM Campaignmember WHERE CampaignId =:camp.Id ];
firstPanel = true;
secondPanel = false;
for(Campaignmember Cpgmb: camplist ) {
smsText = '';
}
}
public void click(){
if(checkBox){
checkBox=true;
}else if(camp.Schedule_Date__c == Null){
checkBox=false;
}
return;
}
public void SendNow(){
system.debug('campaingn id '+camp.Id);
processCampaign(camp.Id,smsText);
firstPanel = false;
secondPanel = true;
}
//Action method to check date and time
public void sendbulk(){
if(camp.Schedule_Date__c < system.Now() || camp.Schedule_SMS_Time__c == Null)
{
datetime dt = DateTime.Now();
time t = dt.time();
integer n = t.hour();
system.debug(n);
system.debug(camp.Schedule_SMS_Time__c);
if(camp.Schedule_Date__c <= (system.Now()-1) && camp.Schedule_SMS_Time__c == NULL)
{
system.debug('insert date '+ camp.Schedule_SMS_Time__c);
camp.Schedule_Date__c.adderror('Invalid date');
}
else if(camp.Schedule_SMS_Time__c != NULL)
{
String s = camp.Schedule_SMS_Time__c;
system.debug('insert Time '+camp.Schedule_SMS_Time__c);
system.debug('s:' +s);
List<String> filterLogicSplittedbySpace = s.split(':');
system.debug('filterLogicSplittedbySpace:' +filterLogicSplittedbySpace[0]);
integer TimeSplit =integer.valueof(filterLogicSplittedbySpace[0]);
if(TimeSplit < n)
{
camp.Schedule_SMS_Time__c.adderror('Invalid Time');
}
}
}
}
public void SendLater(){
try{
String s = camp.Schedule_SMS_Time__c;
system.debug('s:' +s);
List<String> filterLogicSplittedbySpace = s.split(':');
system.debug('filterLogicSplittedbySpace:' +filterLogicSplittedbySpace[0]);
String smsText = 'Test'+smsText;
Date scheduletime = camp.Schedule_Date__c;
String day = string.valueOf(scheduletime.day());
String month = string.valueOf(scheduletime.month());
String year = string.valueOf(scheduletime.year());
String hour = filterLogicSplittedbySpace[0];
String minute = '0';
String second = '0';
String strSchedule = '0 ' + minute + ' ' + hour + ' ' + day + ' ' + month + ' ?' + ' ' + year;
CampaignSchedulemsgbody campsc= new CampaignSchedulemsgbody();
campsc.setCampaignId(camp.Id,smsText);
String scheduledJobName = strSchedule;
System.schedule('ETGSMS '+hour+':00 '+day +'/'+month +'/'+year,strSchedule,campsc);
/*list<SMS_Response__c> srm= new list<SMS_Response__c>();
SMS_Response__c str = new SMS_Response__c();
str.message__c = smsText;
srm.add(str);
insert srm; */
}catch(Exception e){
}
}
//call the twillio/Nexmo
public void callActiveService(string smsText)
{
smsText=smsText;
system.debug('Campaign Id'+camp.Id+'smsText'+smsText);
configuration_setting__c config = [select Name,Lead_Phone_Number__c
FROM configuration_setting__c where Active__c = True limit 1 ];
List<Campaignmember> camplist=[ SELECT phone,FirstName FROM Campaignmember
WHERE CampaignId =:camp.Id];
system.debug('Lead_Phone_Number__c');
for(Campaignmember cam: camplist)
{
if(config.Name == 'Twilio')//TwilioConfig__c.getinstence().Name
{
Twilio.sendfromtwilio(config.Lead_Phone_Number__c,smsText,cam.Phone);
}
else if(config.Name == 'Nexmo')
{
Nexmo.sendmessage(cam.Phone,config.Lead_Phone_Number__c,'sms');
}
}
}
public void callServices()
{
system.debug('Campaign Id'+camp.Id);
configuration_setting__c config = [select Name,FirstName FROM Campaignmember
WHERE CampaignId =:camp.Id];
system.debug('Lead_Phone_Number__c');
for(Campaignmember cam: camplist)
{
if(config.Name == 'Twilio')//TwilioConfig__c.getinstence().Name
{
Twilio.sendfromtwilio(config.Lead_Phone_Number__c,cam.Phone);
}
else if(config.Name == 'Nexmo')
{
Nexmo.sendmessage(cam.Phone,'sms');
}
}
}
@future(callout = true)
public static void processCampaign(string campaignID,String smsText){
system.debug('id '+campaignID+'text'+smsText);
date myDate = date.today();
integer msgcount = 0;
List<configuration_setting__c> lstconfig = new List<configuration_setting__c>();
configuration_setting__c conf = [select Name,Phone_Numbers__c,Lead_Phone_Number__c,Messages_Send__c,Last_Message_Sent_Date__c
FROM configuration_setting__c where Active__c =True limit 1 ];
List<String> lstAlpha = conf.Phone_Numbers__c.split(',');
Integer currentPhone=0;
List<SMS_Response__c> SMSRP = new List<SMS_Response__c>();
List<Campaignmember> camplist=[ SELECT phone,FirstName FROM Campaignmember WHERE CampaignId =:campaignID limit 5000];
//change for loop to Traditional increment size to 100 (limit to 5000 max at line no 46)
//create a new future methods sendinbatch() send it as list of campagin members
//sendinbatch() have a for loop for 100,campagin 100 list move 56 to 63 have to move into method
for(Campaignmember Cpgmb: camplist) {
string phonefromid =lstAlpha[currentPhone++];
string newStatus;
//smsText = ' ';
//smsText = 'Hello '+Cpgmb.FirstName;
smsText = ' '+smsText;
if(conf.Name == 'Nexmo'){
newStatus= bulksms(Cpgmb.Phone,phonefromid,'sms');
msgcount = msgcount+1;
}else if(conf.Name == 'Twilio'){
newStatus= bulkfromtwilio(phonefromid,Cpgmb.Phone);
msgcount = msgcount+1;
}
//Message log API
SMS_Response__c sr = new SMS_Response__c();
if(Schema.sobjectType.SMS_Response__c.fields.From_Number__c.isCreateable() &&
Schema.sobjectType.SMS_Response__c.fields.From_Number__c.isUpdateable())
{
sr.from_number__c = phonefromid ;
}
if(Schema.sobjectType.SMS_Response__c.fields.Message__c.isCreateable() &&
Schema.sobjectType.SMS_Response__c.fields.Message__c.isUpdateable())
{
sr.message__c = smsText;
}
if(Schema.sobjectType.SMS_Response__c.fields.Status__c.isCreateable() &&
Schema.sobjectType.SMS_Response__c.fields.Status__c.isUpdateable())
{
sr.status__c = newStatus;
}
if(Schema.sobjectType.SMS_Response__c.fields.Campaign__c.isCreateable() &&
Schema.sobjectType.SMS_Response__c.fields.Campaign__c.isUpdateable())
{
sr.campaign__c = campaignID;
}
if(Schema.sobjectType.SMS_Response__c.fields.Service_Providers__c.isCreateable() &&
Schema.sobjectType.SMS_Response__c.fields.Service_Providers__c.isUpdateable())
{
sr.service_providers__c = conf.Name;
}
if(Schema.sobjectType.SMS_Response__c.fields.SMS_Type__c.isCreateable() &&
Schema.sobjectType.SMS_Response__c.fields.SMS_Type__c.isUpdateable())
{
sr.sms_type__c = 'OutGoing Message' ;
}
if(Schema.sobjectType.SMS_Response__c.fields.Mobile_Number__c.isCreateable() &&
Schema.sobjectType.SMS_Response__c.fields.Mobile_Number__c.isUpdateable())
{
sr.mobile_number__c = Cpgmb.Phone;
}
if(Schema.sobjectType.SMS_Response__c.fields.Mobile_Number__c.isCreateable() &&
Schema.sobjectType.SMS_Response__c.fields.Mobile_Number__c.isUpdateable())
{
SMSRP.add(sr);
}
if (currentPhone >= lstAlpha.size()){
currentPhone=0;
}
} // end of all campaing memebers
//Updating Configurations settings with No. of messages sent for a day
Configuration_setting__c config = new Configuration_setting__c();
if(Schema.sobjectType.Configuration_setting__c.fields.id.isCreateable() &&
Schema.sobjectType.Configuration_setting__c.fields.id.isUpdateable())
{
config.id = conf.id;
}
system.debug('system.today() : '+mydate+'latdate '+conf.Last_Message_Sent_Date__c);
if (conf.Last_Message_Sent_Date__c != mydate){
system.debug('Inside system.today if condition');
if(Schema.sobjectType.Configuration_setting__c.fields.Last_Message_Sent_Date__c.isCreateable() &&
Schema.sobjectType.Configuration_setting__c.fields.Last_Message_Sent_Date__c.isUpdateable())
{
config.Last_Message_Sent_Date__c = mydate;
}
if(Schema.sobjectType.Configuration_setting__c.fields.Messages_Send__c.isCreateable() &&
Schema.sobjectType.Configuration_setting__c.fields.Messages_Send__c.isUpdateable())
{
config.Messages_Send__c = msgcount;
}
}
else if (conf.Last_Message_Sent_Date__c == mydate){
if (conf.Messages_Send__c == 0){
if(Schema.sobjectType.Configuration_setting__c.fields.Messages_Send__c.isCreateable() &&
Schema.sobjectType.Configuration_setting__c.fields.Messages_Send__c.isUpdateable())
{
config.Messages_Send__c = msgcount;
}
}
else {
if(Schema.sobjectType.Configuration_setting__c.fields.Messages_Send__c.isCreateable() &&
Schema.sobjectType.Configuration_setting__c.fields.Messages_Send__c.isUpdateable())
{
config.Messages_Send__c = conf.Messages_Send__c +msgcount;
}
}
}
if (Schema.sobjectType.Configuration_setting__c.isCreateable() &&
Schema.sobjectType.Configuration_setting__c.isUpdateable())
{
lstconfig.add(config);
}
system.debug('lstconfig'+lstconfig+'SMSRP'+SMSRP);
if(Schema.sobjectType.Configuration_setting__c.fields.Messages_Send__c.isCreateable() &&
Schema.sobjectType.Configuration_setting__c.fields.Messages_Send__c.isUpdateable())
{
insert smsrp;
}
if(Schema.sobjectType.Configuration_setting__c.fields.Messages_Send__c.isCreateable() &&
Schema.sobjectType.Configuration_setting__c.fields.Messages_Send__c.isUpdateable())
{
if(lstconfig.size()>0){
}
}
if (Schema.sobjectType.Configuration_setting__c.isCreateable() &&
Schema.sobjectType.Configuration_setting__c.isUpdateable())
{
upsert lstconfig;
}
} // end of method
public static string bulksms(String toId,String fromId,String text,String channel) {
String status;
String body = buildrequestBody(toId,fromId,text,channel);
String authHeader = getAuthorizationHeader();
errorResponseWrapper erw;
HttpRequest request = buildrequest(body,authHeader);
Http http = new Http();
HTTPResponse res = http.send(request);
if(res.getStatusCode()>=200 && res.getStatusCode()<=300) {
status= 'SMS Sent Successfully';
} else{
erw =(errorResponseWrapper)json.deserialize(res.getBody(),errorResponseWrapper.class);
status='SMS Send Failed:' + erw.title;
}
return status ;
}
public static String buildrequestBody(String toId,String channel) {
String result = '';
result += '{';
if (channel == SMS_CHANNEL) {
result += '"from": { "type": "sms","number": "' + fromId + '" },';
result += '"to": { "type": "sms","number": "' + toId + '" },';
}
result += '"message": {';
if(channel == SMS_CHANNEL) {
result += '"content": {"type": "text","text": "' + text + '" ';
}
else {
result += '"content": {"type": "text","text": "' + text + '"';
}
result += '}';
result += '}';
result += '}';
return result;
}
public static HttpRequest buildrequest(String body,String authHeader) {
configuration_setting__c configset = [select name,Endpoint_URI_to_BulkSMS__c FROM configuration_setting__c where Name='nexmo' limit 1 ];
String API_ENDPOINT = configset.Endpoint_URI_to_BulkSMS__c;
HttpRequest req = new HttpRequest();
req.setEndpoint(API_ENDPOINT );
req.setMethod('POST');
req.setCompressed(true);// otherwise we hit a limit of 32000
req.setHeader('Authorization',authHeader);
req.setHeader('Content-Type','application/json');
req.setBody(body);
req.setTimeout(60000);// timeout in milliseconds
return req;
}
public static String getAuthorizationHeader() {
String apiKey = '';
String apiSecret = '';
list<configuration_setting__c> conflst = [SELECT Name,AccountSid__c,Active__c,AuthToken__c FROM configuration_setting__c where Name='Nexmo' LIMIT 1];
for(configuration_setting__c conf:conflst) {
apiKey = conf.AccountSid__c;
apiSecret = conf.AuthToken__c;
}
Blob headerValue = Blob.valueOf(apiKey + ':' + apiSecret);
return 'BASIC ' + EncodingUtil.base64Encode(headerValue);
}
Public static string bulkfromtwilio (string Fromnumber,string text,string tonumber) {
System.debug('Fromnumber'+Fromnumber + ' text'+text + 'tonumber'+tonumber);
String status;
errorResponseWrapper erw;
configuration_setting__c cstt=new configuration_setting__c();
cstt = [select Name,AuthToken__c,Bulk_SMS__c,Endpoint_URI_to_BulkSMS__c,Contact_Phone_Number__c,Lead_Phone_Number__c FROM configuration_setting__c where Name='Twilio' limit 1];
String account = cstt.AccountSid__c;
String token = cstt.AuthToken__c;
string endpoint=cstt.Endpoint_URI_to_BulkSMS__c;
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
String VERSION = '3.2.0';
req.setHeader('X-Twilio-Client','salesforce-' + VERSION);
req.setHeader('User-Agent','twilio-salesforce/' + VERSION);
req.setHeader('Accept','application/json');
req.setHeader('Accept-Charset','utf-8');
req.setHeader('Authorization','Basic '+EncodingUtil.base64Encode(Blob.valueOf(account+':' +token)));
req.setBody('To='+EncodingUtil.urlEncode(+tonumber,'UTF-8')+'&From='+EncodingUtil.urlEncode(+Fromnumber,'UTF-8')+'&Body='+text);
Http http = new Http();
HTTPResponse res = http.send(req);
if(res.getStatusCode()>=200 && res.getStatusCode()<300)
{
status= 'SMS Sent Successfully';
} else{
erw =(errorResponseWrapper)json.deserialize(res.getBody(),errorResponseWrapper.class);
status= 'SMS Send Failed:' + erw.message;
}
return status ;
}
public class errorResponseWrapper{
String message;
String title;
String invalid_paramete;
string reason;
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)