Merge pull request #13585 from civicrm/5.11
[civicrm-core.git] / CRM / Campaign / Form / Task / Interview.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * This class provides the functionality to record voter's interview.
36 */
37 class CRM_Campaign_Form_Task_Interview extends CRM_Campaign_Form_Task {
38
39 /**
40 * The title of the group
41 *
42 * @var string
43 */
44 protected $_title;
45
46 /**
47 * Variable to store redirect path
48 */
49 private $_userContext;
50
51 private $_groupTree;
52
53 private $_surveyFields;
54
55 private $_surveyTypeId;
56
57 private $_interviewerId;
58
59 private $_surveyActivityIds;
60
61 private $_votingTab = FALSE;
62
63 private $_surveyValues;
64
65 private $_resultOptions;
66
67 private $_allowAjaxReleaseButton;
68
69 /**
70 * Build all the data structures needed to build the form.
71 */
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.
77 foreach (array(
78 'surveyId',
79 'contactIds',
80 'interviewerId',
81 ) as $fld) {
82 $this->{"_$fld"} = $this->get($fld);
83 }
84 //get the target voter ids.
85 if ($this->_votingTab) {
86 $this->getVoterIds();
87 }
88 }
89 else {
90 parent::preProcess();
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'));
94 }
95
96 if ($this->_surveyId) {
97 $params = array('id' => $this->_surveyId);
98 CRM_Campaign_BAO_Survey::retrieve($params, $this->_surveyDetails);
99 }
100
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);
106 }
107 elseif ($walkListActivityId == $this->_surveyDetails['activity_type_id']) {
108 $orderByParams
109 = array(
110 1 => array(
111 'column' => 'civicrm_address.street_name',
112 'order' => 'ASC',
113 ),
114 2 => array(
115 'column' => 'civicrm_address.street_number%2',
116 'order' => 'ASC',
117 ),
118 3 => array(
119 'column' => 'civicrm_address.street_number',
120 'order' => 'ASC',
121 ),
122 4 => array(
123 'column' => 'contact_a.sort_name',
124 'order' => 'ASC',
125 ),
126 );
127 }
128
129 $orderBy = array();
130 if (!empty($orderByParams)) {
131 foreach ($orderByParams as $key => $val) {
132 if (!empty($val['column'])) {
133 $orderBy[] = "{$val['column']} {$val['order']}";
134 }
135 }
136 if (!empty($orderBy)) {
137 $orderClause = "ORDER BY " . implode(', ', $orderBy);
138 }
139 }
140
141 $this->_contactIds = array_unique($this->_contactIds);
142 if (!empty($this->_contactIds) && $orderClause) {
143 $clause = 'contact_a.id IN ( ' . implode(',', $this->_contactIds) . ' ) ';
144 $sql = "
145 SELECT contact_a.id
146 FROM civicrm_contact contact_a
147 LEFT JOIN civicrm_address ON contact_a.id = civicrm_address.contact_id
148 WHERE {$clause}
149 {$orderClause}";
150
151 $this->_contactIds = array();
152 $dao = CRM_Core_DAO::executeQuery($sql);
153 while ($dao->fetch()) {
154 $this->_contactIds[] = $dao->id;
155 }
156 }
157
158 //get the contact read only fields to display.
159 $readOnlyFields = array_merge(array(
160 'contact_type' => '',
161 'sort_name' => ts('Name'),
162 ));
163
164 //get the read only field data.
165 $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
166 $returnProperties['contact_sub_type'] = TRUE;
167
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,
171 $this->_contactIds,
172 $this->_interviewerId
173 );
174 $scheduledStatusId = CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Scheduled');
175
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);
181 if ($activityId &&
182 $statusId &&
183 $scheduledStatusId == $statusId
184 ) {
185 $activityIds["activity_id_{$voterId}"] = $activityId;
186 }
187 else {
188 unset($this->_contactIds[$key]);
189 }
190 }
191
192 //retrieve the contact details.
193 $voterDetails = CRM_Campaign_BAO_Survey::voterDetails($this->_contactIds, $returnProperties);
194
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')
200 )
201 ) {
202 $this->_allowAjaxReleaseButton = TRUE;
203 }
204
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);
215
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);
223 }
224 $this->set('surveyValues', $this->_surveyValues);
225 }
226 $this->assign('surveyValues', $this->_surveyValues);
227
228 $result = CRM_Campaign_BAO_Survey::getReportID($this->_surveyId);
229 $this->assign("instanceId", $result);
230
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);
237 }
238 $this->set('resultOptions', $this->_resultOptions);
239 }
240
241 //validate the required ids.
242 $this->validateIds();
243
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)));
248 }
249
250 //set the title.
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)));
254 }
255
256 public function validateIds() {
257 $required = array(
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.'),
262 );
263
264 $errorMessages = array();
265 foreach ($required as $fld => $msg) {
266 if (empty($this->{"_$fld"})) {
267 if (!$this->_votingTab) {
268 CRM_Core_Error::statusBounce($msg);
269 break;
270 }
271 $errorMessages[] = $msg;
272 }
273 }
274
275 $this->assign('errorMessages', empty($errorMessages) ? FALSE : $errorMessages);
276 }
277
278 /**
279 * Build the form object.
280 */
281 public function buildQuickForm() {
282 $this->assign('surveyTypeId', $this->_surveyTypeId);
283
284 $options
285 = array(
286 '' => ' - none - ',
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',
291 );
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'),
297 ));
298 }
299
300 //pickup the uf fields.
301 $this->_surveyFields = CRM_Campaign_BAO_Survey::getSurveyResponseFields($this->_surveyId,
302 $this->_surveyTypeId
303 );
304
305 foreach ($this->_contactIds as $contactId) {
306 //build the profile fields.
307 foreach ($this->_surveyFields as $name => $field) {
308 if ($field) {
309 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $contactId);
310 }
311 }
312
313 //build the result field.
314 if (!empty($this->_resultOptions)) {
315 $this->add('select', "field[$contactId][result]", ts('Result'),
316 array(
317 '' => ts('- select -'),
318 ) +
319 array_combine($this->_resultOptions, $this->_resultOptions)
320 );
321 }
322
323 $this->add('text', "field[{$contactId}][note]", ts('Note'));
324
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")
330 );
331 }
332 }
333 $this->assign('surveyFields', empty($this->_surveyFields) ? FALSE : $this->_surveyFields);
334
335 //no need to get qf buttons.
336 if ($this->_votingTab) {
337 return;
338 }
339
340 $buttons = array(
341 array(
342 'type' => 'cancel',
343 'name' => ts('Done'),
344 'subName' => 'interview',
345 'isDefault' => TRUE,
346 ),
347 );
348
349 $buttons[] = array(
350 'type' => 'submit',
351 'name' => ts('Order By >>'),
352 'subName' => 'orderBy',
353 );
354
355 $manageCampaign = CRM_Core_Permission::check('manage campaign');
356 $adminCampaign = CRM_Core_Permission::check('administer CiviCampaign');
357 if ($manageCampaign ||
358 $adminCampaign ||
359 CRM_Core_Permission::check('release campaign contacts')
360 ) {
361 $buttons[] = array(
362 'type' => 'next',
363 'name' => ts('Release Respondents >>'),
364 'subName' => 'interviewToRelease',
365 );
366 }
367 if ($manageCampaign ||
368 $adminCampaign ||
369 CRM_Core_Permission::check('reserve campaign contacts')
370 ) {
371 $buttons[] = array(
372 'type' => 'done',
373 'name' => ts('Reserve More Respondents >>'),
374 'subName' => 'interviewToReserve',
375 );
376 }
377
378 $this->addButtons($buttons);
379 }
380
381 /**
382 * Set default values for the form.
383 */
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;
392 }
393 }
394 if (!empty($contactFields)) {
395 foreach ($this->_contactIds as $contactId) {
396 CRM_Core_BAO_UFGroup::setProfileDefaults($contactId, $contactFields, $defaults, FALSE);
397 }
398 }
399
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']
403 = array(
404 1 => array(
405 'column' => 'civicrm_address.street_name',
406 'order' => 'ASC',
407 ),
408 2 => array(
409 'column' => 'civicrm_address.street_number%2',
410 'order' => 'ASC',
411 ),
412 3 => array(
413 'column' => 'civicrm_address.street_number',
414 'order' => 'ASC',
415 ),
416 4 => array(
417 'column' => 'contact_a.sort_name',
418 'order' => 'ASC',
419 ),
420 );
421 }
422 else {
423 $defaults['order_bys']
424 = array(
425 1 => array(
426 'column' => 'contact_a.sort_name',
427 'order' => 'ASC',
428 ),
429 );
430 }
431 return $defaults;
432 }
433
434 /**
435 * Process the form after the input has been submitted and validated.
436 */
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'));
442 }
443 elseif ($buttonName == '_qf_Interview_next_interviewToRelease') {
444 //get ready to jump to release form.
445 foreach (array(
446 'surveyId',
447 'contactIds',
448 'interviewerId',
449 ) as $fld) {
450 $this->controller->set($fld, $this->{"_$fld"});
451 }
452 $this->controller->set('interviewToRelease', TRUE);
453 }
454
455 // vote is done through ajax
456 }
457
458 /**
459 * @param array $params
460 *
461 * @return mixed
462 */
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) {
467 return FALSE;
468 }
469
470 static $surveyFields;
471 if (!is_array($surveyFields)) {
472 $surveyFields = CRM_Core_BAO_CustomField::getFields('Activity',
473 FALSE,
474 FALSE,
475 $surveyTypeId,
476 NULL,
477 FALSE,
478 TRUE
479 );
480 }
481
482 static $statusId;
483 if (!$statusId) {
484 $statusId = CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed');
485 }
486
487 //format custom fields.
488 $customParams = CRM_Core_BAO_CustomField::postProcess($params,
489 $activityId,
490 'Activity'
491 );
492
493 CRM_Core_BAO_CustomValueTable::store($customParams, 'civicrm_activity', $activityId);
494
495 //process contact data.
496 $contactParams = $fields = array();
497
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"];
508 }
509 }
510 }
511 }
512 }
513
514 $contactId = CRM_Utils_Array::value('voter_id', $params);
515 if ($contactId && !empty($contactParams)) {
516 CRM_Contact_BAO_Contact::createProfileContact($contactParams, $fields, $contactId);
517 }
518
519 //update activity record.
520 $activity = new CRM_Activity_DAO_Activity();
521 $activity->id = $activityId;
522
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;
528
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']);
531 }
532
533 $subject = '';
534 $surveyTitle = CRM_Utils_Array::value('surveyTitle', $params);
535 if ($surveyTitle) {
536 $subject = $surveyTitle . ' - ';
537 }
538 $subject .= ts('Respondent Interview');
539
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',
551 );
552 foreach ($activityParams as $key => $field) {
553 if (!empty($params[$field])) {
554 $activity->$key = $params[$field];
555 }
556 }
557
558 $activity->save();
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);
562
563 return $activityId;
564 }
565
566 public function getVoterIds() {
567 if (!$this->_interviewerId) {
568 $session = CRM_Core_Session::singleton();
569 $this->_interviewerId = $session->get('userID');
570 }
571 if (!$this->_surveyId) {
572 // use default survey id
573 $dao = new CRM_Campaign_DAO_Survey();
574 $dao->is_active = 1;
575 $dao->is_default = 1;
576 $dao->find(TRUE);
577 $this->_surveyId = $dao->id;
578 }
579
580 $this->_contactIds = $this->get('contactIds');
581 if (!is_array($this->_contactIds)) {
582 //get the survey activities.
583 $statusIds[] = CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Scheduled');
584 $surveyActivities = CRM_Campaign_BAO_Survey::getSurveyVoterInfo($this->_surveyId,
585 $this->_interviewerId,
586 $statusIds
587 );
588 $this->_contactIds = array();
589 foreach ($surveyActivities as $val) {
590 $this->_contactIds[$val['voter_id']] = $val['voter_id'];
591 }
592 $this->set('contactIds', $this->_contactIds);
593 }
594 }
595
596 public function filterVoterIds() {
597 //do the cleanup later on.
598 if (!is_array($this->_contactIds)) {
599 return;
600 }
601
602 $profileId = CRM_Campaign_BAO_Survey::getSurveyProfileId($this->_surveyId);
603 if ($profileId) {
604 $profileType = CRM_Core_BAO_UFField::getProfileType($profileId);
605 if (in_array($profileType, CRM_Contact_BAO_ContactType::basicTypes())) {
606 $voterIdCount = count($this->_contactIds);
607
608 //create temporary table to store voter ids.
609 $tempTableName = CRM_Core_DAO::createTempTableName('civicrm_survey_respondent');
610 CRM_Core_DAO::executeQuery("DROP TEMPORARY TABLE IF EXISTS {$tempTableName}");
611 $query = "
612 CREATE TEMPORARY TABLE {$tempTableName} (
613 id int unsigned NOT NULL AUTO_INCREMENT,
614 survey_contact_id int unsigned NOT NULL,
615 PRIMARY KEY ( id )
616 );
617 ";
618 CRM_Core_DAO::executeQuery($query);
619 $batch = 100;
620 $insertedCount = 0;
621 do {
622 $processIds = $this->_contactIds;
623 $insertIds = array_splice($processIds, $insertedCount, $batch);
624 if (!empty($insertIds)) {
625 $insertSQL = "INSERT IGNORE INTO {$tempTableName}( survey_contact_id )
626 VALUES (" . implode('),(', $insertIds) . ');';
627 CRM_Core_DAO::executeQuery($insertSQL);
628 }
629 $insertedCount += $batch;
630 } while ($insertedCount < $voterIdCount);
631
632 $query = "
633 SELECT contact.id as id
634 FROM civicrm_contact contact
635 INNER JOIN {$tempTableName} ON ( {$tempTableName}.survey_contact_id = contact.id )
636 WHERE contact.contact_type != %1";
637 $removeContact = CRM_Core_DAO::executeQuery($query,
638 array(1 => array($profileType, 'String'))
639 );
640 while ($removeContact->fetch()) {
641 unset($this->_contactIds[$removeContact->id]);
642 }
643 }
644 }
645 }
646
647 }