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