First commit

This commit is contained in:
Theodotos Andreou 2018-01-14 13:10:16 +00:00
commit c6e2478c40
13918 changed files with 2303184 additions and 0 deletions

View file

@ -0,0 +1,651 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to record voter's interview.
*/
class CRM_Campaign_Form_Task_Interview extends CRM_Campaign_Form_Task {
/**
* The title of the group
*
* @var string
*/
protected $_title;
/**
* Variable to store redirect path
*/
private $_userContext;
private $_groupTree;
private $_surveyFields;
private $_surveyTypeId;
private $_interviewerId;
private $_surveyActivityIds;
private $_votingTab = FALSE;
private $_surveyValues;
private $_resultOptions;
private $_allowAjaxReleaseButton;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
$this->_votingTab = $this->get('votingTab');
$this->_reserveToInterview = $this->get('reserveToInterview');
if ($this->_reserveToInterview || $this->_votingTab) {
//user came from voting tab / reserve form.
foreach (array(
'surveyId',
'contactIds',
'interviewerId',
) as $fld) {
$this->{"_$fld"} = $this->get($fld);
}
//get the target voter ids.
if ($this->_votingTab) {
$this->getVoterIds();
}
}
else {
parent::preProcess();
//get the survey id from user submitted values.
$this->_surveyId = CRM_Utils_Array::value('campaign_survey_id', $this->get('formValues'));
$this->_interviewerId = CRM_Utils_Array::value('survey_interviewer_id', $this->get('formValues'));
}
if ($this->_surveyId) {
$params = array('id' => $this->_surveyId);
CRM_Campaign_BAO_Survey::retrieve($params, $this->_surveyDetails);
}
$orderClause = FALSE;
$buttonName = $this->controller->getButtonName();
if ($buttonName == '_qf_Interview_submit_orderBy' && !empty($_POST['order_bys'])) {
$orderByParams = CRM_Utils_Array::value('order_bys', $_POST);
}
elseif (CRM_Core_OptionGroup::getValue('activity_type', 'WalkList') == $this->_surveyDetails['activity_type_id']) {
$orderByParams
= array(
1 => array(
'column' => 'civicrm_address.street_name',
'order' => 'ASC',
),
2 => array(
'column' => 'civicrm_address.street_number%2',
'order' => 'ASC',
),
3 => array(
'column' => 'civicrm_address.street_number',
'order' => 'ASC',
),
4 => array(
'column' => 'contact_a.sort_name',
'order' => 'ASC',
),
);
}
$orderBy = array();
if (!empty($orderByParams)) {
foreach ($orderByParams as $key => $val) {
if (!empty($val['column'])) {
$orderBy[] = "{$val['column']} {$val['order']}";
}
}
if (!empty($orderBy)) {
$orderClause = "ORDER BY " . implode(', ', $orderBy);
}
}
$this->_contactIds = array_unique($this->_contactIds);
if (!empty($this->_contactIds) && $orderClause) {
$clause = 'contact_a.id IN ( ' . implode(',', $this->_contactIds) . ' ) ';
$sql = "
SELECT contact_a.id
FROM civicrm_contact contact_a
LEFT JOIN civicrm_address ON contact_a.id = civicrm_address.contact_id
WHERE {$clause}
{$orderClause}";
$this->_contactIds = array();
$dao = CRM_Core_DAO::executeQuery($sql);
while ($dao->fetch()) {
$this->_contactIds[] = $dao->id;
}
}
//get the contact read only fields to display.
$readOnlyFields = array_merge(array(
'contact_type' => '',
'sort_name' => ts('Name'),
));
//get the read only field data.
$returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
$returnProperties['contact_sub_type'] = TRUE;
//validate all voters for required activity.
//get the survey activities for given voters.
$this->_surveyActivityIds = CRM_Campaign_BAO_Survey::voterActivityDetails($this->_surveyId,
$this->_contactIds,
$this->_interviewerId
);
$activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
$scheduledStatusId = array_search('Scheduled', $activityStatus);
$activityIds = array();
foreach ($this->_contactIds as $key => $voterId) {
$actVals = CRM_Utils_Array::value($voterId, $this->_surveyActivityIds);
$statusId = CRM_Utils_Array::value('status_id', $actVals);
$activityId = CRM_Utils_Array::value('activity_id', $actVals);
if ($activityId &&
$statusId &&
$scheduledStatusId == $statusId
) {
$activityIds["activity_id_{$voterId}"] = $activityId;
}
else {
unset($this->_contactIds[$key]);
}
}
//retrieve the contact details.
$voterDetails = CRM_Campaign_BAO_Survey::voterDetails($this->_contactIds, $returnProperties);
$this->_allowAjaxReleaseButton = FALSE;
if ($this->_votingTab &&
(CRM_Core_Permission::check('manage campaign') ||
CRM_Core_Permission::check('administer CiviCampaign') ||
CRM_Core_Permission::check('release campaign contacts')
)
) {
$this->_allowAjaxReleaseButton = TRUE;
}
//validate voter ids across profile.
$this->filterVoterIds();
$this->assign('votingTab', $this->_votingTab);
$this->assign('componentIds', $this->_contactIds);
$this->assign('componentIdsJson', json_encode($this->_contactIds));
$this->assign('voterDetails', $voterDetails);
$this->assign('readOnlyFields', $readOnlyFields);
$this->assign('interviewerId', $this->_interviewerId);
$this->assign('surveyActivityIds', json_encode($activityIds));
$this->assign('allowAjaxReleaseButton', $this->_allowAjaxReleaseButton);
//get the survey values.
$this->_surveyValues = $this->get('surveyValues');
if (!is_array($this->_surveyValues)) {
$this->_surveyValues = array();
if ($this->_surveyId) {
$surveyParams = array('id' => $this->_surveyId);
CRM_Campaign_BAO_Survey::retrieve($surveyParams, $this->_surveyValues);
}
$this->set('surveyValues', $this->_surveyValues);
}
$this->assign('surveyValues', $this->_surveyValues);
$result = CRM_Campaign_BAO_Survey::getReportID($this->_surveyId);
$this->assign("instanceId", $result);
//get the survey result options.
$this->_resultOptions = $this->get('resultOptions');
if (!is_array($this->_resultOptions)) {
$this->_resultOptions = array();
if ($resultOptionId = CRM_Utils_Array::value('result_id', $this->_surveyValues)) {
$this->_resultOptions = CRM_Core_OptionGroup::valuesByID($resultOptionId);
}
$this->set('resultOptions', $this->_resultOptions);
}
//validate the required ids.
$this->validateIds();
//append breadcrumb to survey dashboard.
if (CRM_Campaign_BAO_Campaign::accessCampaign()) {
$url = CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=survey');
CRM_Utils_System::appendBreadCrumb(array(array('title' => ts('Survey(s)'), 'url' => $url)));
}
//set the title.
$activityTypes = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
$this->_surveyTypeId = CRM_Utils_Array::value('activity_type_id', $this->_surveyValues);
CRM_Utils_System::setTitle(ts('Record %1 Responses', array(1 => $activityTypes[$this->_surveyTypeId])));
}
public function validateIds() {
$required = array(
'surveyId' => ts('Could not find Survey.'),
'interviewerId' => ts('Could not find Interviewer.'),
'contactIds' => ts('No respondents are currently reserved for you to interview.'),
'resultOptions' => ts('Oops. It looks like there is no response option configured.'),
);
$errorMessages = array();
foreach ($required as $fld => $msg) {
if (empty($this->{"_$fld"})) {
if (!$this->_votingTab) {
CRM_Core_Error::statusBounce($msg);
break;
}
$errorMessages[] = $msg;
}
}
$this->assign('errorMessages', empty($errorMessages) ? FALSE : $errorMessages);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->assign('surveyTypeId', $this->_surveyTypeId);
$options
= array(
'' => ' - none - ',
'civicrm_address.street_name' => 'Street Name',
'civicrm_address.street_number%2' => 'Odd / Even Street Number',
'civicrm_address.street_number' => 'Street Number',
'contact_a.sort_name' => 'Respondent Name',
);
for ($i = 1; $i < count($options); $i++) {
$this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
$this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
'ASC' => ts('Ascending'),
'DESC' => ts('Descending'),
));
}
//pickup the uf fields.
$this->_surveyFields = CRM_Campaign_BAO_Survey::getSurveyResponseFields($this->_surveyId,
$this->_surveyTypeId
);
foreach ($this->_contactIds as $contactId) {
//build the profile fields.
foreach ($this->_surveyFields as $name => $field) {
if ($field) {
CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $contactId);
}
}
//build the result field.
if (!empty($this->_resultOptions)) {
$this->add('select', "field[$contactId][result]", ts('Result'),
array(
'' => ts('- select -'),
) +
array_combine($this->_resultOptions, $this->_resultOptions)
);
}
$this->add('text', "field[{$contactId}][note]", ts('Note'));
//need to keep control for release/reserve.
if ($this->_allowAjaxReleaseButton) {
$this->addElement('hidden',
"field[{$contactId}][is_release_or_reserve]", 0,
array('id' => "field_{$contactId}_is_release_or_reserve")
);
}
}
$this->assign('surveyFields', empty($this->_surveyFields) ? FALSE : $this->_surveyFields);
//no need to get qf buttons.
if ($this->_votingTab) {
return;
}
$buttons = array(
array(
'type' => 'cancel',
'name' => ts('Done'),
'subName' => 'interview',
'isDefault' => TRUE,
),
);
$buttons[] = array(
'type' => 'submit',
'name' => ts('Order By >>'),
'subName' => 'orderBy',
);
$manageCampaign = CRM_Core_Permission::check('manage campaign');
$adminCampaign = CRM_Core_Permission::check('administer CiviCampaign');
if ($manageCampaign ||
$adminCampaign ||
CRM_Core_Permission::check('release campaign contacts')
) {
$buttons[] = array(
'type' => 'next',
'name' => ts('Release Respondents >>'),
'subName' => 'interviewToRelease',
);
}
if ($manageCampaign ||
$adminCampaign ||
CRM_Core_Permission::check('reserve campaign contacts')
) {
$buttons[] = array(
'type' => 'done',
'name' => ts('Reserve More Respondents >>'),
'subName' => 'interviewToReserve',
);
}
$this->addButtons($buttons);
}
/**
* Set default values for the form.
*/
public function setDefaultValues() {
//load default data for only contact fields.
$contactFields = $defaults = array();
foreach ($this->_surveyFields as $name => $field) {
$acceptable_types = CRM_Contact_BAO_ContactType::basicTypes();
$acceptable_types[] = 'Contact';
if (in_array($field['field_type'], $acceptable_types)) {
$contactFields[$name] = $field;
}
}
if (!empty($contactFields)) {
foreach ($this->_contactIds as $contactId) {
CRM_Core_BAO_UFGroup::setProfileDefaults($contactId, $contactFields, $defaults, FALSE);
}
}
if (CRM_Core_OptionGroup::getValue('activity_type', 'WalkList') == $this->_surveyDetails['activity_type_id']) {
$defaults['order_bys']
= array(
1 => array(
'column' => 'civicrm_address.street_name',
'order' => 'ASC',
),
2 => array(
'column' => 'civicrm_address.street_number%2',
'order' => 'ASC',
),
3 => array(
'column' => 'civicrm_address.street_number',
'order' => 'ASC',
),
4 => array(
'column' => 'contact_a.sort_name',
'order' => 'ASC',
),
);
}
else {
$defaults['order_bys']
= array(
1 => array(
'column' => 'contact_a.sort_name',
'order' => 'ASC',
),
);
}
return $defaults;
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
$buttonName = $this->controller->getButtonName();
if ($buttonName == '_qf_Interview_done_interviewToReserve') {
//hey its time to stop cycle.
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/survey/search', 'reset=1&op=reserve'));
}
elseif ($buttonName == '_qf_Interview_next_interviewToRelease') {
//get ready to jump to release form.
foreach (array(
'surveyId',
'contactIds',
'interviewerId',
) as $fld) {
$this->controller->set($fld, $this->{"_$fld"});
}
$this->controller->set('interviewToRelease', TRUE);
}
// vote is done through ajax
}
/**
* @param array $params
*
* @return mixed
*/
public static function registerInterview($params) {
$activityId = CRM_Utils_Array::value('activity_id', $params);
$surveyTypeId = CRM_Utils_Array::value('activity_type_id', $params);
if (!is_array($params) || !$surveyTypeId || !$activityId) {
return FALSE;
}
static $surveyFields;
if (!is_array($surveyFields)) {
$surveyFields = CRM_Core_BAO_CustomField::getFields('Activity',
FALSE,
FALSE,
$surveyTypeId,
NULL,
FALSE,
TRUE
);
}
static $statusId;
if (!$statusId) {
$statusId = array_search('Completed', CRM_Core_PseudoConstant::activityStatus('name'));
}
//format custom fields.
$customParams = CRM_Core_BAO_CustomField::postProcess($params,
$activityId,
'Activity'
);
CRM_Core_BAO_CustomValueTable::store($customParams, 'civicrm_activity', $activityId);
//process contact data.
$contactParams = $fields = array();
$contactFieldTypes = array_merge(array('Contact'), CRM_Contact_BAO_ContactType::basicTypes());
$responseFields = CRM_Campaign_BAO_Survey::getSurveyResponseFields($params['survey_id']);
if (!empty($responseFields)) {
foreach ($params as $key => $value) {
if (array_key_exists($key, $responseFields)) {
if (in_array($responseFields[$key]['field_type'], $contactFieldTypes)) {
$fields[$key] = $responseFields[$key];
$contactParams[$key] = $value;
if (isset($params["{$key}_id"])) {
$contactParams["{$key}_id"] = $params["{$key}_id"];
}
}
}
}
}
$contactId = CRM_Utils_Array::value('voter_id', $params);
if ($contactId && !empty($contactParams)) {
CRM_Contact_BAO_Contact::createProfileContact($contactParams, $fields, $contactId);
}
//update activity record.
$activity = new CRM_Activity_DAO_Activity();
$activity->id = $activityId;
$activity->selectAdd();
$activity->selectAdd('activity_date_time, status_id, result, subject');
$activity->find(TRUE);
$activity->activity_date_time = date('YmdHis');
$activity->status_id = $statusId;
if (!empty($params['activity_date_time'])) {
$activity->activity_date_time = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
}
$subject = '';
$surveyTitle = CRM_Utils_Array::value('surveyTitle', $params);
if ($surveyTitle) {
$subject = $surveyTitle . ' - ';
}
$subject .= ts('Respondent Interview');
$activity->subject = $subject;
$activityParams = array(
'details' => 'details',
'result' => 'result',
'engagement_level' => 'activity_engagement_level',
'subject' => 'activity_subject',
'status_id' => 'activity_status_id',
'source_contact_id' => 'source_contact',
'location' => 'activity_location',
'campaign_id' => 'activity_campaign_id',
'duration' => 'activity_duration',
);
foreach ($activityParams as $key => $field) {
if (!empty($params[$field])) {
$activity->$key = $params[$field];
}
}
$activity->save();
//really this should use Activity BAO& not be here but refactoring will have to be later
//actually the whole ajax call could be done as an api ajax call & post hook would be sorted
CRM_Utils_Hook::post('edit', 'Activity', $activity->id, $activity);
$activity->free();
return $activityId;
}
public function getVoterIds() {
if (!$this->_interviewerId) {
$session = CRM_Core_Session::singleton();
$this->_interviewerId = $session->get('userID');
}
if (!$this->_surveyId) {
// use default survey id
$dao = new CRM_Campaign_DAO_Survey();
$dao->is_active = 1;
$dao->is_default = 1;
$dao->find(TRUE);
$this->_surveyId = $dao->id;
}
$this->_contactIds = $this->get('contactIds');
if (!is_array($this->_contactIds)) {
//get the survey activities.
$activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
$statusIds = array();
if ($statusId = array_search('Scheduled', $activityStatus)) {
$statusIds[] = $statusId;
}
$surveyActivities = CRM_Campaign_BAO_Survey::getSurveyVoterInfo($this->_surveyId,
$this->_interviewerId,
$statusIds
);
$this->_contactIds = array();
foreach ($surveyActivities as $val) {
$this->_contactIds[$val['voter_id']] = $val['voter_id'];
}
$this->set('contactIds', $this->_contactIds);
}
}
public function filterVoterIds() {
//do the cleanup later on.
if (!is_array($this->_contactIds)) {
return;
}
$profileId = CRM_Campaign_BAO_Survey::getSurveyProfileId($this->_surveyId);
if ($profileId) {
$profileType = CRM_Core_BAO_UFField::getProfileType($profileId);
if (in_array($profileType, CRM_Contact_BAO_ContactType::basicTypes())) {
$voterIdCount = count($this->_contactIds);
//create temporary table to store voter ids.
$tempTableName = CRM_Core_DAO::createTempTableName('civicrm_survey_respondent');
CRM_Core_DAO::executeQuery("DROP TEMPORARY TABLE IF EXISTS {$tempTableName}");
$query = "
CREATE TEMPORARY TABLE {$tempTableName} (
id int unsigned NOT NULL AUTO_INCREMENT,
survey_contact_id int unsigned NOT NULL,
PRIMARY KEY ( id )
);
";
CRM_Core_DAO::executeQuery($query);
$batch = 100;
$insertedCount = 0;
do {
$processIds = $this->_contactIds;
$insertIds = array_splice($processIds, $insertedCount, $batch);
if (!empty($insertIds)) {
$insertSQL = "INSERT IGNORE INTO {$tempTableName}( survey_contact_id )
VALUES (" . implode('),(', $insertIds) . ');';
CRM_Core_DAO::executeQuery($insertSQL);
}
$insertedCount += $batch;
} while ($insertedCount < $voterIdCount);
$query = "
SELECT contact.id as id
FROM civicrm_contact contact
INNER JOIN {$tempTableName} ON ( {$tempTableName}.survey_contact_id = contact.id )
WHERE contact.contact_type != %1";
$removeContact = CRM_Core_DAO::executeQuery($query,
array(1 => array($profileType, 'String'))
);
while ($removeContact->fetch()) {
unset($this->_contactIds[$removeContact->id]);
}
}
}
}
}

