Skip to content

Commit

Permalink
Fixed issue #13080: Cannot add survey participants to the CPDB
Browse files Browse the repository at this point in the history
  • Loading branch information
lacrioque committed Dec 22, 2017
1 parent 4d549f3 commit da00c75
Show file tree
Hide file tree
Showing 5 changed files with 150 additions and 132 deletions.
7 changes: 7 additions & 0 deletions application/controllers/admin/tokens.php
Expand Up @@ -2357,6 +2357,13 @@ public function bouncesettings($iSurveyId)
$this->_renderWrappedTemplate('token', array('bounce'), $aData);
}

public function prepExportToCPDB(){
$exportedItems = Yii::app()->request->getPost('itemsid', []);
if(is_array($exportedItems)) { $_FILESexportedItems = json_encode($exportedItems); }
Yii::app()->session['participantid'] = $exportedItems;
return;
}

/**
* Handle token form for addnew/edit actions
* @param int $iSurveyId
Expand Down
101 changes: 52 additions & 49 deletions application/models/Participant.php
Expand Up @@ -1902,7 +1902,7 @@ public function copyToCentral($surveyid, $aAttributesToBeCreated, $aMapped, $ove
{
$survey = Survey::model()->findByPk($surveyid);
$tokenid_string = Yii::app()->session['participantid']; //List of token_id's to add to participants table
$tokenid = json_decode($tokenid_string);
$tokenids = json_decode($tokenid_string,true);
$duplicate = 0;
$sucessfull = 0;
$attid = array(); //Will store the CPDB attribute_id of new or existing attributes keyed by CPDB at
Expand All @@ -1917,78 +1917,81 @@ public function copyToCentral($surveyid, $aAttributesToBeCreated, $aMapped, $ove
/* Create CPDB attributes */
if (!empty($aAttributesToBeCreated)) {
foreach ($aAttributesToBeCreated as $key => $value) {
//creating new central attribute
//creating new central attribute
/* $key is the fieldname from the token table (ie "attribute_1")
* $value is the 'friendly name' for the attribute (ie "Gender")
*/
$insertnames = array('attribute_type' => 'TB', 'visible' => 'Y', 'defaultname' => $value);
Yii::app()->db
->createCommand()
->insert('{{participant_attribute_names}}', $insertnames);
$attid[$key] = $aAttributesToBeCreated[$key] = getLastInsertID('{{participant_attribute_names}}'); /* eg $attid['attribute_1']='8372' */
$insertnames = array(
'attribute_type' => 'TB',
'visible' => 'Y',
'defaultname' => $value
);
$oParticipantAttributeNames = new ParticipantAttributeName();
$oParticipantAttributeNames->setAttributes($insertnames, false);
$oParticipantAttributeNames->save(false);
$attid[$key] = $oParticipantAttributeNames->getPrimaryKey();

$insertnameslang = array(
'attribute_id' => $attid[$key],
'attribute_name' => urldecode($value),
'lang' => Yii::app()->session['adminlang']
);
Yii::app()->db
->createCommand()
->insert('{{participant_attribute_names_lang}}', $insertnameslang);
'attribute_id' => $attid[$key],
'attribute_name' => urldecode($value),
'lang' => Yii::app()->session['adminlang']
);
$oParticipantAttributeNamesLang = new ParticipantAttributeNameLang();
$oParticipantAttributeNamesLang->setAttributes($insertnameslang, false);
$oParticipantAttributeNamesLang->save(false);

}
}

