Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <apex:page sidebar="false" showHeader="false" standardStylesheets="false">
- <head>
- <!--- Stylesheets--->
- <link type="text/css" rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/themes/flick/jquery-ui.css" />
- <link type="text/css" rel="stylesheet" href="{!URLFOR($Resource.tableSorter, '/css/ui/style.css')}" />
- <!---- jQuery libraries --->
- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />
- <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js" />
- <!---- Apex connection Libraries --->
- <script src="/soap/ajax/25.0/connection.js" type="text/javascript"></script>
- <script src="/soap/ajax/15.0/apex.js" type="text/javascript"></script>
- <script src="../static/102010/js/picklist.js"></script>
- <!--- table sorter libraries --->
- <script src="{!URLFOR($Resource.tableSorter, '/js/jquery.tablesorter.min.js')}"></script>
- <script src="{!URLFOR($Resource.tableSorter, '/js/jquery.tablesorter.widgets.min.js')}"></script>
- <!--- theme switcher--->
- <style>
- body
- {
- font-size:11px;
- }
- #container
- {
- min-height:500px;
- }
- #toolbar
- {
- padding:5px;
- }
- #respondent_attributes li
- {
- list-style-type:none;
- }
- #log
- {
- margin:15px;
- font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace;
- color: #000000;
- background-color: #eee;
- font-size: 12px;
- border: 1px dashed #999999;
- line-height: 14px;
- padding: 5px;
- height:300px;
- overflow: auto;
- }
- #bulkChangeProgressBar
- {
- height:15px;
- float:left;
- width:75%;
- display:none;
- }
- #bulkChangeProgressVal
- {
- float:right;
- text-align:right;
- font-weight:bold;
- width:15%;
- padding-right:5px;
- display:none;
- }
- #switcher { display: inline-block; padding-bottom: 5px; margin-right:25px; float:right; }
- </style>
- <script type="text/javascript">
- setInterval("checkOnline()",500);
- var totals = new Object();
- var campaigns = new Object();
- var payments = new Object();
- var respondentNumbers = new Object();
- var codes = new Object();
- var lastRespNum = -1;
- var lastStatus = 'NA';
- var offlineCount = 0;
- var lastContact;
- var lastPayment;
- var reportId;
- var statusListValues = '';
- sforce.connection.sessionId = '{!$Api.Session_ID}';
- var describeResults = sforce.connection.describeSObject('payments__c'); // the object we want picklists from
- $(document).ready(function()
- {
- writeLogEntry('Initializing Interface');
- //prevent accidental window closing
- $(window).bind('beforeunload', function(){
- //return 'Are you sure you wish to leave this page?';
- });
- //get status__c picklist values
- var statusList = getPicklistValues('Status__c').values;
- setPickVals('#bulkChangeFrom',statusList);
- setPickVals('#bulkChangeTo',statusList);
- for(var i = 0; i < statusList.length; i++)
- {
- statusListValues += '<option value="'+statusList[i].value+'">'+statusList[i].label+'</option>';
- }
- $('#saveDQRow').click(function(){
- var saveResult = evalRespondentRecord($('.statusList[contact='+lastContact+']').val(), lastContact,lastPayment,false);
- if(!saveResult.success)
- {
- $('#dqSaveResult').html(saveResult.message);
- $(this).val(lastStatus);
- }
- else
- {
- $('#selectDQReason').dialog('close');
- }
- });
- $('#cancelDQRow').click(function(){
- $('#selectDQReason').dialog('close');
- });
- $('#bulkStatusChangeButton').click(function(){
- $('#bulkStatusChange').dialog('open');
- });
- $('#bulkStatusChangeSubmit').click(function(){
- $('#bulkStatusChangeSubmit').button("disable");
- $('#bulkChangeProgressVal').show();
- $('#bulkChangeProgressBar').show();
- var startVal = $('#bulkChangeFrom').val();
- var endVal = $('#bulkChangeTo').val();
- var totalToSave = 0;
- var completed = 0;
- $('.statusList').each(function(){
- if($(this).val() == startVal)
- {
- totalToSave++;
- }
- });
- $('.statusList').each(function(i){
- var selectItem = $(this);
- if($(this).val() == startVal)
- {
- lastStatus = startVal;
- setTimeout((function(i,selectItem) {
- return function() {
- $(selectItem).val(endVal).trigger("focus").trigger("change");
- completed++;
- var percent = Math.round(completed/totalToSave*100);
- $('#bulkChangeProgressVal').html(percent +'%');
- $('#bulkChangeProgressBar' ).progressbar( "value" , percent);
- if(percent == 100)
- {
- $('#bulkChangeProgressVal').html('0%');
- $('#bulkChangeProgressBar' ).progressbar( "value" , 0);
- $('#bulkChangeProgressVal').hide();
- $('#bulkChangeProgressBar').hide();
- $('#bulkStatusChangeSubmit').button("enable");
- $('#bulkStatusChange').dialog('close');
- }
- }
- })(i,selectItem), 200*i);
- }
- });
- return false;
- });
- $( "#bulkChangeProgressBar" ).progressbar({
- value: 0
- });
- // Theme switcher
- //$('#switcher').themeswitcher({loadTheme: 'Smoothness'} );
- //register dialog boxes
- $('.dialog').dialog({
- autoOpen: false,
- modal: true
- });
- $('#clearLog').click(function(){
- $('#log').html(null);
- });
- $(':button[value="Cancel"]').click(function(){
- $($(this).parent().parent()).dialog('close');
- });
- //register the attribute update button
- $('#updateAttributes').click(function(event,ui){
- writeLogEntry('Updating respondent attributes');
- var paymentId = $('#updateAttributePaymentId').val();
- var respondentsToUpdate = new Array();
- var thisRespondent = new sforce.SObject("Respondent__c");
- thisRespondent.Id = payments[paymentId].RespondentRecord__r.Id;
- $('.attrib_box').each(function(index){
- if($(this).attr('checked'))
- {
- thisRespondent['Attribute_'+parseInt(index+1,10)+'_Met__c'] = true;
- }
- else
- {
- thisRespondent['Attribute_'+parseInt(index+1,10)+'_Met__c'] = false;
- }
- });
- respondentsToUpdate.push(thisRespondent);
- result = saveObject(respondentsToUpdate);
- writeLogEntry('Respondent update success: ' + result[0].success);
- if(result[0].success == 'true')
- {
- $('#updateAttributeStatus').html(null);
- $('.attrib_box').each(function(index){
- if($(this).attr('checked'))
- {
- payments[paymentId].RespondentRecord__r['Attribute_'+parseInt(index+1,10)+'_Met__c'] = 'true';
- }
- else
- {
- payments[paymentId].RespondentRecord__r['Attribute_'+parseInt(index+1,10)+'_Met__c'] = 'false';
- }
- });
- $( "#attributes" ).dialog('close');
- }
- else
- {
- $('#updateAttributeStatus').html('Error updating respondent: ' + result.message);
- }
- });
- $('#assignCheckButton').click(function(){
- if(!$.isNumeric($('#checkNumber').val()))
- {
- $('#updateCheckStatus').html('Please enter a valid check number');
- return false;
- }
- runQuery("select id,name, payment__c, payment__r.name from check__c where name = '"+$('#checkNumber').val()+"'",function(data){
- console.log(data);
- if(data.records.length == 0)
- {
- $('#updateCheckStatus').html('No check with that number could be found. Please double check the number and try again.');
- return false;
- }
- if(data.records[0].Payment__c != null)
- {
- $('#updateCheckStatus').html('Check has already been assigned to payment ' +data.records[0].Payment__r.Name );
- return false;
- }
- reportId = data.records[0].Id;
- var payment = new Object();
- payment.id = $('#updateCheckPaymentId').val();
- payment.check__c = data.records[0].Id;
- saveResult = savePayment(payment);
- if(!saveResult.success)
- {
- $('#updateCheckStatus').html(saveResult.message.message);
- }
- else
- {
- $('#updateCheckStatus').html('Update successfull!');
- $('.check[check="'+data.records[0].Id+'"]').each(function(){$(this).html(null)});
- $('.check[check="'+data.records[0].Id+'"]').each(function(){$(this).attr('check',null)});
- $('.check[payment="'+$("#updateCheckPaymentId").val()+'"]').each(function(){$(this).html(data.records[0].Name)});
- $('.check[payment="'+$("#updateCheckPaymentId").val()+'"]').each(function(){$(this).attr('check',data.records[0].Id)});
- $('#assignCheck').dialog('close');
- }
- });
- });
- $('#container').tabs();
- $('#tabs').hide();
- $('input[type=checkbox]').button();
- $('.button').button();
- $('#reportLink').button('disable');
- $('#useRotation').click(function(){
- if($(this).is(':checked'))
- {
- writeLogEntry('Enabling rotation assigner');
- $('.respondentNumber').attr("disabled","disabled");
- //$('#tabs li:nth-child(2)').show().next().show();
- }
- else
- {
- writeLogEntry('Disabling rotation assigner');
- $('.respondentNumber').removeAttr("disabled");
- //$('#tabs li:nth-child(2)').hide().next().hide();
- }
- });
- $( "input[type=checkbox]" ).button({ icons: {primary:'ui-icon-circle-close'} }).click(function(){
- if($(this).is(':checked'))
- {
- $(this).next().children('.ui-button-icon-primary').addClass("ui-icon-circle-check").removeClass("ui-icon-circle-close");
- }
- else
- {
- $(this).next().children('.ui-button-icon-primary').addClass("ui-icon-circle-close").removeClass("ui-icon-circle-check");
- }
- }).each(function(){
- if($(this).is(':checked'))
- {
- $(this).next().children('.ui-button-icon-primary').addClass("ui-icon-circle-check").removeClass("ui-icon-circle-close");
- }
- else
- {
- $(this).next().children('.ui-button-icon-primary').addClass("ui-icon-circle-close").removeClass("ui-icon-circle-check");
- }
- });
- //get master campaign list when the umbrella campaign changes.
- $('#umbrellacampaigns').change(function(){
- if($(this).val() == '--Select One--')
- {
- return false;
- }
- writeLogEntry('Umbrella campaign changed to ' + $(this).val());
- getMasterCampaignList($(this).val());
- setLink($(this+':selected').text());
- $('.reportLink').button('enable');
- });
- $('#clearButton').click(function(){
- $('#filter-box').val(null);
- $("#checkInTableGrid tr:hidden").show();
- $('#filter-box').focus();
- });
- $("#lostConnection").dialog({
- closeOnEscape: false,
- modal: true,
- autoOpen: false,
- open: function(event, ui) { $(".ui-dialog-titlebar-close", ui.dialog || ui).hide(); }
- }).parent().addClass("ui-state-error");
- $('#cancelUpdateAttributes').click(function(){
- $('#attributes').dialog('close');
- });
- //when a master campaign is chosen, parse the CSV content, serve scores, etc.
- $('#mastercampaigns').change(function(){
- writeLogEntry('Master campaign changed to ' + $(this).val());
- $('#bulkStatusChangeButton').button('enable');
- if($(this).val() == '--Select One--')
- {
- return false;
- }
- $('#tabs').show();
- //$('#tabs li:nth-child(2)').hide().next().hide();
- if(campaigns[$(this).val()].Serve_Rotation__c != null)
- {
- try
- {
- var parseServe = parseCSV(campaigns[$(this).val()].Serve_Rotation__c);
- var calcScores= calculateServeScores();
- if(parseServe.success && calcScores.success)
- {
- $('#useRotation').button("enable");
- }
- else
- {
- $('#useRotation').attr("checked","false");
- $('#useRotation').hide();
- showAlert('Test has a rotation defined, but it is invalid. Please ensure the rotation is in the expected format and try again');
- }
- }
- catch(ex)
- {
- }
- }
- getRespondentList($(this).val());
- $('#progressTrackerFrame').attr('src', '/apex/studyprogresstrackersimple?core.apexpages.devmode.url=0&campaignid='+$(this).val());
- writeLogEntry('Master campaign data load complete');
- }).attr("disabled", true);
- //get the list of umbrella campaigns.
- getUmbrellaCampaignList();
- });
- //set all the checked attributes for a given payment
- function setCheckedAttributes(paymentId)
- {
- writeLogEntry('Finding all attributes for payment' + paymentId);
- var returnObj = new returnObject();
- try
- {
- $('#updateAttributePaymentId').val(paymentId);
- $( "#attributes" ).dialog('option', 'title', 'Attributes for ' + payments[paymentId].Contact__r.Name);
- $('.attrib_box').each(function(index){
- if(payments[paymentId]['RespondentRecord__r']['Attribute_'+parseInt(index+1,10)+'_Met__c'] == 'true')
- {
- $(this).attr('checked',true);
- }
- else
- {
- $(this).removeAttr("checked")
- }
- });
- }
- catch(exception)
- {
- returnObj.success = false;
- returnObj.message = exception;showAlert(exception.message);
- }
- writeLogEntry('Finding all attributes for payment' + paymentId + ' complete');
- return returnObj;
- }
- // function to get the picklist values of a field. Finds all potential options. Simple pass it in a field id. Will return object with data in the values key.
- function getPicklistValues(field)
- {
- //create return object
- var returnObj = new returnObject();
- try
- {
- var validField = false;
- for(var i = 0; i < describeResults.fields.length; i++)
- {
- var fieldList = describeResults.fields[i];
- var fieldName = fieldList.name;
- if(fieldName.toLowerCase() == field.toLowerCase())
- {
- validField = true;
- for(var j = 0; j < fieldList.picklistValues.length; j++)
- {
- var newValue = new Object();
- newValue.label = fieldList.picklistValues[j].label;
- newValue.value = fieldList.picklistValues[j].value;
- newValue.default = fieldList.picklistValues[j].defaultValue;
- if(fieldList.picklistValues[j].hasOwnProperty('validFor'))
- {
- newValue.validFor = fieldList.picklistValues[j].validFor;
- }
- returnObj.values.push(newValue);
- }
- break;
- }
- }
- if(!validField)
- {
- throw 'Invalid field '+field+' specified for object ' + params.object;
- }
- }
- catch(exception)
- {
- returnObj.message = exception;showAlert(exception.message);
- returnObj.success = false;
- }
- return returnObj;
- }
- function setPickVals(field,optionsArray)
- {
- var options = '';
- for(var i = 0; i < optionsArray.length; i++)
- {
- options += '<option value="'+optionsArray[i].value+'">'+optionsArray[i].label+'</option>';
- }
- $(field).html(options);
- }
- function getDependentValues(field, value)
- {
- var returnObj = new returnObject();
- try
- {
- var dependencyCode = new Array();
- var getValues = getPicklistValues(field);
- if(!getValues.success)
- {
- throw getValues.message;
- }
- var picklistValues = getValues.values;
- var getController = getControllerName(field);
- if(!getController.success)
- {
- throw getController.message;
- }
- var controller = getController.values;
- // sub function to do the validFor test
- function isDependentValue(index, validFor)
- {
- var base64 = new sforce.Base64Binary("");
- var decoded = base64.decode(validFor);
- var bits = decoded.charCodeAt(index>>3);
- return ((bits & (0x80 >> (index%8))) != 0);
- }
- var controllerFields =getPicklistValues(controller);
- for(var item = 0; item < controllerFields.values.length; item++)
- {
- if(controllerFields.values[item].value.toLowerCase() == value.toLowerCase())
- {
- for(var i = 0; i < picklistValues.length; i++)
- {
- if(isDependentValue(item, picklistValues[i].validFor))
- {
- var newValue = new Object();
- newValue.label = picklistValues[i].label;
- newValue.value = picklistValues[i].value;
- newValue.default = picklistValues[i].defaultValue;
- newValue.validFor = picklistValues[i].validFor;
- newValue.validForName =controllerFields.values[item].value;
- returnObj.values.push(newValue);
- }
- }
- }
- }
- }
- catch(exception)
- {
- returnObj.success = false;
- returnObj.message = exception;showAlert(exception.message);
- }
- return returnObj;
- }
- // get the controller field name
- function getControllerName(field)
- {
- var returnObj = new returnObject();
- try
- {
- var isValid = false;
- for(var i = 0; i < describeResults.fields.length; i++)
- {
- var fieldList = describeResults.fields[i];
- var fieldName = fieldList.name;
- if(fieldName.toLowerCase() == field.toLowerCase())
- {
- if(fieldList.controllerName == undefined)
- {
- throw 'Field has no controller';
- }
- else
- {
- returnObj.values = fieldList.controllerName;
- isValid = true;
- }
- break;
- }
- }
- if(!isValid)
- {
- throw 'Invalid field '+field+' specified';
- }
- }
- catch(exception)
- {
- returnObj.success = false;
- returnObj.message = exception;showAlert(exception.message);
- }
- return returnObj;
- }
- function returnObject()
- {
- this.success = true;
- this.message = 'Operation Ran Successfully';
- this.values = new Array();
- }
- function getUmbrellaCampaignList()
- {
- writeLogEntry('Getting umbrella campaigns');
- var returnObj = new returnObject();
- try
- {
- $('#umbrellacampaigns').empty();
- $('#umbrellacampaigns').append($('<option value="--Select One--">', { value :null }) .text('--Select One--'));
- var selectList = '';
- var queryString = "Select name, id from campaign where isActive = true and recordType.Name = 'FPI Umbrella Campaign' ";
- runQuery(queryString,function(data){
- for(var i = 0; i < data.records.length; i++)
- {
- $('#umbrellacampaigns').append($('<option>', { value : data.records[i].Id }).text(data.records[i].Name));
- }
- });
- }
- catch(exception)
- {
- returnObj.success = false;
- returnObj.message = exception;showAlert(exception.message);
- }
- writeLogEntry('Getting umbrella campaigns complete');
- return returnObj;
- }
- function getMasterCampaignList(umbrellaCampaignId)
- {
- writeLogEntry('Getting master campaigns for umbrella ' + umbrellaCampaignId);
- var returnObj = new returnObject();
- try
- {
- $('#mastercampaigns').empty();
- $('#mastercampaigns').append($('<option value="--Select One--">', { value :null }) .text('--Select One--'));
- var selectList = '';
- for(i = 1; i < 16; i++)
- {
- selectList += 'Attribute_'+i+'__c,Attribute_'+i+'_Description__c,';
- }
- var queryString = "Select "+selectList+" name, id, serve_rotation__c from campaign where isActive = true and recordType.Name = 'FPI Parent Campaign' and parentId = '"+umbrellaCampaignId+"'";
- runQuery(queryString,function(data){
- if(data.records.length == 0)
- {
- $('#mastercampaigns').attr("disabled", true);
- }
- else
- {
- $('#mastercampaigns').removeAttr("disabled");
- }
- for(var i = 0; i < data.records.length; i++)
- {
- campaigns[data.records[i].Id] = data.records[i];
- campaigns[data.records[i].Id]['attributes'] = new Array();
- for(j = 1; j < 16; j++)
- {
- if(data.records[i]['Attribute_'+j+'__c'] == null)
- {
- break;
- }
- campaigns[data.records[i].Id]['attributes'][j] = data.records[i]['Attribute_'+j+'__c'];
- }
- $('#mastercampaigns').append($('<option>', { value : data.records[i].Id }).text(data.records[i].Name));
- }
- });
- }
- catch(exception)
- {
- returnObj.success = false;
- returnObj.message = exception;showAlert(exception.message);
- }
- writeLogEntry('Getting master campaigns for umbrella ' + umbrellaCampaignId + ' complete');
- return returnObj;
- }
- function tableSortify(tableId)
- {
- writeLogEntry('Adding table sort logic to table ' + tableId );
- var returnObj = new returnObject();
- try
- {
- $(tableId).tablesorter({
- widthFixed: true,
- // widget code now contained in the jquery.tablesorter.widgets.js file
- widgets : ['uitheme', 'zebra'],
- widgetOptions : {
- // adding zebra striping, using content and default styles - the ui css removes the background from default
- // even and odd class names included for this demo to allow switching themes
- zebra : ["ui-widget-content even", "ui-state-default odd"],
- // change default uitheme icons - find the full list of icons here: http://jqueryui.com/themeroller/ (hover over them for their name)
- // default icons: ["ui-icon-arrowthick-2-n-s", "ui-icon-arrowthick-1-s", "ui-icon-arrowthick-1-n"]
- // ["up/down arrow (cssHeaders/unsorted)", "down arrow (cssDesc/descending)", "up arrow (cssAsc/ascending)" ]
- uitheme : ["ui-icon-carat-2-n-s", "ui-icon-carat-1-s", "ui-icon-carat-1-n"]
- }
- })
- }
- catch(exception)
- {
- returnObj.success = false;
- returnObj.message = exception;showAlert(exception.message);
- }
- writeLogEntry('Adding table sort logic to table ' + tableId + ' complete' );
- return returnObj;
- }
- function getRespondentList(campaignId)
- {
- writeLogEntry('Getting respondents for campaign ' + campaignId );
- var returnObj = new returnObject();
- try
- {
- var selectList = '';
- for(i = 1; i < 16; i++)
- {
- selectList += 'RespondentRecord__r.Attribute_'+i+'_Met__c,';
- }
- var queryString = "Select "+selectList+" name, Contact__c, Contact__r.name, Contact__r.Firstname, Contact__r.Lastname, Contact__r.Gender__c, Contact__r.Age__c, Contact__r.Id, Contact__r.pid__c, Respondent_Number__c, Status__c, RespondentRecord__r.Child_Campaign__r.Time_Slot__c, Organization__r.Name, check__c, check__r.Name, RespondentRecord__r.Id, id from payments__c where Parent_Study__c = '"+campaignId+"'";
- runQuery(queryString,function(data){
- for(var i = 0; i < data.records.length; i++)
- {
- payments[data.records[i].Id] = data.records[i];
- var respNo = parseInt(Math.round(data.records[i].Respondent_Number__c),10);
- if(respNo > 0 && respNo != null)
- {
- if(!respondentNumbers.hasOwnProperty(respNo))
- {
- respondentNumbers[respNo] = new Object();
- }
- respondentNumbers[respNo]['available'] = false;
- $('#pid_'+respNo).html(data.records[i].Contact__r.Name);
- }
- }
- //Draw the actual table on the screen for the user
- drawCheckIntable(data);
- //apply the filtering as you type code
- $("#filter-box").keyup(function(){
- var s = $(this).val().toLowerCase().split(" ");
- $("#checkInTableGrid tr:hidden").show();
- $.each(s, function(){
- $("#checkInTableGrid tr:visible .indexColumn:not(:contains('"
- + this + "'))").parent().hide();
- });
- });
- $("#checkInTableGrid tr:has(td)").each(function(){
- var t = $(this).text().toLowerCase(); //all row text
- $("<td class='indexColumn'></td>")
- .hide().text(t).appendTo(this);
- });//each tr
- calculateServeScores();
- drawTotalsTable();
- });
- }
- catch(exception)
- {
- returnObj.success = false;
- returnObj.message = exception;showAlert(exception.message);
- }
- writeLogEntry('Getting respondents for campaign ' + campaignId + ' complete' );
- return returnObj;
- }
- function drawCheckIntable(paymentList)
- {
- writeLogEntry('Creating check in table using respondent data');
- var returnObj = new returnObject();
- var org = '';
- var check = '';
- try
- {
- var html = '<table id="checkInTableGrid" class="tablesorter">';
- html +='<thead><tr><th width="75">Action</th><th width="75">Resp No</th><th>Session</th><th>Firstname</th><th>Lastname</th><th>PID</th><th>Gender</th><th>Age</th><th>Org</th><th>Check</th><th>Details</th></thead><tbody>';
- for(var i = 0; i<paymentList.records.length;i++)
- {
- org = '';
- check = '';
- checkId = '';
- if(paymentList.records[i].Organization__r != null)
- {
- org = paymentList.records[i].Organization__r.Name;
- }
- if(paymentList.records[i].Check__r != null)
- {
- check = paymentList.records[i].Check__r.Name;
- checkId = paymentList.records[i].Check__c;
- }
- if(!paymentList.records[i].RespondentRecord__r.hasOwnProperty('Child_Campaign__r'))
- {
- paymentList.records[i].RespondentRecord__r.Child_Campaign__r = new Object();
- paymentList.records[i].RespondentRecord__r.Child_Campaign__r.Time_Slot__c = 'Unknown';
- }
- html+='<tr><td><select class="statusList" startStatus="'+paymentList.records[i].Status__c+'" contact="'+paymentList.records[i].Contact__c+'" payment="'+paymentList.records[i].Id+'">'+statusListValues+'</select><td><input type="text" class="respondentNumber" contact="'+paymentList.records[i].Contact__c+'" payment="'+paymentList.records[i].Id+'" size="4" maxlength="3" value="'+parseInt(Math.round(paymentList.records[i].Respondent_Number__c),10)+'"/></td><td>'+paymentList.records[i].RespondentRecord__r.Child_Campaign__r.Time_Slot__c+'</td><td>'+paymentList.records[i].Contact__r.FirstName+'</td><td>'+paymentList.records[i].Contact__r.LastName+'</td><td>'+paymentList.records[i].Contact__r.PID__c+'</td><td>'+paymentList.records[i].Contact__r.Gender__c+'</td><td>'+paymentList.records[i].Contact__r.Age__c+'</td><td>'+ org +'</td><td><div class="check" check="'+checkId+'" contact="'+paymentList.records[i].Contact__c+'" payment="'+paymentList.records[i].Id+'">'+check+'</div></td><td><button class="detailButton" contact="'+paymentList.records[i].Contact__c+'" payment="'+paymentList.records[i].Id+'" >Attribute and Quota Info</button><button class="assignCheckButton" contact="'+paymentList.records[i].Contact__c+'" payment="'+paymentList.records[i].Id+'" >Assign Check</button></td></tr>';
- }
- html += '</tbody></table>';
- $('#checkinTable').html(html);
- //set the default value of each select list to the value specified in the startStatus attribute
- $('.statusList').each(function(index){
- $(this).val($(this).attr('startStatus'));
- });
- //whena respondent record changes, get the possible value for the DQ reason field based on the status, then attempt to evaluate the respondent record.
- $('.statusList').change(function(event, ui){
- setPickVals('#dqReason',getDependentValues('Disqualification_Reason__c',$(this).val()).values);
- var saveResult = evalRespondentRecord($(this).val(), $(this).attr('contact'), $(this).attr('payment'),true);
- console.log(saveResult);
- if(!saveResult.success)
- {
- $(this).val(lastStatus);
- }
- lastStatus = $(this).val();
- }).focus(function(){
- setCheckedAttributes($(this).attr('payment'));
- lastStatus = $(this).val();
- lastContact = $(this).attr('contact');
- lastPayment = $(this).attr('payment');
- });
- $('.respondentNumber').blur(function(ui,event){
- //only bother attempting to save if the value has changed.
- if(lastRespNum != $(this).val())
- {
- //evalRespondentRecord( $('.statusList[contact='+$(this).attr('contact')+']').val(), $(this).attr('contact'), $(this).attr('payment'));
- }
- }).focus(function(ui,event){
- lastRespNum = $(this).val();
- }).keydown(function(event) {
- // Allow: backspace, delete, tab, escape, and enter
- if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
- // Allow: Ctrl+A
- (event.keyCode == 65 && event.ctrlKey === true) ||
- // Allow: home, end, left, right
- (event.keyCode >= 35 && event.keyCode <= 39)) {
- // let it happen, dont do anything
- return;
- }
- else {
- // Ensure that it is a number and stop the keypress
- if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
- event.preventDefault();
- }
- }
- });
- tableSortify('#checkInTableGrid');
- $( ".detailButton" ).button({
- icons: {
- primary: "ui-icon-shuffle"
- },
- text: false
- }).click(function(){
- setCheckedAttributes($(this).attr('payment'));
- $('#attributes').data('payment',$(this).attr('payment')).data('contact',$(this).attr('contact')).dialog('open');
- });
- $( ".assignCheckButton" ).button({
- icons: {
- primary: "ui-icon-pencil"
- },
- text: false
- }).click(function(){
- $('#updateCheckStatus').html(null);
- $('#assignCheck').dialog('option', 'title', 'Assign Check to for ' + payments[$(this).attr('payment')].Contact__r.Name);
- $('#assignCheck').data('payment',$(this).attr('payment')).data('contact',$(this).attr('contact')).dialog('open');
- $('#checkNumber').val( $('.check[payment="'+$(this).attr('payment')+ '"]').html());
- $('#updateCheckPaymentId').val($(this).attr('payment'));
- });
- }
- catch(exception)
- {
- returnObj.success = false;
- returnObj.message = exception;showAlert(exception.message);
- }
- writeLogEntry('Creating check in table using respondent data complete');
- return returnObj;
- }
- function parseCSV(text)
- {
- writeLogEntry('Parsing rotation CSV content');
- var returnObj = new returnObject();
- try
- {
- totals = new Object();
- text = text + '\n';
- var fields = text.split(/\n/);
- fields.pop(fields.length-1);
- var headers = fields[0].split(','), html = '<table cellspacing="2" cellpadding="2" border="1" width="550" id="serveTable" class="tablesorter">';
- html += '<thead><tr>';
- for(var i = 0; i < headers.length; i += 1)
- {
- html += '<th scope="col" width="75">' + headers[i].trim() + '</th>';
- }
- html += '<th width="75">Score</th><th scope="col" width="85">Respondent</th>';
- html += '</tr></thead><tbody> ';
- var data = fields.slice(1, fields.length);
- var attributes = '';
- for(var j = 0; j < data.length; j++)
- {
- var dataFields = data[j].split(',');
- var respNum = new Object();
- respNum['available'] = true;
- respNum['serves'] = new Object();
- respNum['score'] = 0;
- respNum['baseScore'] = 0;
- respNum['scoremod'] = 0;
- respNum['respno'] = dataFields[0].trim();
- html += '<tr>';
- for(var k =0; k < dataFields.length; k++)
- {
- dataFields[k] = dataFields[k].trim();
- if(k != 1)
- {
- html += '<td>' + dataFields[k] + '</td>';
- }
- else
- {
- html += '<td><input type="number" class="scoremod" disabled="disabled" readonly id="scoremod' + dataFields[0] +'" value="'+dataFields[k]+'" size="2" maxlength="3" /> </td>';
- respNum['scoremod'] = dataFields[k];
- }
- if(k > 1 && !codes.hasOwnProperty(dataFields[k]))
- {
- codes[dataFields[k]] = campaigns[$('#mastercampaigns').val()]['attributes'][Object.keys(codes).length+1];
- attributes += '<li><input type="checkbox" name="attribBox_'+dataFields[k]+'" code="'+dataFields[k]+'" attribute="'+campaigns[$('#mastercampaigns').val()]['attributes'][k]+'" id="attribBox_'+dataFields[k]+'" class="attrib_box" value="'+dataFields[k]+'"><label for="attribBox_'+dataFields[k]+'">'+dataFields[k]+' (' +codes[dataFields[k]]+')</label></li>';
- }
- if(k > 1)
- {
- respNum['serves'][dataFields[k]] = 1;
- }
- }
- respondentNumbers[dataFields[0]] = respNum;
- html += '<td><div id="score_'+dataFields[0]+'">0</div></td>';
- html += '<td><div id="pid_'+dataFields[0]+'"></div></td>';
- html += '</tr>';
- }
- html += '</tbody></table>';
- $('#rotationTable').html(html);
- tableSortify('#serveTable');
- drawTotalsTable();
- $('#respondent_attributes').html(attributes);
- }
- catch(exception)
- {
- returnObj.success = false;
- returnObj.message = exception;showAlert(exception.message);
- }
- writeLogEntry('CSV Parsing complete');
- return returnObj;
- }
- function calculateServeScores()
- {
- writeLogEntry('Calculating serve scores');
- var returnObj = new returnObject();
- try
- {
- for(respNo in respondentNumbers)
- {
- if(respondentNumbers[respNo]['available'] == true)
- {
- respondentNumbers[respNo]['score'] = 0;
- for(serve in respondentNumbers[respNo]['serves'])
- {
- respondentNumbers[respNo]['score'] += parseInt(totals[serve]['unused'],10);
- }
- $('#score_'+respNo).html(respondentNumbers[respNo]['score']);
- }
- else
- {
- //$('#score_'+respNo).html('----');
- }
- }
- }
- catch(exception)
- {
- returnObj.success = false;
- returnObj.message = exception;showAlert(exception.message);
- }
- writeLogEntry('Calculating serve scores complete');
- return returnObj;
- }
- function drawTotalsTable()
- {
- writeLogEntry('Drawing totals table');
- var returnObj = new returnObject();
- try
- {
- var totalServes = 0;
- totals = new Object();
- for(respNo in respondentNumbers)
- {
- for(serve in respondentNumbers[respNo]['serves'])
- {
- totalServes++;
- if(!totals.hasOwnProperty(serve))
- {
- totals[serve] = new Object();
- totals[serve]['total'] = 0;
- totals[serve]['used'] = 0;
- totals[serve]['unused'] = 0;
- }
- if(respondentNumbers[respNo]['available'])
- {
- totals[serve]['unused']++;
- }
- else
- {
- totals[serve]['used']++;
- }
- totals[serve]['total']++;
- }
- }
- var totalsTable = '<table class="tablesorter" id="totalsTable" cellspacing="2" cellpadding="2" border="1" width="550">';
- totalsTable += '<thead><tr><th width="75">Serve</th><th width="75">Total</th><th width="85">Percent Of Total</th><th width="75">Assigned</th><th width="75">Remaining</th></thead><tbody>';
- for(key in totals)
- {
- totalsTable+= '<tr><td>'+key+' ('+codes[key]+')</td><td>'+totals[key]['total']+'</td><td>'+parseInt(totals[key]['total']/totalServes*100,10)+'%</td><td><div id="assigned_'+key+'">'+totals[key]['used']+'</div></td><td><div id="remaining_'+key+'">'+totals[key]['unused']+'</div></td></tr>';
- }
- totalsTable += '</tbody></table>';
- $('#totals').html(totalsTable);
- tableSortify('#totalsTable');
- }
- catch(exception)
- {
- returnObj.success = false;
- returnObj.message = exception;showAlert(exception.message);
- }
- writeLogEntry('Drawing totals table complete');
- return returnObj;
- }
- function evalRespondentRecord(status, contact, payment,showDQPopup)
- {
- writeLogEntry('Evaluating payment record ' + payment + ' with status ' + status);
- var returnObj = new returnObject();
- try
- {
- var currentRespondentNumber = $('.respondentNumber[contact='+payments[payment].Contact__r.Id+']').val();
- writeLogEntry('Found record has respondent number ' + currentRespondentNumber);
- if( (status == 'Disqualified - Paid' || status == 'Disqualified - Not Paid') && showDQPopup)
- {
- writeLogEntry('Respondent has disqualified status, but no reason specified. Presenting reason dialog');
- $( "#selectDQReason" ).dialog( "open" );
- currentRespondentNumber = unassignRespondentNumber(payment).data;
- returnObj.message = 'Respondent Not Saved. Disqualified Status with No reason selected';
- return returnObj;
- }
- else if(status != 'Tested' && status != 'In Progress')
- {
- writeLogEntry('Respondent has non tested status. Clearing respondent number.');
- currentRespondentNumber = unassignRespondentNumber(payment).data;
- }
- else if(status == 'Tested' || status == 'In Progress')
- {
- unassignRespondentNumber(payment);
- }
- var saveRespondent = assignRespondentNumber(payment,currentRespondentNumber,$('#useRotation').is(':checked'),status);
- if(saveRespondent.success)
- {
- calculateServeScores();
- $('#dqReason').val('none');
- drawTotalsTable();
- }
- else
- {
- writeLogEntry('Respondent record not saved. Reverting changes');
- throw new UserException(saveRespondent.message.message);
- }
- }
- catch(exception)
- {
- returnObj.success = false;
- returnObj.message = exception;
- showAlert(exception.message);
- }
- return returnObj;
- }
- function savePayment(obj)
- {
- setStatusMessage('Saving payment for ' + obj.Id);
- var returnObj = new returnObject();
- returnObj.data = 0;
- try
- {
- var paymentsToUpdate = new Array();
- var thisPayment = new sforce.SObject("Payments__c");
- for(field in obj)
- {
- thisPayment[field] = obj[field];
- }
- paymentsToUpdate.push(thisPayment);
- saveResult = saveObject(paymentsToUpdate);
- if(saveResult[0].success == 'false')
- {
- throw new UserException('Save error: ' + saveResult[0].errors.message + ' ' + saveResult[0].errors.statusCode);
- }
- returnObj.values = saveResult;
- setStatusMessage('');
- }
- catch(exception)
- {
- returnObj.success = false;
- returnObj.message = exception;
- showAlert(exception.message);
- }
- return returnObj;
- }
- function assignRespondentNumber(paymentId,respNum,useRotation,status)
- {
- var returnObj = new returnObject();
- returnObj.data = 0;
- try
- {
- //if we are passed a numm respondent number, that means we want to use the rotation assigner to generate one.
- if((respNum == null || respNum <=0) && useRotation && (status == 'Tested' || status == 'In Progress'))
- {
- writeLogEntry('Respondent is null or 0. Using rotation assigner. Finding valid rotation');
- var getRespNo = findAvailableRespondentNumber(paymentId);
- if(getRespNo.success)
- {
- writeLogEntry('Rotation found. Assigning respondent number ' + getRespNo.data);
- unassignRespondentNumber(paymentId);
- respNum = getRespNo.data;
- }
- else
- {
- writeLogEntry('No valid rotation could be located. Tossing error');
- $('.respondentNumber[contact='+payments[paymentId].Contact__r.Id+']').effect( "shake", 100 ).addClass('ui-state-error');
- throw new UserException("No valid rotation could be found for this respondent. Please adjust attributes or disqualify respondent.");
- }
- }
- else if((respNum == null || respNum <= 0) && (status == 'Tested' || status == 'In Progress') && !useRotation)
- {
- writeLogEntry('Respondent is null or 0 and not using rotation assigner. Invalid respondent number, tossing error');
- $('.respondentNumber[contact='+payments[paymentId].Contact__r.Id+']').effect( "shake", 100 ).addClass('ui-state-error');
- throw new UserException("Invalid respondent number. Respondent number must not be 0 if not using rotation assigner");
- }
- returnObj.data = respNum;
- //create payment object to be saved
- var thisPayment = new Object();
- thisPayment.id = paymentId;
- thisPayment.Respondent_Number__c = respNum;
- thisPayment.Status__c = status;
- writeLogEntry('Prepping record(s) for save...');
- var saveResult = savePayment(thisPayment);
- if(saveResult.success)
- {
- $('#pid_'+ respNum).html(payments[paymentId].Contact__r.Name);
- payments[paymentId].Respondent_Number__c = respNum;
- $('.respondentNumber[contact='+payments[paymentId].Contact__r.Id+']').val(respNum).removeClass('ui-state-error');
- if(respNum > 0)
- {
- respondentNumbers[respNum]['available'] = false;
- writeLogEntry('Incrimenting used count for serves in this rotation');
- for(serve in respondentNumbers[respNum]['serves'])
- {
- writeLogEntry('Incrimenting serve to have total of ' + serve);
- totals[serve]['used']++;
- totals[serve]['unused']--;
- }
- }
- else
- {
- writeLogEntry('No ajustments in total since respondent has been unassigned and did not receive new respondent number.');
- }
- }
- else
- {
- throw new UserException("Error saving payment: " + saveResult.message.message);
- }
- }
- catch(exception)
- {
- returnObj.success = false;
- returnObj.message = exception;
- }
- return returnObj;
- }
- function findAvailableRespondentNumber(paymentId)
- {
- writeLogEntry('Trying to find available rotation for respondent');
- var returnObj = new returnObject();
- try
- {
- var assignedAttributes = new Array();
- $('.attrib_box:checked').each(function(index){
- assignedAttributes.push($(this).val());
- });
- writeLogEntry('Respondent has attributes: '+assignedAttributes.join(", "));
- var potentials = new Array();
- for(respNo in respondentNumbers)
- {
- var isValid = true;
- if(!respondentNumbers[respNo]['available'])
- {
- continue;
- }
- for(serve in respondentNumbers[respNo]['serves'])
- {
- if($.inArray(serve, assignedAttributes) < 0)
- {
- isValid = false;
- }
- }
- if(isValid)
- {
- potentials.push(respondentNumbers[respNo]);
- writeLogEntry('Found potential respondent numbers/serve codes : '+respNo);
- }
- }
- var score = 100000;
- var respNo = -1;
- for(var i = 0; i< potentials.length; i++)
- {
- if(potentials[i]['score'] < score && potentials[i]['score'] > 0)
- {
- score = potentials[i]['score'] ;
- respNo = potentials[i]['respno'] ;
- }
- }
- returnObj.data = respNo;
- if(respNo < 0)
- {
- throw new UserException("No matching code found for attributes on respondent.");
- }
- }
- catch(exception)
- {
- returnObj.success = false;
- returnObj.message = exception;
- showAlert(exception.message);
- }
- return returnObj;
- }
- function unassignRespondentNumber(paymentId)
- {
- var returnObj = new returnObject();
- try
- {
- returnObj.data = 0;
- var respNo = parseInt(Math.round(payments[paymentId].Respondent_Number__c),10);
- writeLogEntry('Clearing stored information for respondent number : '+respNo);
- if(respondentNumbers.hasOwnProperty(respNo) && respondentNumbers[respNo].hasOwnProperty('serves') && respNo > 0)
- {
- for(serve in respondentNumbers[respNo]['serves'])
- {
- totals[serve]['used']--;
- totals[serve]['unused']++;
- }
- }
- $('#pid_'+ respNo).html(null);
- payments[paymentId].Respondent_Number__c = 0;
- $('.respondentNumber[contact='+payments[paymentId].Contact__r.Id+']').val(0);
- if(respondentNumbers.hasOwnProperty(respNo) && respNo > 0)
- {
- respondentNumbers[respNo]['available'] = true;
- }
- }
- catch(exception)
- {
- returnObj.success = false;
- returnObj.message = exception;
- showAlert(exception.message + ' on line ' + exception.lineNumber);
- }
- return returnObj;
- }
- function setStatusMessage(message)
- {
- $('#statusDiv').html(message);
- }
- function saveObject(objectList)
- {
- var saveResult = sforce.connection.update(objectList);
- return saveResult;
- }
- function runQuery(queryString,callback)
- {
- var resultHandler = {onSuccess : function(queryResult){
- if(queryResult.size == 0)
- {
- queryResult.records = new Array();
- }
- if(queryResult.size == 1)
- {
- var dataArray = new Array();
- dataArray[0] = new Object();
- for(key in queryResult.records)
- {
- dataArray[0][key] = queryResult.records[key];
- }
- delete queryResult['records'];
- queryResult.records = dataArray;
- }
- callback(queryResult);
- },
- onFailure : function(e){
- console.log(e);
- alert('Error: ' + e);
- }
- };
- var queryResult = sforce.connection.query(queryString, resultHandler);
- }
- function showAlert(message)
- {
- writeLogEntry(message);
- $('#statusDiv').html(message);
- }
- function UserException(message) {
- this.message = message;
- this.name = "UserException";
- }
- function checkOnline()
- {
- if (!navigator.onLine)
- {
- writeLogEntry('Internet connectivity interuption. This has happened ' + offlineCount + ' times');
- offlineCount++;
- }
- else
- {
- if(offlineCount > 5)
- {
- writeLogEntry('Connectivity Restored');
- }
- offlineCount = 0;
- $('#lostConnection').dialog('close');
- }
- if(offlineCount > 5)
- {
- $('#lostConnection').dialog('open');
- }
- }
- function writeLogEntry(message)
- {
- $('#log').append(message + '<br/>');
- }
- function setLink(campaignName)
- {
- var reportName = 'Payments Report grouped by Study #';
- var campaignId = campaignName.substring(0,campaignName.indexOf('-'));
- var instance = 'na2';
- try
- {
- var url = window.location.toString();
- instance = url.substring(10,13);
- }
- catch(ex){ }
- if(reportId == null)
- {
- runQuery("select id from report where name = '"+reportName+"'",function(data){
- reportId = data.records[0].Id;
- var basePath = 'https://'+instance+'.salesforce.com/'+reportId+'?pv0='+campaignId;
- $("#reportLink").prop("href", basePath);
- $('#filter-box').val(null);
- });
- }
- else
- {
- var basePath = 'https://'+instance+'.salesforce.com/'+reportId+'?pv0='+campaignId;
- $("#reportLink").prop("href", basePath);
- $('#filter-box').val(null);
- }
- }
- </script>
- <title>Host Check In EXTREME!</title>
- </head>
- <body>
- <div id="toolbar" class="ui-widget-header ui-corner-all">
- <label for="mastercampaigns">Select Campaign</label>
- <select id="umbrellacampaigns"><option>--Select One--</option></select>
- <select id="mastercampaigns"><option>--Select One--</option></select>
- <!-----
- <button id="tlbrBtn1">Rotation Table</button>
- <button id="tlbrBtn2">Report Link</button>
- <button id="tlbrBtn3">Progress Tracker</button>
- <button id="tlbrBtn4">Reload Respondent List</button>
- ------>
- Search: <input name="filter" id="filter-box" value="" maxlength="30" size="30" type="text" />
- <button class="button" id="clearButton">Clear</button>
- <div class="clear"></div>
- <input type="checkbox" id="useRotation" name="useRotation" disabled="disabled" /><label for="useRotation">Use Rotation Assigner</label>
- <button class="button" id="bulkStatusChangeButton" disabled="disabled">Change Statuses</button>
- <a class="reportLink button" href="https://na2.salesforce.com/00O40000002jNnY?pv0=02585" id="reportLink" target="_blank" >Report Link</a>
- <span id="statusDiv"></span>
- <div id="switcher"></div>
- </div>
- <div id="container">
- <ul id="tabs">
- <li><a href="#tabs-1">Check In</a></li>
- <li><a href="#tabs-2">Rotation Tables</a></li>
- <li><a href="#tabs-3">Rotation Totals</a></li>
- <li><a href="#tabs-4">Progress Tracker</a></li>
- <li><a href="#tabs-5">Log</a></li>
- </ul>
- <div id="tabs-1">
- <div id="checkinTable"></div>
- </div>
- <div id="tabs-2">
- <div id="rotationTable"></div>
- </div>
- <div id="tabs-3">
- <div id="totals"></div>
- </div>
- <div id="tabs-4">
- <iframe id="progressTrackerFrame" width="100%" height="500" frameborder="0"></iframe>
- </div>
- <div id="tabs-5">
- <div id="log"></div><br />
- <button id="clearLog" class="button">Clear Log</button>
- </div>
- <div id="reportLink" class="dialog" title="Report"></div>
- <div id="progressTracker" class="dialog" title="Progress Tracker"></div>
- <div id="selectDQReason" class="dialog" title="Select Disqualification Reason">
- <p>Please select the reason this person is being disqualified.</p>
- <select id="dqReason" size="1"></select>
- <div id="dqSaveResult"></div>
- <input type="button" class="button" name="submitRow" id="saveDQRow" value="Save" />
- <input type="button" class="button" name="cancelSave" id="cancelDQRow" value="Cancel" />
- </div>
- <div id="showAlert" class="dialog" title="Alert!"></div>
- <div id="attributes" class="dialog" title="Respondent Attributes">
- View/Edit Respondent Attributes/Serve Codes
- <ul id="respondent_attributes"></ul>
- <div id="updateAttributeStatus"></div>
- <input id="updateAttributePaymentId" type="hidden" />
- <center><input type="button" value="Update" id="updateAttributes" class="button"/><input type="button" value="Cancel" class="button"/></center>
- </div>
- <div id="assignCheck" class="dialog" title="Assign Check To Respondent">
- <label for="checkNumber">Check Number</label>
- <input type="text" name="checkNumber" id="checkNumber" />
- <div id="updateCheckStatus"></div>
- <br /><br/>
- <center><input type="button" value="Update" id="assignCheckButton" class="button"/><input type="button" value="Cancel" class="button"/></center>
- <input id="updateCheckPaymentId" type="hidden" />
- </div>
- </div>
- <div id="bulkStatusChange" title="Bulk Change Status" class="dialog">
- <table>
- <tr>
- <td><label for="bulkChangeFrom">Change Payments With Status</label></td><td><select id="bulkChangeFrom"></select></td>
- </tr>
- <tr>
- <td><label for="bulkChangeTo">To Have Status</label></td><td><select id="bulkChangeTo"></select></td>
- </tr>
- <tr>
- <td> <button class="button" id="bulkStatusChangeSubmit">Change</button> </td><td><div id="bulkChangeProgressBar"></div><div id="bulkChangeProgressVal"></div></td>
- </tr>
- </table>
- </div>
- <div id="lostConnection" title="No Internet Connection!">It seems internet connectivity has been lost. Please check your connection. This dialog will automatically close when connection has been re-established.</div>
- </body>
- </apex:page>
Add Comment
Please, Sign In to add comment