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
50 private $_userContext;
54 private $_surveyFields;
56 private $_surveyTypeId;
58 private $_interviewerId;
60 private $_surveyActivityIds;
62 private $_votingTab = FALSE;
64 private $_surveyValues;
66 private $_resultOptions;
68 private $_allowAjaxReleaseButton;
71 * Build all the data structures needed to build the form.
73 public function preProcess() {
74 $this->_votingTab
= $this->get('votingTab');
75 $this->_reserveToInterview
= $this->get('reserveToInterview');
76 if ($this->_reserveToInterview ||
$this->_votingTab
) {
77 //user came from voting tab / reserve form.
83 $this->{"_$fld"} = $this->get($fld);
85 //get the target voter ids.
86 if ($this->_votingTab
) {
92 //get the survey id from user submitted values.
93 $this->_surveyId
= CRM_Utils_Array
::value('campaign_survey_id', $this->get('formValues'));
94 $this->_interviewerId
= CRM_Utils_Array
::value('survey_interviewer_id', $this->get('formValues'));
97 if ($this->_surveyId
) {
98 $params = ['id' => $this->_surveyId
];
99 CRM_Campaign_BAO_Survey
::retrieve($params, $this->_surveyDetails
);
102 $orderClause = FALSE;
103 $buttonName = $this->controller
->getButtonName();
104 $walkListActivityId = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'WalkList');
105 if ($buttonName == '_qf_Interview_submit_orderBy' && !empty($_POST['order_bys'])) {
106 $orderByParams = CRM_Utils_Array
::value('order_bys', $_POST);
108 elseif ($walkListActivityId == $this->_surveyDetails
['activity_type_id']) {
112 'column' => 'civicrm_address.street_name',
116 'column' => 'civicrm_address.street_number%2',
120 'column' => 'civicrm_address.street_number',
124 'column' => 'contact_a.sort_name',
131 if (!empty($orderByParams)) {
132 foreach ($orderByParams as $key => $val) {
133 if (!empty($val['column'])) {
134 $orderBy[] = "{$val['column']} {$val['order']}";
137 if (!empty($orderBy)) {
138 $orderClause = "ORDER BY " . implode(', ', $orderBy);
142 $this->_contactIds
= array_unique($this->_contactIds
);
143 if (!empty($this->_contactIds
) && $orderClause) {
144 $clause = 'contact_a.id IN ( ' . implode(',', $this->_contactIds
) . ' ) ';
147 FROM civicrm_contact contact_a
148 LEFT JOIN civicrm_address ON contact_a.id = civicrm_address.contact_id
152 $this->_contactIds
= [];
153 $dao = CRM_Core_DAO
::executeQuery($sql);
154 while ($dao->fetch()) {
155 $this->_contactIds
[] = $dao->id
;
159 //get the contact read only fields to display.
160 $readOnlyFields = array_merge([
161 'contact_type' => '',
162 'sort_name' => ts('Name'),
165 //get the read only field data.
166 $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
167 $returnProperties['contact_sub_type'] = TRUE;
169 //validate all voters for required activity.
170 //get the survey activities for given voters.
171 $this->_surveyActivityIds
= CRM_Campaign_BAO_Survey
::voterActivityDetails($this->_surveyId
,
173 $this->_interviewerId
175 $scheduledStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Scheduled');
178 foreach ($this->_contactIds
as $key => $voterId) {
179 $actVals = CRM_Utils_Array
::value($voterId, $this->_surveyActivityIds
);
180 $statusId = CRM_Utils_Array
::value('status_id', $actVals);
181 $activityId = CRM_Utils_Array
::value('activity_id', $actVals);
184 $scheduledStatusId == $statusId
186 $activityIds["activity_id_{$voterId}"] = $activityId;
189 unset($this->_contactIds
[$key]);
193 //retrieve the contact details.
194 $voterDetails = CRM_Campaign_BAO_Survey
::voterDetails($this->_contactIds
, $returnProperties);
196 $this->_allowAjaxReleaseButton
= FALSE;
197 if ($this->_votingTab
&&
198 (CRM_Core_Permission
::check('manage campaign') ||
199 CRM_Core_Permission
::check('administer CiviCampaign') ||
200 CRM_Core_Permission
::check('release campaign contacts')
203 $this->_allowAjaxReleaseButton
= TRUE;
206 //validate voter ids across profile.
207 $this->filterVoterIds();
208 $this->assign('votingTab', $this->_votingTab
);
209 $this->assign('componentIds', $this->_contactIds
);
210 $this->assign('componentIdsJson', json_encode($this->_contactIds
));
211 $this->assign('voterDetails', $voterDetails);
212 $this->assign('readOnlyFields', $readOnlyFields);
213 $this->assign('interviewerId', $this->_interviewerId
);
214 $this->assign('surveyActivityIds', json_encode($activityIds));
215 $this->assign('allowAjaxReleaseButton', $this->_allowAjaxReleaseButton
);
217 //get the survey values.
218 $this->_surveyValues
= $this->get('surveyValues');
219 if (!is_array($this->_surveyValues
)) {
220 $this->_surveyValues
= [];
221 if ($this->_surveyId
) {
222 $surveyParams = ['id' => $this->_surveyId
];
223 CRM_Campaign_BAO_Survey
::retrieve($surveyParams, $this->_surveyValues
);
225 $this->set('surveyValues', $this->_surveyValues
);
227 $this->assign('surveyValues', $this->_surveyValues
);
229 $result = CRM_Campaign_BAO_Survey
::getReportID($this->_surveyId
);
230 $this->assign("instanceId", $result);
232 //get the survey result options.
233 $this->_resultOptions
= $this->get('resultOptions');
234 if (!is_array($this->_resultOptions
)) {
235 $this->_resultOptions
= [];
236 if ($resultOptionId = CRM_Utils_Array
::value('result_id', $this->_surveyValues
)) {
237 $this->_resultOptions
= CRM_Core_OptionGroup
::valuesByID($resultOptionId);
239 $this->set('resultOptions', $this->_resultOptions
);
242 //validate the required ids.
243 $this->validateIds();
245 //append breadcrumb to survey dashboard.
246 if (CRM_Campaign_BAO_Campaign
::accessCampaign()) {
247 $url = CRM_Utils_System
::url('civicrm/campaign', 'reset=1&subPage=survey');
248 CRM_Utils_System
::appendBreadCrumb([['title' => ts('Survey(s)'), 'url' => $url]]);
252 $this->_surveyTypeId
= CRM_Utils_Array
::value('activity_type_id', $this->_surveyValues
);
253 $surveyTypeLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $this->_surveyTypeId
);
254 CRM_Utils_System
::setTitle(ts('Record %1 Responses', [1 => $surveyTypeLabel]));
257 public function validateIds() {
259 'surveyId' => ts('Could not find Survey.'),
260 'interviewerId' => ts('Could not find Interviewer.'),
261 'contactIds' => ts('No respondents are currently reserved for you to interview.'),
262 'resultOptions' => ts('Oops. It looks like there is no response option configured.'),
266 foreach ($required as $fld => $msg) {
267 if (empty($this->{"_$fld"})) {
268 if (!$this->_votingTab
) {
269 CRM_Core_Error
::statusBounce($msg);
272 $errorMessages[] = $msg;
276 $this->assign('errorMessages', empty($errorMessages) ?
FALSE : $errorMessages);
280 * Build the form object.
282 public function buildQuickForm() {
283 $this->assign('surveyTypeId', $this->_surveyTypeId
);
288 'civicrm_address.street_name' => 'Street Name',
289 'civicrm_address.street_number%2' => 'Odd / Even Street Number',
290 'civicrm_address.street_number' => 'Street Number',
291 'contact_a.sort_name' => 'Respondent Name',
293 for ($i = 1; $i < count($options); $i++
) {
294 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
295 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), [
296 'ASC' => ts('Ascending'),
297 'DESC' => ts('Descending'),
301 //pickup the uf fields.
302 $this->_surveyFields
= CRM_Campaign_BAO_Survey
::getSurveyResponseFields($this->_surveyId
,
306 foreach ($this->_contactIds
as $contactId) {
307 //build the profile fields.
308 foreach ($this->_surveyFields
as $name => $field) {
310 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, NULL, $contactId);
314 //build the result field.
315 if (!empty($this->_resultOptions
)) {
316 $this->add('select', "field[$contactId][result]", ts('Result'),
318 '' => ts('- select -'),
320 array_combine($this->_resultOptions
, $this->_resultOptions
)
324 $this->add('text', "field[{$contactId}][note]", ts('Note'));
326 //need to keep control for release/reserve.
327 if ($this->_allowAjaxReleaseButton
) {
328 $this->addElement('hidden',
329 "field[{$contactId}][is_release_or_reserve]", 0,
330 ['id' => "field_{$contactId}_is_release_or_reserve"]
334 $this->assign('surveyFields', empty($this->_surveyFields
) ?
FALSE : $this->_surveyFields
);
336 //no need to get qf buttons.
337 if ($this->_votingTab
) {
344 'name' => ts('Done'),
345 'subName' => 'interview',
352 'name' => ts('Order By >>'),
353 'subName' => 'orderBy',
356 $manageCampaign = CRM_Core_Permission
::check('manage campaign');
357 $adminCampaign = CRM_Core_Permission
::check('administer CiviCampaign');
358 if ($manageCampaign ||
360 CRM_Core_Permission
::check('release campaign contacts')
364 'name' => ts('Release Respondents >>'),
365 'subName' => 'interviewToRelease',
368 if ($manageCampaign ||
370 CRM_Core_Permission
::check('reserve campaign contacts')
374 'name' => ts('Reserve More Respondents >>'),
375 'subName' => 'interviewToReserve',
379 $this->addButtons($buttons);
383 * Set default values for the form.
385 public function setDefaultValues() {
386 //load default data for only contact fields.
387 $contactFields = $defaults = [];
388 foreach ($this->_surveyFields
as $name => $field) {
389 $acceptable_types = CRM_Contact_BAO_ContactType
::basicTypes();
390 $acceptable_types[] = 'Contact';
391 if (isset($field['field_type']) && (in_array($field['field_type'], $acceptable_types))) {
392 $contactFields[$name] = $field;
395 if (!empty($contactFields)) {
396 foreach ($this->_contactIds
as $contactId) {
397 CRM_Core_BAO_UFGroup
::setProfileDefaults($contactId, $contactFields, $defaults, FALSE);
401 $walkListActivityId = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'WalkList');
402 if ($walkListActivityId == $this->_surveyDetails
['activity_type_id']) {
403 $defaults['order_bys']
406 'column' => 'civicrm_address.street_name',
410 'column' => 'civicrm_address.street_number%2',
414 'column' => 'civicrm_address.street_number',
418 'column' => 'contact_a.sort_name',
424 $defaults['order_bys']
427 'column' => 'contact_a.sort_name',
436 * Process the form after the input has been submitted and validated.
438 public function postProcess() {
439 $buttonName = $this->controller
->getButtonName();
440 if ($buttonName == '_qf_Interview_done_interviewToReserve') {
441 //hey its time to stop cycle.
442 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/survey/search', 'reset=1&op=reserve'));
444 elseif ($buttonName == '_qf_Interview_next_interviewToRelease') {
445 //get ready to jump to release form.
451 $this->controller
->set($fld, $this->{"_$fld"});
453 $this->controller
->set('interviewToRelease', TRUE);
456 // vote is done through ajax
460 * @param array $params
464 public static function registerInterview($params) {
465 $activityId = CRM_Utils_Array
::value('activity_id', $params);
466 $surveyTypeId = CRM_Utils_Array
::value('activity_type_id', $params);
467 if (!is_array($params) ||
!$surveyTypeId ||
!$activityId) {
471 static $surveyFields;
472 if (!is_array($surveyFields)) {
473 $surveyFields = CRM_Core_BAO_CustomField
::getFields('Activity',
485 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed');
488 //format custom fields.
489 $customParams = CRM_Core_BAO_CustomField
::postProcess($params,
494 CRM_Core_BAO_CustomValueTable
::store($customParams, 'civicrm_activity', $activityId);
496 //process contact data.
497 $contactParams = $fields = [];
499 $contactFieldTypes = array_merge(['Contact'], CRM_Contact_BAO_ContactType
::basicTypes());
500 $responseFields = CRM_Campaign_BAO_Survey
::getSurveyResponseFields($params['survey_id']);
501 if (!empty($responseFields)) {
502 foreach ($params as $key => $value) {
503 if (array_key_exists($key, $responseFields)) {
504 if (in_array($responseFields[$key]['field_type'], $contactFieldTypes)) {
505 $fields[$key] = $responseFields[$key];
506 $contactParams[$key] = $value;
507 if (isset($params["{$key}_id"])) {
508 $contactParams["{$key}_id"] = $params["{$key}_id"];
515 $contactId = CRM_Utils_Array
::value('voter_id', $params);
516 if ($contactId && !empty($contactParams)) {
517 CRM_Contact_BAO_Contact
::createProfileContact($contactParams, $fields, $contactId);
520 //update activity record.
521 $activity = new CRM_Activity_DAO_Activity();
522 $activity->id
= $activityId;
524 $activity->selectAdd();
525 $activity->selectAdd('activity_date_time, status_id, result, subject');
526 $activity->find(TRUE);
527 $activity->activity_date_time
= date('YmdHis');
528 $activity->status_id
= $statusId;
530 if (!empty($params['activity_date_time'])) {
531 $activity->activity_date_time
= CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
535 $surveyTitle = CRM_Utils_Array
::value('surveyTitle', $params);
537 $subject = $surveyTitle . ' - ';
539 $subject .= ts('Respondent Interview');
541 $activity->subject
= $subject;
543 'details' => 'details',
544 'result' => 'result',
545 'engagement_level' => 'activity_engagement_level',
546 'subject' => 'activity_subject',
547 'status_id' => 'activity_status_id',
548 'source_contact_id' => 'source_contact',
549 'location' => 'activity_location',
550 'campaign_id' => 'activity_campaign_id',
551 'duration' => 'activity_duration',
553 foreach ($activityParams as $key => $field) {
554 if (!empty($params[$field])) {
555 $activity->$key = $params[$field];
560 //really this should use Activity BAO& not be here but refactoring will have to be later
561 //actually the whole ajax call could be done as an api ajax call & post hook would be sorted
562 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
= [];
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 [1 => [$profileType, 'String']]
641 while ($removeContact->fetch()) {
642 unset($this->_contactIds
[$removeContact->id
]);