View file

@ -0,0 +1,106 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to print voter records
*/
class CRM_Campaign_Form_Task_Print extends CRM_Campaign_Form_Task {
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
parent::preprocess();
// set print view, so that print templates are called
$this->controller->setPrint(1);
// get the formatted params
$queryParams = $this->get('queryParams');
$sortID = NULL;
if ($this->get(CRM_Utils_Sort::SORT_ID)) {
$sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
$this->get(CRM_Utils_Sort::SORT_DIRECTION)
);
}
$selector = new CRM_Campaign_Selector_Search($queryParams,
$this->_action,
$this->_componentClause
);
$controller = new CRM_Core_Selector_Controller($selector,
NULL,
$sortID,
CRM_Core_Action::VIEW,
$this,
CRM_Core_Selector_Controller::SCREEN
);
$controller->setEmbedded(TRUE);
$controller->run();
}
/**
* Build the form object.
*
* It consists of
* - displaying the QILL (query in local language)
* - displaying elements for saving the search
*/
public function buildQuickForm() {
//
// just need to add a javacript to popup the window for printing
//
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Print Respondents'),
'js' => array('onclick' => 'window.print()'),
'isDefault' => TRUE,
),
array(
'type' => 'back',
'name' => ts('Done'),
),
)
);
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
// redirect to the main search page after printing is over
}
}

