3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This class provides the functionality to record voter's interview.
21 class CRM_Campaign_Form_Task_Interview
extends CRM_Campaign_Form_Task
{
24 * The title of the group
31 * Variable to store redirect path
34 private $_userContext;
38 private $_surveyFields;
40 private $_surveyTypeId;
42 private $_interviewerId;
44 private $_surveyActivityIds;
46 private $_votingTab = FALSE;
48 private $_surveyValues;
50 private $_resultOptions;
52 private $_allowAjaxReleaseButton;
55 * Build all the data structures needed to build the form.
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.
67 $this->{"_$fld"} = $this->get($fld);
69 //get the target voter ids.
70 if ($this->_votingTab
) {
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'));
81 if ($this->_surveyId
) {
82 $params = ['id' => $this->_surveyId
];
83 CRM_Campaign_BAO_Survey
::retrieve($params, $this->_surveyDetails
);
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;
92 elseif ($walkListActivityId == $this->_surveyDetails
['activity_type_id']) {
96 'column' => 'civicrm_address.street_name',
100 'column' => 'civicrm_address.street_number%2',
104 'column' => 'civicrm_address.street_number',
108 'column' => 'contact_a.sort_name',
115 if (!empty($orderByParams)) {
116 foreach ($orderByParams as $key => $val) {
117 if (!empty($val['column'])) {
118 $orderBy[] = "{$val['column']} {$val['order']}";
121 if (!empty($orderBy)) {
122 $orderClause = "ORDER BY " . implode(', ', $orderBy);
126 $this->_contactIds
= array_unique($this->_contactIds
);
127 if (!empty($this->_contactIds
) && $orderClause) {
128 $clause = 'contact_a.id IN ( ' . implode(',', $this->_contactIds
) . ' ) ';
131 FROM civicrm_contact contact_a
132 LEFT JOIN civicrm_address ON contact_a.id = civicrm_address.contact_id
136 $this->_contactIds
= [];
137 $dao = CRM_Core_DAO
::executeQuery($sql);
138 while ($dao->fetch()) {
139 $this->_contactIds
[] = $dao->id
;
143 //get the contact read only fields to display.
144 $readOnlyFields = array_merge([
145 'contact_type' => '',
146 'sort_name' => ts('Name'),
149 //get the read only field data.
150 $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
151 $returnProperties['contact_sub_type'] = TRUE;
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
,
157 $this->_interviewerId
159 $scheduledStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Scheduled');
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;
168 $scheduledStatusId == $statusId
170 $activityIds["activity_id_{$voterId}"] = $activityId;
173 unset($this->_contactIds
[$key]);
177 //retrieve the contact details.
178 $voterDetails = CRM_Campaign_BAO_Survey
::voterDetails($this->_contactIds
, $returnProperties);
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')
187 $this->_allowAjaxReleaseButton
= TRUE;
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
);
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
);
209 $this->set('surveyValues', $this->_surveyValues
);
211 $this->assign('surveyValues', $this->_surveyValues
);
213 $result = CRM_Campaign_BAO_Survey
::getReportID($this->_surveyId
);
214 $this->assign("instanceId", $result);
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);
223 $this->set('resultOptions', $this->_resultOptions
);
226 //validate the required ids.
227 $this->validateIds();
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]]);
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]));
241 public function validateIds() {
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.'),
250 foreach ($required as $fld => $msg) {
251 if (empty($this->{"_$fld"})) {
252 if (!$this->_votingTab
) {
253 CRM_Core_Error
::statusBounce($msg);
256 $errorMessages[] = $msg;
260 $this->assign('errorMessages', empty($errorMessages) ?
FALSE : $errorMessages);
264 * Build the form object.
266 public function buildQuickForm() {
267 $this->assign('surveyTypeId', $this->_surveyTypeId
);
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',
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'),
285 //pickup the uf fields.
286 $this->_surveyFields
= CRM_Campaign_BAO_Survey
::getSurveyResponseFields($this->_surveyId
,
290 foreach ($this->_contactIds
as $contactId) {
291 //build the profile fields.
292 foreach ($this->_surveyFields
as $name => $field) {
294 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, NULL, $contactId);
298 //build the result field.
299 if (!empty($this->_resultOptions
)) {
300 $this->add('select', "field[$contactId][result]", ts('Result'),
302 '' => ts('- select -'),
304 array_combine($this->_resultOptions
, $this->_resultOptions
)
308 $this->add('text', "field[{$contactId}][note]", ts('Note'));
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"]
318 $this->assign('surveyFields', empty($this->_surveyFields
) ?
FALSE : $this->_surveyFields
);
320 //no need to get qf buttons.
321 if ($this->_votingTab
) {
328 'name' => ts('Done'),
329 'subName' => 'interview',
336 'name' => ts('Order By >>'),
337 'subName' => 'orderBy',
340 $manageCampaign = CRM_Core_Permission
::check('manage campaign');
341 $adminCampaign = CRM_Core_Permission
::check('administer CiviCampaign');
342 if ($manageCampaign ||
344 CRM_Core_Permission
::check('release campaign contacts')
348 'name' => ts('Release Respondents >>'),
349 'subName' => 'interviewToRelease',
352 if ($manageCampaign ||
354 CRM_Core_Permission
::check('reserve campaign contacts')
358 'name' => ts('Reserve More Respondents >>'),
359 'subName' => 'interviewToReserve',
363 $this->addButtons($buttons);
367 * Set default values for the form.
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;
379 if (!empty($contactFields)) {
380 foreach ($this->_contactIds
as $contactId) {
381 CRM_Core_BAO_UFGroup
::setProfileDefaults($contactId, $contactFields, $defaults, FALSE);
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']
390 'column' => 'civicrm_address.street_name',
394 'column' => 'civicrm_address.street_number%2',
398 'column' => 'civicrm_address.street_number',
402 'column' => 'contact_a.sort_name',
408 $defaults['order_bys']
411 'column' => 'contact_a.sort_name',
420 * Process the form after the input has been submitted and validated.
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'));
428 elseif ($buttonName == '_qf_Interview_next_interviewToRelease') {
429 //get ready to jump to release form.
435 $this->controller
->set($fld, $this->{"_$fld"});
437 $this->controller
->set('interviewToRelease', TRUE);
440 // vote is done through ajax
444 * @param array $params
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) {
455 static $surveyFields;
456 if (!is_array($surveyFields)) {
457 $surveyFields = CRM_Core_BAO_CustomField
::getFields('Activity',
469 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed');
472 //format custom fields.
473 $customParams = CRM_Core_BAO_CustomField
::postProcess($params,
478 CRM_Core_BAO_CustomValueTable
::store($customParams, 'civicrm_activity', $activityId);
480 //process contact data.
481 $contactParams = $fields = [];
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"];
499 $contactId = $params['voter_id'] ??
NULL;
500 if ($contactId && !empty($contactParams)) {
501 CRM_Contact_BAO_Contact
::createProfileContact($contactParams, $fields, $contactId);
504 //update activity record.
505 $activity = new CRM_Activity_DAO_Activity();
506 $activity->id
= $activityId;
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;
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']);
519 $surveyTitle = $params['surveyTitle'] ??
NULL;
521 $subject = $surveyTitle . ' - ';
523 $subject .= ts('Respondent Interview');
525 $activity->subject
= $subject;
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',
537 foreach ($activityParams as $key => $field) {
538 if (!empty($params[$field])) {
539 $activity->$key = $params[$field];
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);
551 public function getVoterIds() {
552 if (!$this->_interviewerId
) {
553 $session = CRM_Core_Session
::singleton();
554 $this->_interviewerId
= $session->get('userID');
556 if (!$this->_surveyId
) {
557 // use default survey id
558 $dao = new CRM_Campaign_DAO_Survey();
560 $dao->is_default
= 1;
562 $this->_surveyId
= $dao->id
;
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
,
573 $this->_contactIds
= [];
574 foreach ($surveyActivities as $val) {
575 $this->_contactIds
[$val['voter_id']] = $val['voter_id'];
577 $this->set('contactIds', $this->_contactIds
);
581 public function filterVoterIds() {
582 //do the cleanup later on.
583 if (!is_array($this->_contactIds
)) {
587 $profileId = CRM_Campaign_BAO_Survey
::getSurveyProfileId($this->_surveyId
);
589 $profileType = CRM_Core_BAO_UFField
::getProfileType($profileId);
590 if (in_array($profileType, CRM_Contact_BAO_ContactType
::basicTypes())) {
591 $voterIdCount = count($this->_contactIds
);
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 )')
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);
607 $insertedCount +
= $batch;
608 } while ($insertedCount < $voterIdCount);
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']]
618 while ($removeContact->fetch()) {
619 unset($this->_contactIds
[$removeContact->id
]);