/* Add the participants to the CPDB = Iterate through each $tokenid and create the new CPDB id*/
foreach ($tokenid as $key => $tid) {
if(!is_array($tokenids)) { $tokenids = (array) $tokenids; }
foreach ($tokenids as $tid) {
if (is_numeric($tid) && $tid != "") {
/* Get the data for this participant from the tokens table */
$tobeinserted = Yii::app()->db
->createCommand()
->select('participant_id,firstname,lastname,email,language')
->where('tid = :tid')
->from($survey->tokensTableName)
->bindParam(":tid", $tid, PDO::PARAM_INT)
->queryRow();
$oTokenDynamic = TokenDynamic::model($survey->sid)->findByPk($tid);

/* See if there are any existing CPDB entries that match on firstname,lastname and email */
$query = Yii::app()->db
->createCommand()
->select('*')
->from('{{participants}}')
->where('firstname = :firstname AND lastname = :lastname AND email = :email')
->bindParam(":firstname", $tobeinserted['firstname'], PDO::PARAM_STR)
->bindParam(":lastname", $tobeinserted['lastname'], PDO::PARAM_STR)
->bindParam(":email", $tobeinserted['email'], PDO::PARAM_STR)
->queryAll();
$participantCriteria = new CDbCriteria();
$participantCriteria->addCondition('firstname = :firstname');
$participantCriteria->addCondition('lastname = :lastname');
$participantCriteria->addCondition('email = :email');
$participantCriteria->params = [
":firstname" => $oTokenDynamic->firstname,
":lastname" => $oTokenDynamic->lastname,
":email" => $oTokenDynamic->email,
];
$existing = Participant::model()->find($participantCriteria);
/* If there is already an existing entry, add to the duplicate count */
if (count($query) > 0) {
if ($existing != null) {
$duplicate++;
if ($overwriteman == "true" && !empty($aMapped)) {
foreach ($aMapped as $cpdbatt => $tatt) {
Participant::model()->updateAttributeValueToken($surveyid, $query[0]['participant_id'], $cpdbatt, $tatt);
Participant::model()->updateAttributeValueToken($surveyid, $existing->participant_id, $cpdbatt, $tatt);
}
}
}
/* If there isn't an existing entry, create one! */
else {
/* Create entry in participants table */
$black = !empty($tobeinserted['blacklisted']) ? $tobeinserted['blacklisted'] : 'N';
$pid = !empty($tobeinserted['participant_id']) ? $tobeinserted['participant_id'] : $this->gen_uuid();
$black = !empty($oTokenDynamic->blacklisted) ? $oTokenDynamic->blacklisted : 'N';
$pid = !empty($oTokenDynamic->participant_id) ? $oTokenDynamic->participant_id : $this->gen_uuid();

$writearray = array('participant_id' => $pid,
'firstname' => $tobeinserted['firstname'],
'lastname' => $tobeinserted['lastname'],
'email' => $tobeinserted['email'],
'language' => $tobeinserted['language'],
'firstname' => $oTokenDynamic->firstname,
'lastname' => $oTokenDynamic->lastname,
'email' => $oTokenDynamic->email,
'language' => $oTokenDynamic->language,
'blacklisted' => $black,
'owner_uid' => Yii::app()->session['loginID'],
'created_by' => Yii::app()->session['loginID'],
'created' => date('Y-m-d H:i:s', time()));
Yii::app()->db
->createCommand()
->insert('{{participants}}', $writearray);
$oParticipant = new Participant();
$oParticipant->setAttributes($writearray, false);
$oParticipant->save(false);

//Update token table and insert the new UUID
$data = array("participant_id"=>$pid);
Yii::app()->db
->createCommand()
->update($survey->tokensTableName, $data, "tid = $tid");
$oTokenDynamic->participant_id = $pid;
$oTokenDynamic->save(false);

/* Now add any new attribute values */
if (!empty($aAttributesToBeCreated)) {
Expand All @@ -2005,15 +2008,15 @@ public function copyToCentral($surveyid, $aAttributesToBeCreated, $aMapped, $ove
$sucessfull++;

/* Create a survey_link */
$oSurveyLink = new SurveyLink();
$data = array(
'participant_id' => $pid,
'token_id' => $tid,
'survey_id' => $surveyid,
'date_created' => date('Y-m-d H:i:s', time())
);
Yii::app()->db
->createCommand()
->insert('{{survey_links}}', $data);
$oSurveyLink->setAttributes($data, false);
$oSurveyLink->save(false);
}
}
}
Expand Down
5 changes: 4 additions & 1 deletion application/views/admin/token/browse.php
Expand Up @@ -45,14 +45,17 @@
'columns' => $model->attributesForGrid,
'ajaxUpdate'=>'token-grid',
'ajaxType'=>'POST',
'afterAjaxUpdate' => 'reinstallParticipantsFilterDatePicker'
'afterAjaxUpdate' => 'onUpdateTokenGrid'
));
?>
</div>
</div>

<?php
// To update rows per page via ajax
App()->getClientScript()->registerScript("Tokens:neccesaryVars", "
var postUrl = '".App()->createUrl('admin/tokens/sa/prepExportToCPDB/sid/'.$_GET['surveyid'])."';
", LSYii_ClientScript::POS_BEGIN);
App()->getClientScript()->registerScript("Tokens:updateRowsPerPage", "
if($('token-grid').length > 0){
reinstallParticipantsFilterDatePicker();
Expand Down
6 changes: 3 additions & 3 deletions assets/scripts/admin/listresponse.js
Expand Up @@ -100,7 +100,6 @@ function reinstallResponsesFilterDatePicker() {
var data = $('#responses-grid .filters input, #responses-grid .filters select').serialize();
$.fn.yiiGridView.update('responses-grid', {data: data});
});

}

function onDocumentReadyListresponse() {
Expand All @@ -119,7 +118,8 @@ function onDocumentReadyListresponse() {
});

}
$(function(){

$(document).on('ready pjax:scriptcomplete',function(){
onDocumentReadyListresponse();
reinstallResponsesFilterDatePicker();
})
});
163 changes: 84 additions & 79 deletions assets/scripts/admin/tokens.js
Expand Up @@ -232,87 +232,10 @@ $(document).on('ready pjax:scriptcomplete', function(){
});
})
});
/**
* Token edit
*/
$(document).on( 'click', '.edit-token', function(){
var $that = $(this),
$sid = $that.data('sid'),
$tid = $that.data('tid'),
$actionUrl = $that.data('url'),
$modal = $('#editTokenModal'),
$modalBody = $modal.find('.modal-body'),
$ajaxLoader = $('#ajaxContainerLoading2'),
$oldModalBody = $modalBody.html();


$ajaxLoader.show();
$modal.modal('show');
// Ajax request
$.ajax({
url : $actionUrl,
type : 'GET',

// html contains the buttons
success : function(html, statut){

$('#modal-content').empty().append(html); // Inject the returned HTML in the modal body

// Apply the yes/no/date jquery plugin to the elements loaded via ajax
/*
$('#sent-yes-no-date-container').YesNoDate();
$('#remind-yes-no-date-container').YesNoDate();
$('#completed-yes-no-date-container').YesNoDate();
*/

$('.yes-no-date-container').each(function(el){
$(this).YesNoDate();
});


$('.yes-no-container').each(function(el){
$(this).YesNo();
});

$('#validfrom').datetimepicker({locale: $('#validfrom').data('locale')});
$('#validuntil').datetimepicker({locale: $('#validuntil').data('locale')});

$('.date .input-group-addon').on('click', function(){
$prev = $(this).siblings();
$prev.data("DateTimePicker").show();
});

var elGeneral = $('#general');

// Fake hide of modal content, so we can still get width of inner elements like labels
var previousCss = $("#modal-content").attr("style");
$("#modal-content")
.css({
position: 'absolute', // Optional if #myDiv is already absolute
visibility: 'hidden',
display: 'block'
});

// Stick the labels on the left side
// Sometime, the content is loaded after modal is shown, sometimes not. So, we wait 200ms just in case (For label width)
setTimeout(function(){
elGeneral.stickLabelOnLeft();
$ajaxLoader.hide();
// Remove fake hide
$("#modal-content").attr("style", previousCss ? previousCss : "");
}, 200);

},
error : function(html, statut){
$ajaxLoader.hide();
$('#modal-content').empty().append(html);
console.ls.error(html);
}
});
});

