Merge pull request #2211 from colemanw/master
[civicrm-core.git] / CRM / Campaign / Form / Task / Interview.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
232624b1 4 | CiviCRM version 4.4 |
6a488035
TO
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
32 * $Id$
33 *
34 */
35
36/**
37 * This class provides the functionality to record voter's interview.
38 */
39class CRM_Campaign_Form_Task_Interview extends CRM_Campaign_Form_Task {
40
41 /**
42 * the title of the group
43 *
44 * @var string
45 */
46 protected $_title;
47
48 /**
49 * variable to store redirect path
50 *
51 */
52 private $_userContext;
53
54 private $_groupTree;
55
56 private $_surveyFields;
57
58 private $_surveyTypeId;
59
60 private $_interviewerId;
61
62 private $_surveyActivityIds;
63
64 private $_votingTab = FALSE;
65
66 private $_surveyValues;
67
68 private $_resultOptions;
69
70 private $_allowAjaxReleaseButton;
71
72 /**
73 * build all the data structures needed to build the form
74 *
75 * @return void
76 * @access public
77 */
78 function preProcess() {
79 $this->_votingTab = $this->get('votingTab');
80 $this->_reserveToInterview = $this->get('reserveToInterview');
81 if ($this->_reserveToInterview || $this->_votingTab) {
82 //user came from voting tab / reserve form.
83 foreach (array(
84 'surveyId', 'contactIds', 'interviewerId') as $fld) {
85 $this->{"_$fld"} = $this->get($fld);
86 }
87 //get the target voter ids.
88 if ($this->_votingTab) {
89 $this->getVoterIds();
90 }
91 }
92 else {
93 parent::preProcess();
94 //get the survey id from user submitted values.
95 $this->_surveyId = CRM_Utils_Array::value('campaign_survey_id', $this->get('formValues'));
96 $this->_interviewerId = CRM_Utils_Array::value('survey_interviewer_id', $this->get('formValues'));
97 }
98
99 if ( $this->_surveyId ) {
100 $params = array('id' => $this->_surveyId);
101 CRM_Campaign_BAO_Survey::retrieve($params, $this->_surveyDetails);
102 }
103
104 $orderClause = false;
105 $buttonName = $this->controller->getButtonName();
106 if ( $buttonName == '_qf_Interview_submit_orderBy' &&
107 CRM_Utils_Array::value('order_bys', $_POST) ) {
108 $orderByParams = CRM_Utils_Array::value('order_bys', $_POST);
109 }
110 elseif ( CRM_Core_OptionGroup::getValue('activity_type','WalkList') == $this->_surveyDetails['activity_type_id'] ) {
111 $orderByParams =
112 array(
113 1 =>
114 array(
115 'column' => 'civicrm_address.street_name',
116 'order' => 'ASC',
117 ),
118 2 =>
119 array(
120 'column' => 'civicrm_address.street_number%2',
121 'order' => 'ASC',
122 ),
123 3 =>
124 array(
125 'column' => 'civicrm_address.street_number',
126 'order' => 'ASC',
127 ),
128 4 =>
129 array(
130 'column' => 'contact_a.sort_name',
131 'order' => 'ASC',
132 ),
133 );
134 }
135
136 $orderBy = array();
137 if ( !empty($orderByParams) ) {
138 foreach ( $orderByParams as $key => $val ) {
139 if (CRM_Utils_Array::value('column', $val)) {
140 $orderBy[] = "{$val['column']} {$val['order']}";
141 }
142 }
143 if ( !empty($orderBy) ) {
144 $orderClause = "ORDER BY " . implode(', ', $orderBy);
145 }
146 }
147
148 $this->_contactIds = array_unique($this->_contactIds);
149 if (!empty($this->_contactIds) && $orderClause) {
150 $clause = 'contact_a.id IN ( ' . implode(',', $this->_contactIds) . ' ) ';
151 $sql = "
152SELECT contact_a.id
153FROM civicrm_contact contact_a
154LEFT JOIN civicrm_address ON contact_a.id = civicrm_address.contact_id
155WHERE {$clause}
156{$orderClause}";
157
158 $this->_contactIds = array();
159 $dao = CRM_Core_DAO::executeQuery($sql);
160 while ($dao->fetch()) {
161 $this->_contactIds[] = $dao->id;
162 }
163 }
164
165
166 //get the contact read only fields to display.
167 $readOnlyFields = array_merge(array(
168 'contact_type' => '',
169 'sort_name' => ts('Name'),
170 ));
171
172 //get the read only field data.
173 $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
174 $returnProperties['contact_sub_type'] = TRUE;
175
176 //validate all voters for required activity.
177 //get the survey activities for given voters.
178 $this->_surveyActivityIds = CRM_Campaign_BAO_Survey::voterActivityDetails($this->_surveyId,
179 $this->_contactIds,
180 $this->_interviewerId
181 );
182 $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
183 $scheduledStatusId = array_search('Scheduled', $activityStatus);
184
185 $activityIds = array();
186 foreach ($this->_contactIds as $key => $voterId) {
187 $actVals = CRM_Utils_Array::value($voterId, $this->_surveyActivityIds);
188 $statusId = CRM_Utils_Array::value('status_id', $actVals);
189 $activityId = CRM_Utils_Array::value('activity_id', $actVals);
190 if ($activityId &&
191 $statusId &&
192 $scheduledStatusId == $statusId
193 ) {
194 $activityIds["activity_id_{$voterId}"] = $activityId;
195 }
196 else {
197 unset($this->_contactIds[$key]);
198 }
199 }
200
201 //retrieve the contact details.
202 $voterDetails = CRM_Campaign_BAO_Survey::voterDetails($this->_contactIds, $returnProperties);
203
204 $this->_allowAjaxReleaseButton = FALSE;
205 if ($this->_votingTab &&
206 (CRM_Core_Permission::check('manage campaign') ||
207 CRM_Core_Permission::check('administer CiviCampaign') ||
208 CRM_Core_Permission::check('release campaign contacts')
209 )
210 ) {
211 $this->_allowAjaxReleaseButton = TRUE;
212 }
213
214 //validate voter ids across profile.
215 $this->filterVoterIds();
216 $this->assign('votingTab', $this->_votingTab);
217 $this->assign('componentIds', $this->_contactIds);
218 $this->assign('componentIdsJson', json_encode($this->_contactIds));
219 $this->assign('voterDetails', $voterDetails);
220 $this->assign('readOnlyFields', $readOnlyFields);
221 $this->assign('interviewerId', $this->_interviewerId);
222 $this->assign('surveyActivityIds', json_encode($activityIds));
223 $this->assign('allowAjaxReleaseButton', $this->_allowAjaxReleaseButton);
224
225 //get the survey values.
226 $this->_surveyValues = $this->get('surveyValues');
227 if (!is_array($this->_surveyValues)) {
228 $this->_surveyValues = array();
229 if ($this->_surveyId) {
230 $surveyParams = array('id' => $this->_surveyId);
231 CRM_Campaign_BAO_Survey::retrieve($surveyParams, $this->_surveyValues);
232 }
233 $this->set('surveyValues', $this->_surveyValues);
234 }
235 $this->assign('surveyValues', $this->_surveyValues);
236
237 $result = CRM_Campaign_BAO_Survey::getReportID($this->_surveyId);
238 $this->assign("instanceId",$result);
239
240 //get the survey result options.
241 $this->_resultOptions = $this->get('resultOptions');
242 if (!is_array($this->_resultOptions)) {
243 $this->_resultOptions = array();
244 if ($resultOptionId = CRM_Utils_Array::value('result_id', $this->_surveyValues)) {
245 $this->_resultOptions = CRM_Core_OptionGroup::valuesByID($resultOptionId);
246 }
247 $this->set('resultOptions', $this->_resultOptions);
248 }
249
250 //validate the required ids.
251 $this->validateIds();
252
253 //append breadcrumb to survey dashboard.
254 if (CRM_Campaign_BAO_Campaign::accessCampaign()) {
255 $url = CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=survey');
256 CRM_Utils_System::appendBreadCrumb(array(array('title' => ts('Survey(s)'), 'url' => $url)));
257 }
258
259 //set the title.
260 $activityTypes = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
261 $this->_surveyTypeId = CRM_Utils_Array::value('activity_type_id', $this->_surveyValues);
262 CRM_Utils_System::setTitle(ts('Record %1 Responses', array(1 => $activityTypes[$this->_surveyTypeId])));
263 }
264
265 function validateIds() {
266 $required = array('surveyId' => ts('Could not find Survey.'),
267 'interviewerId' => ts('Could not find Interviewer.'),
268 'contactIds' => ts('No respondents are currently reserved for you to interview.'),
269 'resultOptions' => ts('Oops. It looks like there is no response option configured.'),
270 );
271
272 $errorMessages = array();
273 foreach ($required as $fld => $msg) {
274 if (empty($this->{"_$fld"})) {
275 if (!$this->_votingTab) {
276 CRM_Core_Error::statusBounce($msg);
277 break;
278 }
279 $errorMessages[] = $msg;
280 }
281 }
282
283 $this->assign('errorMessages', empty($errorMessages) ? FALSE : $errorMessages);
284 }
285
286 /**
287 * Build the form
288 *
289 * @access public
290 *
291 * @return void
292 */
293 function buildQuickForm() {
294 $this->assign('surveyTypeId', $this->_surveyTypeId);
295
296 $options =
297 array('' => ' - none - ',
298 'civicrm_address.street_name' => 'Street Name',
299 'civicrm_address.street_number%2' => 'Odd / Even Street Number',
300 'civicrm_address.street_number' => 'Street Number',
301 'contact_a.sort_name' => 'Respondent Name',
302 );
303 for ($i = 1; $i < count($options); $i++) {
304 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
305 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
306 }
307
308 //pickup the uf fields.
309 $this->_surveyFields = CRM_Campaign_BAO_Survey::getSurveyResponseFields($this->_surveyId,
310 $this->_surveyTypeId
311 );
312
313 foreach ($this->_contactIds as $contactId) {
314 //build the profile fields.
315 foreach ($this->_surveyFields as $name => $field) {
316 if ($field){
317 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $contactId);
318 }
319 }
320
321 //build the result field.
322 if (!empty($this->_resultOptions)) {
323 $this->add('select', "field[$contactId][result]", ts('Result'),
324 array(
325 '' => ts('- select -')) +
326 array_combine($this->_resultOptions, $this->_resultOptions)
327 );
328 }
329
330 $this->add('text', "field[{$contactId}][note]", ts('Note'));
331
332 //need to keep control for release/reserve.
333 if ($this->_allowAjaxReleaseButton) {
334 $this->addElement('hidden',
335 "field[{$contactId}][is_release_or_reserve]", 0,
336 array('id' => "field_{$contactId}_is_release_or_reserve")
337 );
338 }
339 }
340 $this->assign('surveyFields', empty($this->_surveyFields) ? FALSE : $this->_surveyFields);
341
342 //no need to get qf buttons.
343 if ($this->_votingTab) {
344 return;
345 }
346
347 $buttons = array(
348 array('type' => 'cancel',
349 'name' => ts('Done'),
350 'subName' => 'interview',
351 'isDefault' => TRUE,
352 ));
353
354 $buttons[] = array(
355 'type' => 'submit',
356 'name' => ts('Order By >>'),
357 'subName' => 'orderBy',
358 );
359
360 $manageCampaign = CRM_Core_Permission::check('manage campaign');
361 $adminCampaign = CRM_Core_Permission::check('administer CiviCampaign');
362 if ($manageCampaign ||
363 $adminCampaign ||
364 CRM_Core_Permission::check('release campaign contacts')
365 ) {
366 $buttons[] = array(
367 'type' => 'next',
368 'name' => ts('Release Respondents >>'),
369 'subName' => 'interviewToRelease',
370 );
371 }
372 if ($manageCampaign ||
373 $adminCampaign ||
374 CRM_Core_Permission::check('reserve campaign contacts')
375 ) {
376 $buttons[] = array(
377 'type' => 'done',
378 'name' => ts('Reserve More Respondents >>'),
379 'subName' => 'interviewToReserve',
380 );
381 }
382
383 $this->addButtons($buttons);
384 }
385
386 /**
387 * This function sets the default values for the form.
388 *
389 * @access public
390 *
391 * @return None
392 */
393 function setDefaultValues() {
394 //load default data for only contact fields.
395 $contactFields = $defaults = array();
396 foreach ($this->_surveyFields as $name => $field) {
397 $acceptable_types = CRM_Contact_BAO_ContactType::basicTypes();
398 $acceptable_types[] = 'Contact';
399 if (in_array($field['field_type'], $acceptable_types)) {
400 $contactFields[$name] = $field;
401 }
402 }
403 if (!empty($contactFields)) {
404 foreach ($this->_contactIds as $contactId) {
405 CRM_Core_BAO_UFGroup::setProfileDefaults($contactId, $contactFields, $defaults, FALSE);
406 }
407 }
408
409 if ( CRM_Core_OptionGroup::getValue('activity_type','WalkList') == $this->_surveyDetails['activity_type_id'] ) {
410 $defaults['order_bys'] =
411 array(
412 1 =>
413 array(
414 'column' => 'civicrm_address.street_name',
415 'order' => 'ASC',
416 ),
417 2 =>
418 array(
419 'column' => 'civicrm_address.street_number%2',
420 'order' => 'ASC',
421 ),
422 3 =>
423 array(
424 'column' => 'civicrm_address.street_number',
425 'order' => 'ASC',
426 ),
427 4 =>
428 array(
429 'column' => 'contact_a.sort_name',
430 'order' => 'ASC',
431 ),
432 );
433 }
434 else {
435 $defaults['order_bys'] =
436 array(
437 1 =>
438 array(
439 'column' => 'contact_a.sort_name',
440 'order' => 'ASC',
441 ),
442 );
443 }
444 return $defaults;
445 }
446
447 /**
448 * process the form after the input has been submitted and validated
449 *
450 * @access public
451 *
452 * @return None
453 */
454 public function postProcess() {
455 $buttonName = $this->controller->getButtonName();
456 if ($buttonName == '_qf_Interview_done_interviewToReserve') {
457 //hey its time to stop cycle.
458 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/survey/search', 'reset=1&op=reserve'));
459 }
460 elseif ($buttonName == '_qf_Interview_next_interviewToRelease') {
461 //get ready to jump to release form.
462 foreach (array(
463 'surveyId', 'contactIds', 'interviewerId') as $fld) {
464 $this->controller->set($fld, $this->{"_$fld"});
465 }
466 $this->controller->set('interviewToRelease', TRUE);
467 }
468
469 // vote is done through ajax
470 return;
471 }
472
473 static function registerInterview($params) {
474 $activityId = CRM_Utils_Array::value('activity_id', $params);
475 $surveyTypeId = CRM_Utils_Array::value('activity_type_id', $params);
476 if (!is_array($params) || !$surveyTypeId || !$activityId) {
477 return FALSE;
478 }
479
480 static $surveyFields;
481 if (!is_array($surveyFields)) {
482 $surveyFields = CRM_Core_BAO_CustomField::getFields('Activity',
483 FALSE,
484 FALSE,
485 $surveyTypeId,
486 NULL,
487 FALSE,
488 TRUE
489 );
490 }
491
492 static $statusId;
493 if (!$statusId) {
494 $statusId = array_search('Completed', CRM_Core_PseudoConstant::activityStatus('name'));
495 }
496
497 //format custom fields.
498 $customParams = CRM_Core_BAO_CustomField::postProcess($params,
499 $surveyFields,
500 $activityId,
501 'Activity'
502 );
503
504 CRM_Core_BAO_CustomValueTable::store($customParams, 'civicrm_activity', $activityId);
505
506 //process contact data.
507 $contactParams = $fields = array();
508
509 $contactFieldTypes = array_merge(array('Contact'), CRM_Contact_BAO_ContactType::basicTypes());
510 $responseFields = CRM_Campaign_BAO_Survey::getSurveyResponseFields($params['survey_id']);
511 if (!empty($responseFields)) {
512 foreach ($params as $key => $value) {
513 if (array_key_exists($key, $responseFields)) {
514 if (in_array($responseFields[$key]['field_type'], $contactFieldTypes)) {
515 $fields[$key] = $responseFields[$key];
516 $contactParams[$key] = $value;
517 if (isset($params["{$key}_id"])) {
518 $contactParams["{$key}_id"] = $params["{$key}_id"];
519 }
520 }
521 }
522 }
523 }
524
525 $contactId = CRM_Utils_Array::value('voter_id', $params);
526 if ($contactId && !empty($contactParams)) {
527 CRM_Contact_BAO_Contact::createProfileContact($contactParams, $fields, $contactId);
528 }
529
530 //update activity record.
531 $activity = new CRM_Activity_DAO_Activity();
532 $activity->id = $activityId;
533
534 $activity->selectAdd();
535 $activity->selectAdd('activity_date_time, status_id, result, subject');
536 $activity->find(TRUE);
537 $activity->activity_date_time = date('YmdHis');
538 $activity->status_id = $statusId;
539
5ee01db2
RN
540 if (CRM_Utils_Array::value('activity_date_time', $params)) {
541 $activity->activity_date_time = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
6a488035
TO
542 }
543
544 $subject = '';
545 $surveyTitle = CRM_Utils_Array::value('surveyTitle', $params);
546 if ($surveyTitle) {
547 $subject = ts('%1', array(1 => $surveyTitle));
548 $subject .= ' - ';
549 }
550 $subject .= ts('Respondent Interview');
551
552 $activity->subject = $subject;
5ee01db2
RN
553 $activityParams = array(
554 'details' => 'details',
555 'result' => 'result',
8ef12e64 556 'engagement_level' => 'activity_engagement_level',
5ee01db2
RN
557 'subject' => 'activity_subject',
558 'status_id' => 'activity_status_id',
8ef12e64 559 'source_contact_id' => 'source_contact',
560 'location' => 'activity_location',
5ee01db2
RN
561 'campaign_id' => 'activity_campaign_id',
562 'duration' => 'activity_duration'
563 );
564 foreach ($activityParams as $key => $field) {
565 if (CRM_Utils_Array::value($field, $params)) {
566 $activity->$key = $params[$field];
567 }
568 }
8ef12e64 569
6a488035
TO
570 $activity->save();
571 //really this should use Activity BAO& not be here but refactoring will have to be later
572 //actually the whole ajax call could be done as an api ajax call & post hook would be sorted
573 CRM_Utils_Hook::post('edit', 'Activity', $activity->id, $activity);
574 $activity->free();
575
576 return $activityId;
577 }
578
579 function getVoterIds() {
580 if (!$this->_interviewerId) {
581 $session = CRM_Core_Session::singleton();
582 $this->_interviewerId = $session->get('userID');
583 }
584 if (!$this->_surveyId) {
585 // use default survey id
586 $dao = new CRM_Campaign_DAO_Survey();
587 $dao->is_active = 1;
588 $dao->is_default = 1;
589 $dao->find(TRUE);
590 $this->_surveyId = $dao->id;
591 }
592
593 $this->_contactIds = $this->get('contactIds');
594 if (!is_array($this->_contactIds)) {
595 //get the survey activities.
596 $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
597 $statusIds = array();
598 if ($statusId = array_search('Scheduled', $activityStatus)) {
599 $statusIds[] = $statusId;
600 }
601 $surveyActivities = CRM_Campaign_BAO_Survey::getSurveyVoterInfo($this->_surveyId,
602 $this->_interviewerId,
603 $statusIds
604 );
605 $this->_contactIds = array();
606 foreach ($surveyActivities as $val) $this->_contactIds[$val['voter_id']] = $val['voter_id'];
607 $this->set('contactIds', $this->_contactIds);
608 }
609 }
610
611 function filterVoterIds() {
612 //do the cleanup later on.
613 if (!is_array($this->_contactIds)) {
614 return;
615 }
616
617 $profileId = CRM_Campaign_BAO_Survey::getSurveyProfileId($this->_surveyId);
618 if ($profileId) {
619 $profileType = CRM_Core_BAO_UFField::getProfileType($profileId);
620 if (in_array($profileType, CRM_Contact_BAO_ContactType::basicTypes())) {
621 $voterIdCount = count($this->_contactIds);
622
623 //create temporary table to store voter ids.
624 $tempTableName = CRM_Core_DAO::createTempTableName('civicrm_survey_respondent');
625 CRM_Core_DAO::executeQuery("DROP TABLE IF EXISTS {$tempTableName}");
626 $query = "
627 CREATE TEMPORARY TABLE {$tempTableName} (
628 id int unsigned NOT NULL AUTO_INCREMENT,
8ef12e64 629 survey_contact_id int unsigned NOT NULL,
6a488035
TO
630 PRIMARY KEY ( id )
631);
632";
633 CRM_Core_DAO::executeQuery($query);
634 $batch = 100;
635 $insertedCount = 0;
636 do {
637 $processIds = $this->_contactIds;
638 $insertIds = array_splice($processIds, $insertedCount, $batch);
639 if (!empty($insertIds)) {
8ef12e64 640 $insertSQL = "INSERT IGNORE INTO {$tempTableName}( survey_contact_id )
6a488035
TO
641 VALUES (" . implode('),(', $insertIds) . ');';
642 CRM_Core_DAO::executeQuery($insertSQL);
643 }
644 $insertedCount += $batch;
645 } while ($insertedCount < $voterIdCount);
646
647 $query = "
648 SELECT contact.id as id
8ef12e64 649 FROM civicrm_contact contact
6a488035
TO
650INNER JOIN {$tempTableName} ON ( {$tempTableName}.survey_contact_id = contact.id )
651 WHERE contact.contact_type != %1";
652 $removeContact = CRM_Core_DAO::executeQuery($query,
653 array(1 => array($profileType, 'String'))
654 );
655 while ($removeContact->fetch()) {
656 unset($this->_contactIds[$removeContact->id]);
657 }
658 }
659 }
660 }
661}
662