View file

@ -0,0 +1,174 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to add contacts for voter reservation.
*/
class CRM_Campaign_Form_Task_Release extends CRM_Campaign_Form_Task {
/**
* Survet id
*
* @var int
*/
protected $_surveyId;
/**
* Number of voters
*
* @var int
*/
protected $_interviewerId;
/**
* Survey details
*
* @var object
*/
protected $_surveyDetails;
protected $_surveyActivities;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
$this->_interviewToRelease = $this->get('interviewToRelease');
if ($this->_interviewToRelease) {
//user came from interview form.
foreach (array(
'surveyId',
'contactIds',
'interviewerId',
) as $fld) {
$this->{"_$fld"} = $this->get($fld);
}
if (!empty($this->_contactIds)) {
$this->assign('totalSelectedContacts', count($this->_contactIds));
}
}
else {
parent::preProcess();
//get the survey id from user submitted values.
$this->_surveyId = CRM_Utils_Array::value('campaign_survey_id', $this->get('formValues'));
$this->_interviewerId = CRM_Utils_Array::value('survey_interviewer_id', $this->get('formValues'));
}
if (!$this->_surveyId) {
CRM_Core_Error::statusBounce(ts("Please search with 'Survey', to apply this action."));
}
if (!$this->_interviewerId) {
CRM_Core_Error::statusBounce(ts('Missing Interviewer contact.'));
}
if (!is_array($this->_contactIds) || empty($this->_contactIds)) {
CRM_Core_Error::statusBounce(ts('Could not find respondents to release.'));
}
$surveyDetails = array();
$params = array('id' => $this->_surveyId);
$this->_surveyDetails = CRM_Campaign_BAO_Survey::retrieve($params, $surveyDetails);
$activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
$statusIds = array();
foreach (array(
'Scheduled',
) as $name) {
if ($statusId = array_search($name, $activityStatus)) {
$statusIds[] = $statusId;
}
}
//fetch the target survey activities.
$this->_surveyActivities = CRM_Campaign_BAO_Survey::voterActivityDetails($this->_surveyId,
$this->_contactIds,
$this->_interviewerId,
$statusIds
);
if (count($this->_surveyActivities) < 1) {
CRM_Core_Error::statusBounce(ts('We could not found respondent for this survey to release.'));
}
$this->assign('surveyTitle', $surveyDetails['title']);
//append breadcrumb to survey dashboard.
if (CRM_Campaign_BAO_Campaign::accessCampaign()) {
$url = CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=survey');
CRM_Utils_System::appendBreadCrumb(array(array('title' => ts('Survey(s)'), 'url' => $url)));
}
//set the title.
CRM_Utils_System::setTitle(ts('Release Respondents'));
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addDefaultButtons(ts('Release Respondents'), 'done');
}
public function postProcess() {
$deleteActivityIds = array();
foreach ($this->_contactIds as $cid) {
if (array_key_exists($cid, $this->_surveyActivities)) {
$deleteActivityIds[] = $this->_surveyActivities[$cid]['activity_id'];
}
}
//set survey activities as deleted = true.
if (!empty($deleteActivityIds)) {
$query = 'UPDATE civicrm_activity SET is_deleted = 1 WHERE id IN ( ' . implode(', ', $deleteActivityIds) . ' )';
CRM_Core_DAO::executeQuery($query);
if ($deleteActivityIds) {
$status = ts("Respondent has been released.", array(
'count' => count($deleteActivityIds),
'plural' => '%count respondents have been released.',
));
CRM_Core_Session::setStatus($status, ts('Released'), 'success');
}
if (count($this->_contactIds) > count($deleteActivityIds)) {
$status = ts('1 respondent did not release.',
array(
'count' => (count($this->_contactIds) - count($deleteActivityIds)),
'plural' => '%count respondents did not release.',
)
);
CRM_Core_Session::setStatus($status, ts('Notice'), 'alert');
}
}
}
}