$('.edit-token').off('click.edittoken').on('click.edittoken', startEditToken);

$(document).on('submit.edittoken','#edittoken',function(event){
$('#edittoken').off('submit.edittoken').on('submit.edittoken',function(event){
if($('#editTokenModal').length > 0 ){
event.preventDefault();
submitEditToken();
Expand Down Expand Up @@ -407,6 +330,84 @@ $(document).on('ready pjax:scriptcomplete', function(){

});

/**
* Token edit
*/
var startEditToken = function(){
var $that = $(this),
$sid = $that.data('sid'),
$tid = $that.data('tid'),
$actionUrl = $that.data('url'),
$modal = $('#editTokenModal'),
$modalBody = $modal.find('.modal-body'),
$ajaxLoader = $('#ajaxContainerLoading2'),
$oldModalBody = $modalBody.html();

$ajaxLoader.show();
$modal.modal('show');
// Ajax request
$.ajax({
url : $actionUrl,
type : 'GET',

// html contains the buttons
success : function(html, statut){

$('#modal-content').empty().append(html); // Inject the returned HTML in the modal body

// Apply the yes/no/date jquery plugin to the elements loaded via ajax
/*
$('#sent-yes-no-date-container').YesNoDate();
$('#remind-yes-no-date-container').YesNoDate();
$('#completed-yes-no-date-container').YesNoDate();
*/

$('.yes-no-date-container').each(function(el){
$(this).YesNoDate();
});


$('.yes-no-container').each(function(el){
$(this).YesNo();
});

$('#validfrom').datetimepicker({locale: $('#validfrom').data('locale')});
$('#validuntil').datetimepicker({locale: $('#validuntil').data('locale')});

$('.date .input-group-addon').on('click', function(){
$prev = $(this).siblings();
$prev.data("DateTimePicker").show();
});

var elGeneral = $('#general');

// Fake hide of modal content, so we can still get width of inner elements like labels
var previousCss = $("#modal-content").attr("style");
$("#modal-content")
.css({
position: 'absolute', // Optional if #myDiv is already absolute
visibility: 'hidden',
display: 'block'
});

// Stick the labels on the left side
// Sometime, the content is loaded after modal is shown, sometimes not. So, we wait 200ms just in case (For label width)
setTimeout(function(){
elGeneral.stickLabelOnLeft();
$ajaxLoader.hide();
// Remove fake hide
$("#modal-content").attr("style", previousCss ? previousCss : "");
}, 200);

},
error : function(html, statut){
$ajaxLoader.hide();
$('#modal-content').empty().append(html);
console.ls.error(html);
}
});
};

var conditionid=1;
function checkbounces() {
$("#dialog-modal").dialog('open');
Expand Down Expand Up @@ -445,6 +446,10 @@ function centerInfoDialog() {
infoDialog.css({ 'left': Math.round((dialogparent.width() - infoDialog.width()) / 2)+'px' });
}

function onUpdateTokenGrid(){
reinstallParticipantsFilterDatePicker();
$('.edit-token').off('click.edittoken').on('click.edittoken', startEditToken);
}

/**
* When date-picker is used in token gridview
Expand Down

0 comments on commit da00c75

Please sign in to comment.