3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * This class provides the functionality to record voter's interview.
37 class CRM_Campaign_Form_Task_Interview
extends CRM_Campaign_Form_Task
{
40 * The title of the group
47 * Variable to store redirect path
49 private $_userContext;
53 private $_surveyFields;
55 private $_surveyTypeId;
57 private $_interviewerId;
59 private $_surveyActivityIds;
61 private $_votingTab = FALSE;
63 private $_surveyValues;
65 private $_resultOptions;
67 private $_allowAjaxReleaseButton;
70 * Build all the data structures needed to build the form.
72 public function preProcess() {
73 $this->_votingTab
= $this->get('votingTab');
74 $this->_reserveToInterview
= $this->get('reserveToInterview');
75 if ($this->_reserveToInterview ||
$this->_votingTab
) {
76 //user came from voting tab / reserve form.
82 $this->{"_$fld"} = $this->get($fld);
84 //get the target voter ids.
85 if ($this->_votingTab
) {
91 //get the survey id from user submitted values.
92 $this->_surveyId
= CRM_Utils_Array
::value('campaign_survey_id', $this->get('formValues'));
93 $this->_interviewerId
= CRM_Utils_Array
::value('survey_interviewer_id', $this->get('formValues'));
96 if ($this->_surveyId
) {
97 $params = array('id' => $this->_surveyId
);
98 CRM_Campaign_BAO_Survey
::retrieve($params, $this->_surveyDetails
);
101 $orderClause = FALSE;
102 $buttonName = $this->controller
->getButtonName();
103 $walkListActivityId = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'WalkList');
104 if ($buttonName == '_qf_Interview_submit_orderBy' && !empty($_POST['order_bys'])) {
105 $orderByParams = CRM_Utils_Array
::value('order_bys', $_POST);
107 elseif ($walkListActivityId == $this->_surveyDetails
['activity_type_id']) {
111 'column' => 'civicrm_address.street_name',
115 'column' => 'civicrm_address.street_number%2',
119 'column' => 'civicrm_address.street_number',
123 'column' => 'contact_a.sort_name',
130 if (!empty($orderByParams)) {
131 foreach ($orderByParams as $key => $val) {
132 if (!empty($val['column'])) {
133 $orderBy[] = "{$val['column']} {$val['order']}";
136 if (!empty($orderBy)) {
137 $orderClause = "ORDER BY " . implode(', ', $orderBy);
141 $this->_contactIds
= array_unique($this->_contactIds
);
142 if (!empty($this->_contactIds
) && $orderClause) {
143 $clause = 'contact_a.id IN ( ' . implode(',', $this->_contactIds
) . ' ) ';
146 FROM civicrm_contact contact_a
147 LEFT JOIN civicrm_address ON contact_a.id = civicrm_address.contact_id
151 $this->_contactIds
= array();
152 $dao = CRM_Core_DAO
::executeQuery($sql);
153 while ($dao->fetch()) {
154 $this->_contactIds
[] = $dao->id
;
158 //get the contact read only fields to display.
159 $readOnlyFields = array_merge(array(
160 'contact_type' => '',
161 'sort_name' => ts('Name'),
164 //get the read only field data.
165 $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
166 $returnProperties['contact_sub_type'] = TRUE;
168 //validate all voters for required activity.
169 //get the survey activities for given voters.
170 $this->_surveyActivityIds
= CRM_Campaign_BAO_Survey
::voterActivityDetails($this->_surveyId
,
172 $this->_interviewerId
174 $scheduledStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Scheduled');
176 $activityIds = array();
177 foreach ($this->_contactIds
as $key => $voterId) {
178 $actVals = CRM_Utils_Array
::value($voterId, $this->_surveyActivityIds
);
179 $statusId = CRM_Utils_Array
::value('status_id', $actVals);
180 $activityId = CRM_Utils_Array
::value('activity_id', $actVals);
183 $scheduledStatusId == $statusId
185 $activityIds["activity_id_{$voterId}"] = $activityId;
188 unset($this->_contactIds
[$key]);
192 //retrieve the contact details.
193 $voterDetails = CRM_Campaign_BAO_Survey
::voterDetails($this->_contactIds
, $returnProperties);
195 $this->_allowAjaxReleaseButton
= FALSE;
196 if ($this->_votingTab
&&
197 (CRM_Core_Permission
::check('manage campaign') ||
198 CRM_Core_Permission
::check('administer CiviCampaign') ||
199 CRM_Core_Permission
::check('release campaign contacts')
202 $this->_allowAjaxReleaseButton
= TRUE;
205 //validate voter ids across profile.
206 $this->filterVoterIds();
207 $this->assign('votingTab', $this->_votingTab
);
208 $this->assign('componentIds', $this->_contactIds
);
209 $this->assign('componentIdsJson', json_encode($this->_contactIds
));
210 $this->assign('voterDetails', $voterDetails);
211 $this->assign('readOnlyFields', $readOnlyFields);
212 $this->assign('interviewerId', $this->_interviewerId
);
213 $this->assign('surveyActivityIds', json_encode($activityIds));
214 $this->assign('allowAjaxReleaseButton', $this->_allowAjaxReleaseButton
);
216 //get the survey values.
217 $this->_surveyValues
= $this->get('surveyValues');
218 if (!is_array($this->_surveyValues
)) {
219 $this->_surveyValues
= array();
220 if ($this->_surveyId
) {
221 $surveyParams = array('id' => $this->_surveyId
);
222 CRM_Campaign_BAO_Survey
::retrieve($surveyParams, $this->_surveyValues
);
224 $this->set('surveyValues', $this->_surveyValues
);
226 $this->assign('surveyValues', $this->_surveyValues
);
228 $result = CRM_Campaign_BAO_Survey
::getReportID($this->_surveyId
);
229 $this->assign("instanceId", $result);
231 //get the survey result options.
232 $this->_resultOptions
= $this->get('resultOptions');
233 if (!is_array($this->_resultOptions
)) {
234 $this->_resultOptions
= array();
235 if ($resultOptionId = CRM_Utils_Array
::value('result_id', $this->_surveyValues
)) {
236 $this->_resultOptions
= CRM_Core_OptionGroup
::valuesByID($resultOptionId);
238 $this->set('resultOptions', $this->_resultOptions
);
241 //validate the required ids.
242 $this->validateIds();
244 //append breadcrumb to survey dashboard.
245 if (CRM_Campaign_BAO_Campaign
::accessCampaign()) {
246 $url = CRM_Utils_System
::url('civicrm/campaign', 'reset=1&subPage=survey');
247 CRM_Utils_System
::appendBreadCrumb(array(array('title' => ts('Survey(s)'), 'url' => $url)));
251 $this->_surveyTypeId
= CRM_Utils_Array
::value('activity_type_id', $this->_surveyValues
);
252 $surveyTypeLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $this->_surveyTypeId
);
253 CRM_Utils_System
::setTitle(ts('Record %1 Responses', array(1 => $surveyTypeLabel)));
256 public function validateIds() {
258 'surveyId' => ts('Could not find Survey.'),
259 'interviewerId' => ts('Could not find Interviewer.'),
260 'contactIds' => ts('No respondents are currently reserved for you to interview.'),
261 'resultOptions' => ts('Oops. It looks like there is no response option configured.'),
264 $errorMessages = array();
265 foreach ($required as $fld => $msg) {
266 if (empty($this->{"_$fld"})) {
267 if (!$this->_votingTab
) {
268 CRM_Core_Error
::statusBounce($msg);
271 $errorMessages[] = $msg;
275 $this->assign('errorMessages', empty($errorMessages) ?
FALSE : $errorMessages);
279 * Build the form object.
281 public function buildQuickForm() {
282 $this->assign('surveyTypeId', $this->_surveyTypeId
);
287 'civicrm_address.street_name' => 'Street Name',
288 'civicrm_address.street_number%2' => 'Odd / Even Street Number',
289 'civicrm_address.street_number' => 'Street Number',
290 'contact_a.sort_name' => 'Respondent Name',
292 for ($i = 1; $i < count($options); $i++
) {
293 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
294 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
295 'ASC' => ts('Ascending'),
296 'DESC' => ts('Descending'),
300 //pickup the uf fields.
301 $this->_surveyFields
= CRM_Campaign_BAO_Survey
::getSurveyResponseFields($this->_surveyId
,
305 foreach ($this->_contactIds
as $contactId) {
306 //build the profile fields.
307 foreach ($this->_surveyFields
as $name => $field) {
309 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, NULL, $contactId);
313 //build the result field.
314 if (!empty($this->_resultOptions
)) {
315 $this->add('select', "field[$contactId][result]", ts('Result'),
317 '' => ts('- select -'),
319 array_combine($this->_resultOptions
, $this->_resultOptions
)
323 $this->add('text', "field[{$contactId}][note]", ts('Note'));
325 //need to keep control for release/reserve.
326 if ($this->_allowAjaxReleaseButton
) {
327 $this->addElement('hidden',
328 "field[{$contactId}][is_release_or_reserve]", 0,
329 array('id' => "field_{$contactId}_is_release_or_reserve")
333 $this->assign('surveyFields', empty($this->_surveyFields
) ?
FALSE : $this->_surveyFields
);
335 //no need to get qf buttons.
336 if ($this->_votingTab
) {
343 'name' => ts('Done'),
344 'subName' => 'interview',
351 'name' => ts('Order By >>'),
352 'subName' => 'orderBy',
355 $manageCampaign = CRM_Core_Permission
::check('manage campaign');
356 $adminCampaign = CRM_Core_Permission
::check('administer CiviCampaign');
357 if ($manageCampaign ||
359 CRM_Core_Permission
::check('release campaign contacts')
363 'name' => ts('Release Respondents >>'),
364 'subName' => 'interviewToRelease',
367 if ($manageCampaign ||
369 CRM_Core_Permission
::check('reserve campaign contacts')
373 'name' => ts('Reserve More Respondents >>'),
374 'subName' => 'interviewToReserve',
378 $this->addButtons($buttons);
382 * Set default values for the form.
384 public function setDefaultValues() {
385 //load default data for only contact fields.
386 $contactFields = $defaults = array();
387 foreach ($this->_surveyFields
as $name => $field) {
388 $acceptable_types = CRM_Contact_BAO_ContactType
::basicTypes();
389 $acceptable_types[] = 'Contact';
390 if (isset($field['field_type']) && (in_array($field['field_type'], $acceptable_types))) {
391 $contactFields[$name] = $field;
394 if (!empty($contactFields)) {
395 foreach ($this->_contactIds
as $contactId) {
396 CRM_Core_BAO_UFGroup
::setProfileDefaults($contactId, $contactFields, $defaults, FALSE);
400 $walkListActivityId = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'WalkList');
401 if ($walkListActivityId == $this->_surveyDetails
['activity_type_id']) {
402 $defaults['order_bys']
405 'column' => 'civicrm_address.street_name',
409 'column' => 'civicrm_address.street_number%2',
413 'column' => 'civicrm_address.street_number',
417 'column' => 'contact_a.sort_name',
423 $defaults['order_bys']
426 'column' => 'contact_a.sort_name',
435 * Process the form after the input has been submitted and validated.
437 public function postProcess() {
438 $buttonName = $this->controller
->getButtonName();
439 if ($buttonName == '_qf_Interview_done_interviewToReserve') {
440 //hey its time to stop cycle.
441 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/survey/search', 'reset=1&op=reserve'));
443 elseif ($buttonName == '_qf_Interview_next_interviewToRelease') {
444 //get ready to jump to release form.
450 $this->controller
->set($fld, $this->{"_$fld"});
452 $this->controller
->set('interviewToRelease', TRUE);
455 // vote is done through ajax
459 * @param array $params
463 public static function registerInterview($params) {
464 $activityId = CRM_Utils_Array
::value('activity_id', $params);
465 $surveyTypeId = CRM_Utils_Array
::value('activity_type_id', $params);
466 if (!is_array($params) ||
!$surveyTypeId ||
!$activityId) {
470 static $surveyFields;
471 if (!is_array($surveyFields)) {
472 $surveyFields = CRM_Core_BAO_CustomField
::getFields('Activity',
484 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed');
487 //format custom fields.
488 $customParams = CRM_Core_BAO_CustomField
::postProcess($params,
493 CRM_Core_BAO_CustomValueTable
::store($customParams, 'civicrm_activity', $activityId);
495 //process contact data.
496 $contactParams = $fields = array();
498 $contactFieldTypes = array_merge(array('Contact'), CRM_Contact_BAO_ContactType
::basicTypes());
499 $responseFields = CRM_Campaign_BAO_Survey
::getSurveyResponseFields($params['survey_id']);
500 if (!empty($responseFields)) {
501 foreach ($params as $key => $value) {
502 if (array_key_exists($key, $responseFields)) {
503 if (in_array($responseFields[$key]['field_type'], $contactFieldTypes)) {
504 $fields[$key] = $responseFields[$key];
505 $contactParams[$key] = $value;
506 if (isset($params["{$key}_id"])) {
507 $contactParams["{$key}_id"] = $params["{$key}_id"];
514 $contactId = CRM_Utils_Array
::value('voter_id', $params);
515 if ($contactId && !empty($contactParams)) {
516 CRM_Contact_BAO_Contact
::createProfileContact($contactParams, $fields, $contactId);
519 //update activity record.
520 $activity = new CRM_Activity_DAO_Activity();
521 $activity->id
= $activityId;
523 $activity->selectAdd();
524 $activity->selectAdd('activity_date_time, status_id, result, subject');
525 $activity->find(TRUE);
526 $activity->activity_date_time
= date('YmdHis');
527 $activity->status_id
= $statusId;
529 if (!empty($params['activity_date_time'])) {
530 $activity->activity_date_time
= CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
534 $surveyTitle = CRM_Utils_Array
::value('surveyTitle', $params);
536 $subject = $surveyTitle . ' - ';
538 $subject .= ts('Respondent Interview');
540 $activity->subject
= $subject;
541 $activityParams = array(
542 'details' => 'details',
543 'result' => 'result',
544 'engagement_level' => 'activity_engagement_level',
545 'subject' => 'activity_subject',
546 'status_id' => 'activity_status_id',
547 'source_contact_id' => 'source_contact',
548 'location' => 'activity_location',
549 'campaign_id' => 'activity_campaign_id',
550 'duration' => 'activity_duration',
552 foreach ($activityParams as $key => $field) {
553 if (!empty($params[$field])) {
554 $activity->$key = $params[$field];
559 //really this should use Activity BAO& not be here but refactoring will have to be later
560 //actually the whole ajax call could be done as an api ajax call & post hook would be sorted
561 CRM_Utils_Hook
::post('edit', 'Activity', $activity->id
, $activity);
567 public function getVoterIds() {
568 if (!$this->_interviewerId
) {
569 $session = CRM_Core_Session
::singleton();
570 $this->_interviewerId
= $session->get('userID');
572 if (!$this->_surveyId
) {
573 // use default survey id
574 $dao = new CRM_Campaign_DAO_Survey();
576 $dao->is_default
= 1;
578 $this->_surveyId
= $dao->id
;
581 $this->_contactIds
= $this->get('contactIds');
582 if (!is_array($this->_contactIds
)) {
583 //get the survey activities.
584 $statusIds[] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Scheduled');
585 $surveyActivities = CRM_Campaign_BAO_Survey
::getSurveyVoterInfo($this->_surveyId
,
586 $this->_interviewerId
,
589 $this->_contactIds
= array();
590 foreach ($surveyActivities as $val) {
591 $this->_contactIds
[$val['voter_id']] = $val['voter_id'];
593 $this->set('contactIds', $this->_contactIds
);
597 public function filterVoterIds() {
598 //do the cleanup later on.
599 if (!is_array($this->_contactIds
)) {
603 $profileId = CRM_Campaign_BAO_Survey
::getSurveyProfileId($this->_surveyId
);
605 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
606 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
607 $voterIdCount = count($this->_contactIds
);
609 //create temporary table to store voter ids.
610 $tempTableName = CRM_Core_DAO
::createTempTableName('civicrm_survey_respondent');
611 CRM_Core_DAO
::executeQuery("DROP TEMPORARY TABLE IF EXISTS {$tempTableName}");
613 CREATE TEMPORARY TABLE {$tempTableName} (
614 id int unsigned NOT NULL AUTO_INCREMENT,
615 survey_contact_id int unsigned NOT NULL,
619 CRM_Core_DAO
::executeQuery($query);
623 $processIds = $this->_contactIds
;
624 $insertIds = array_splice($processIds, $insertedCount, $batch);
625 if (!empty($insertIds)) {
626 $insertSQL = "INSERT IGNORE INTO {$tempTableName}( survey_contact_id )
627 VALUES (" . implode('),(', $insertIds) . ');';
628 CRM_Core_DAO
::executeQuery($insertSQL);
630 $insertedCount +
= $batch;
631 } while ($insertedCount < $voterIdCount);
634 SELECT contact.id as id
635 FROM civicrm_contact contact
636 INNER JOIN {$tempTableName} ON ( {$tempTableName}.survey_contact_id = contact.id )
637 WHERE contact.contact_type != %1";
638 $removeContact = CRM_Core_DAO
::executeQuery($query,
639 array(1 => array($profileType, 'String'))
641 while ($removeContact->fetch()) {
642 unset($this->_contactIds
[$removeContact->id
]);