View file

@ -0,0 +1,357 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to add contacts for voter reservation.
*/
class CRM_Campaign_Form_Task_Reserve extends CRM_Campaign_Form_Task {
/**
* @var int
* Survey id.
*/
protected $_surveyId;
/**
* Interviewer id
*
* @var int
*/
protected $_interviewerId;
/**
* Survey details
*
* @var object
*/
protected $_surveyDetails;
/**
* Number of voters
*
* @var int
*/
protected $_numVoters;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
parent::preProcess();
//get the survey id from user submitted values.
$this->_surveyId = $this->get('surveyId');
$this->_interviewerId = $this->get('interviewerId');
if (!$this->_surveyId) {
CRM_Core_Error::statusBounce(ts("Could not find Survey Id."));
}
if (!$this->_interviewerId) {
CRM_Core_Error::statusBounce(ts("Missing Interviewer contact."));
}
if (!is_array($this->_contactIds) || empty($this->_contactIds)) {
CRM_Core_Error::statusBounce(ts("Could not find contacts for reservation."));
}
$params = array('id' => $this->_surveyId);
CRM_Campaign_BAO_Survey::retrieve($params, $this->_surveyDetails);
//get the survey activities.
$activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
$statusIds = array();
foreach (array('Scheduled') as $name) {
if ($statusId = array_search($name, $activityStatus)) {
$statusIds[] = $statusId;
}
}
// these are the activities count that are linked to the current
// interviewer and current survey and not the list of ALL survey activities
$this->_numVoters = CRM_Campaign_BAO_Survey::getSurveyActivities($this->_surveyId,
$this->_interviewerId,
$statusIds,
NULL,
TRUE
);
//validate the selected survey.
$this->validateSurvey();
$this->assign('surveyTitle', $this->_surveyDetails['title']);
$this->assign('activityType', $this->_surveyDetails['activity_type_id']);
$this->assign('surveyId', $this->_surveyId);
//append breadcrumb to survey dashboard.
if (CRM_Campaign_BAO_Campaign::accessCampaign()) {
$url = CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=survey');
CRM_Utils_System::appendBreadCrumb(array(array('title' => ts('Survey(s)'), 'url' => $url)));
}
//set the title.
CRM_Utils_System::setTitle(ts('Reserve Respondents'));
}
public function validateSurvey() {
$errorMsg = NULL;
$maxVoters = CRM_Utils_Array::value('max_number_of_contacts', $this->_surveyDetails);
if ($maxVoters) {
if ($maxVoters <= $this->_numVoters) {
$errorMsg = ts('The maximum number of contacts is already reserved for this interviewer.');
}
elseif (count($this->_contactIds) > ($maxVoters - $this->_numVoters)) {
$errorMsg = ts('You can reserve a maximum of %count contact at a time for this survey.',
array(
'plural' => 'You can reserve a maximum of %count contacts at a time for this survey.',
'count' => $maxVoters - $this->_numVoters,
)
);
}
}
$defaultNum = CRM_Utils_Array::value('default_number_of_contacts', $this->_surveyDetails);
if (!$errorMsg && $defaultNum && (count($this->_contactIds) > $defaultNum)) {
$errorMsg = ts('You can reserve a maximum of %count contact at a time for this survey.',
array(
'plural' => 'You can reserve a maximum of %count contacts at a time for this survey.',
'count' => $defaultNum,
)
);
}
if ($errorMsg) {
CRM_Core_Error::statusBounce($errorMsg);
}
}
/**
* Build the form object.
*/
public function buildQuickForm() {
// allow to add contact to either new or existing group.
$this->addElement('text', 'ActivityType', ts('Activity Type'));
$this->addElement('text', 'newGroupName', ts('Name for new group'));
$this->addElement('text', 'newGroupDesc', ts('Description of new group'));
$groups = CRM_Core_PseudoConstant::nestedGroup();
$hasExistingGroups = FALSE;
if (is_array($groups) && !empty($groups)) {
$hasExistingGroups = TRUE;
$this->addElement('select', 'groups', ts('Add respondent(s) to existing group(s)'),
$groups, array('multiple' => "multiple", 'class' => 'crm-select2')
);
}
$this->assign('hasExistingGroups', $hasExistingGroups);
$buttons = array(
array(
'type' => 'done',
'name' => ts('Reserve'),
'subName' => 'reserve',
'isDefault' => TRUE,
),
);
if (CRM_Core_Permission::check('manage campaign') ||
CRM_Core_Permission::check('administer CiviCampaign') ||
CRM_Core_Permission::check('interview campaign contacts')
) {
$buttons[] = array(
'type' => 'next',
'name' => ts('Reserve and Interview'),
'subName' => 'reserveToInterview',
);
}
$buttons[] = array(
'type' => 'back',
'name' => ts('Cancel'),
);
$this->addButtons($buttons);
$this->addFormRule(array('CRM_Campaign_Form_Task_Reserve', 'formRule'), $this);
}
/**
* Global validation rules for the form.
*
* @param array $fields
* Posted values of the form.
*
* @param $files
* @param $self
*
* @return array
* list of errors to be posted back to the form
*/
public static function formRule($fields, $files, $self) {
$errors = array();
$invalidGroupName = FALSE;
if (!empty($fields['newGroupName'])) {
$title = trim($fields['newGroupName']);
$name = CRM_Utils_String::titleToVar($title);
$query = 'select count(*) from civicrm_group where name like %1 OR title like %2';
$grpCnt = CRM_Core_DAO::singleValueQuery($query, array(
1 => array($name, 'String'),
2 => array($title, 'String'),
));
if ($grpCnt) {
$invalidGroupName = TRUE;
$errors['newGroupName'] = ts('Group \'%1\' already exists.', array(1 => $fields['newGroupName']));
}
}
$self->assign('invalidGroupName', $invalidGroupName);
return empty($errors) ? TRUE : $errors;
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
//add reservation.
$countVoters = 0;
$maxVoters = CRM_Utils_Array::value('max_number_of_contacts', $this->_surveyDetails);
$activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
$statusHeld = array_search('Scheduled', $activityStatus);
$reservedVoterIds = array();
foreach ($this->_contactIds as $cid) {
$subject = $this->_surveyDetails['title'] . ' - ' . ts('Respondent Reservation');
$session = CRM_Core_Session::singleton();
$activityParams = array(
'source_contact_id' => $session->get('userID'),
'assignee_contact_id' => array($this->_interviewerId),
'target_contact_id' => array($cid),
'source_record_id' => $this->_surveyId,
'activity_type_id' => $this->_surveyDetails['activity_type_id'],
'subject' => $subject,
'activity_date_time' => date('YmdHis'),
'status_id' => $statusHeld,
'skipRecentView' => 1,
'campaign_id' => CRM_Utils_Array::value('campaign_id', $this->_surveyDetails),
);
$activity = CRM_Activity_BAO_Activity::create($activityParams);
if ($activity->id) {
$countVoters++;
$reservedVoterIds[$cid] = $cid;
}
if ($maxVoters && ($maxVoters <= ($this->_numVoters + $countVoters))) {
break;
}
}
//add reserved voters to groups.
$groupAdditions = $this->_addRespondentToGroup($reservedVoterIds);
// Success message
if ($countVoters > 0) {
$status = '<p>' . ts("%count contact has been reserved.", array('plural' => '%count contacts have been reserved.', 'count' => $countVoters)) . '</p>';
if ($groupAdditions) {
$status .= '<p>' . ts('They have been added to %1.',
array(1 => implode(' ' . ts('and') . ' ', $groupAdditions))
) . '</p>';
}
CRM_Core_Session::setStatus($status, ts('Reservation Added'), 'success');
}
// Error message
if (count($this->_contactIds) > $countVoters) {
CRM_Core_Session::setStatus(ts('Reservation did not add for %count contact.',
array(
'plural' => 'Reservation did not add for %count contacts.',
'count' => (count($this->_contactIds) - $countVoters),
)
), ts('Notice'));
}
//get ready to jump to voter interview form.
$buttonName = $this->controller->getButtonName();
if (!empty($reservedVoterIds) &&
$buttonName == '_qf_Reserve_next_reserveToInterview'
) {
$this->controller->set('surveyId', $this->_surveyId);
$this->controller->set('contactIds', $reservedVoterIds);
$this->controller->set('interviewerId', $this->_interviewerId);
$this->controller->set('reserveToInterview', TRUE);
}
}
/**
* @param $contactIds
*
* @return array
*/
private function _addRespondentToGroup($contactIds) {
$groupAdditions = array();
if (empty($contactIds)) {
return $groupAdditions;
}
$params = $this->controller->exportValues($this->_name);
$groups = CRM_Utils_Array::value('groups', $params, array());
$newGroupName = CRM_Utils_Array::value('newGroupName', $params);
$newGroupDesc = CRM_Utils_Array::value('newGroupDesc', $params);
$newGroupId = NULL;
//create new group.
if ($newGroupName) {
$grpParams = array(
'title' => $newGroupName,
'description' => $newGroupDesc,
'is_active' => TRUE,
);
$group = CRM_Contact_BAO_Group::create($grpParams);
$groups[] = $newGroupId = $group->id;
}
//add the respondents to groups.
if (is_array($groups)) {
$existingGroups = CRM_Core_PseudoConstant::group();
foreach ($groups as $groupId) {
$addCount = CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
$totalCount = CRM_Utils_Array::value(1, $addCount);
if ($groupId == $newGroupId) {
$name = $newGroupName;
$new = TRUE;
}
else {
$name = $existingGroups[$groupId];
$new = FALSE;
}
if ($totalCount) {
$url = CRM_Utils_System::url('civicrm/group/search',
'reset=1&force=1&context=smog&gid=' . $groupId
);
$groupAdditions[] = '<a href="' . $url . '">' . $name . '</a>';
}
}
}
return $groupAdditions;
}
}

View file

@ -0,0 +1,59 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Used for displaying results.
*/
class CRM_Campaign_Form_Task_Result extends CRM_Campaign_Form_Task {
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addButtons(array(
array(
'type' => 'done',
'name' => ts('Done'),
'isDefault' => TRUE,
),
)
);
}
}