Merge pull request #14211 from colemanw/routeBinder
[civicrm-core.git] / CRM / Event / Form / Task / Batch.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
32 */
33
34/**
0f57ba7a 35 * This class provides the functionality for batch profile update for events.
6a488035
TO
36 */
37class CRM_Event_Form_Task_Batch extends CRM_Event_Form_Task {
38
39 /**
eceb18cc 40 * The title of the group.
6a488035
TO
41 *
42 * @var string
43 */
44 protected $_title;
45
46 /**
eceb18cc 47 * Maximum profile fields that will be displayed.
90b461f1 48 * @var int
6a488035
TO
49 */
50 protected $_maxFields = 9;
51
52 /**
eceb18cc 53 * Variable to store redirect path.
90b461f1 54 * @var string
6a488035
TO
55 */
56 protected $_userContext;
57
58 /**
100fef9d 59 * Variable to store previous status id.
90b461f1 60 * @var array
6a488035
TO
61 */
62 protected $_fromStatusIds;
63
64 /**
eceb18cc 65 * Build all the data structures needed to build the form.
6a488035
TO
66 *
67 * @return void
03e04002 68 */
00be9182 69 public function preProcess() {
353ffa53
TO
70 /*
71 * initialize the task and row fields
72 */
6a488035
TO
73 parent::preProcess();
74
75 //get the contact read only fields to display.
be2fb01f 76 $readOnlyFields = array_merge(['sort_name' => ts('Name')],
6a488035
TO
77 CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
78 'contact_autocomplete_options',
79 TRUE, NULL, FALSE, 'name', TRUE
80 )
81 );
82 //get the read only field data.
83 $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
84 $contactDetails = CRM_Contact_BAO_Contact_Utils::contactDetails($this->_participantIds,
85 'CiviEvent', $returnProperties
86 );
87 $this->assign('contactDetails', $contactDetails);
88 $this->assign('readOnlyFields', $readOnlyFields);
89 }
90
91 /**
eceb18cc 92 * Build the form object.
6a488035 93 *
6a488035
TO
94 *
95 * @return void
96 */
00be9182 97 public function buildQuickForm() {
6a488035 98 $ufGroupId = $this->get('ufGroupId');
6a488035
TO
99 if (!$ufGroupId) {
100 CRM_Core_Error::fatal('ufGroupId is missing');
101 }
102
b581842f 103 $this->_title = ts('Update multiple participants') . ' - ' . CRM_Core_BAO_UFGroup::getTitle($ufGroupId);
6a488035
TO
104 CRM_Utils_System::setTitle($this->_title);
105 $this->addDefaultButtons(ts('Save'));
be2fb01f 106 $this->_fields = [];
6a488035 107 $this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW);
f72db5fa 108 if (array_key_exists('participant_status', $this->_fields)) {
3ea7ca33 109 $this->assign('statusProfile', 1);
110 $this->assignToTemplate();
111 }
6a488035
TO
112
113 // remove file type field and then limit fields
114 $suppressFields = FALSE;
be2fb01f 115 $removehtmlTypes = ['File'];
6a488035
TO
116 foreach ($this->_fields as $name => $field) {
117 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) &&
118 in_array($this->_fields[$name]['html_type'], $removehtmlTypes)
119 ) {
120 $suppressFields = TRUE;
121 unset($this->_fields[$name]);
122 }
123
124 //fix to reduce size as we are using this field in grid
125 if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) {
126 //shrink class to "form-text-medium"
127 $this->_fields[$name]['attributes']['size'] = 19;
128 }
129 }
130
131 $this->_fields = array_slice($this->_fields, 0, $this->_maxFields);
132
be2fb01f 133 $this->addButtons([
90b461f1
SL
134 [
135 'type' => 'submit',
136 'name' => ts('Update Participant(s)'),
137 'isDefault' => TRUE,
138 ],
139 [
140 'type' => 'cancel',
141 'name' => ts('Cancel'),
142 ],
143 ]);
6a488035 144
6a488035
TO
145 $this->assign('profileTitle', $this->_title);
146 $this->assign('componentIds', $this->_participantIds);
147 $fileFieldExists = FALSE;
148
149 //load all campaigns.
150 if (array_key_exists('participant_campaign_id', $this->_fields)) {
be2fb01f 151 $this->_componentCampaigns = [];
6a488035
TO
152 CRM_Core_PseudoConstant::populate($this->_componentCampaigns,
153 'CRM_Event_DAO_Participant',
154 TRUE, 'campaign_id', 'id',
155 ' id IN (' . implode(' , ', array_values($this->_participantIds)) . ' ) '
156 );
157 }
158
159 //fix for CRM-2752
160 // get the option value for custom data type
c460c196
PN
161 $customDataType = CRM_Core_OptionGroup::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name');
162 $this->_roleCustomDataTypeID = array_search('ParticipantRole', $customDataType);
163 $this->_eventNameCustomDataTypeID = array_search('ParticipantEventName', $customDataType);
164 $this->_eventTypeCustomDataTypeID = array_search('ParticipantEventType', $customDataType);
6a488035
TO
165
166 // build custom data getFields array
167 $customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, $this->_roleCustomDataTypeID);
168
169 $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, $this->_eventNameCustomDataTypeID);
d623de42
M
170 $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, $this->_eventTypeCustomDataTypeID);
171
6a488035
TO
172 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole,
173 CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE)
174 );
d623de42 175 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
6a488035
TO
176 $this->_customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
177
178 foreach ($this->_participantIds as $participantId) {
179 $roleId = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participantId, 'role_id');
180 $eventId = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participantId, 'event_id');
d623de42 181 $eventTypeId = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $eventId, 'event_type_id');
6a488035
TO
182 foreach ($this->_fields as $name => $field) {
183 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
184 $customValue = CRM_Utils_Array::value($customFieldID, $this->_customFields);
be2fb01f 185 $entityColumnValue = [];
a7488080 186 if (!empty($customValue['extends_entity_column_value'])) {
6a488035
TO
187 $entityColumnValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
188 $customValue['extends_entity_column_value']
189 );
190 }
191 $entityColumnValueRole = CRM_Utils_Array::value($roleId, $entityColumnValue);
9f8dff81 192 $entityColumnValueEventType = in_array($eventTypeId, $entityColumnValue) ? $eventTypeId : NULL;
6a488035
TO
193 if (($this->_roleCustomDataTypeID == $customValue['extends_entity_column_id']) &&
194 ($entityColumnValueRole)
195 ) {
196 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
197 }
198 elseif (($this->_eventNameCustomDataTypeID == $customValue['extends_entity_column_id']) &&
199 ($eventId == $entityColumnValueRole)
200 ) {
201 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
202 }
d623de42
M
203 elseif ($this->_eventTypeCustomDataTypeID == $customValue['extends_entity_column_id'] &&
204 ($entityColumnValueEventType == $eventTypeId)
205 ) {
206 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
207 }
6a488035
TO
208 elseif (CRM_Utils_System::isNull($entityColumnValueRole)) {
209 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
210 }
211 }
212 else {
f2f98854 213 if ($field['name'] == 'participant_role') {
6a488035
TO
214 $field['is_multiple'] = TRUE;
215 }
216 // handle non custom fields
217 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
218 }
219 }
220 }
221
222 $this->assign('fields', $this->_fields);
223
224 // don't set the status message when form is submitted.
225 $buttonName = $this->controller->getButtonName('submit');
226
227 if ($suppressFields && $buttonName != '_qf_Batch_next') {
657c89d9 228 CRM_Core_Session::setStatus(ts("File type field(s) in the selected profile are not supported for Update multiple participants."), ts('Unsupported Field Type'), 'info');
6a488035
TO
229 }
230
231 $this->addDefaultButtons(ts('Update Participant(s)'));
232 }
233
234 /**
c490a46a 235 * Set default values for the form.
6a488035 236 *
6a488035 237 *
355ba699 238 * @return void
6a488035 239 */
00be9182 240 public function setDefaultValues() {
6a488035
TO
241 if (empty($this->_fields)) {
242 return;
243 }
244
be2fb01f 245 $defaults = [];
6a488035 246 foreach ($this->_participantIds as $participantId) {
be2fb01f 247 $details[$participantId] = [];
6a488035
TO
248
249 $details[$participantId] = CRM_Event_BAO_Participant::participantDetails($participantId);
250 CRM_Core_BAO_UFGroup::setProfileDefaults(NULL, $this->_fields, $defaults, FALSE, $participantId, 'Event');
251
252 //get the from status ids, CRM-4323
253 if (array_key_exists('participant_status', $this->_fields)) {
254 $this->_fromStatusIds[$participantId] = CRM_Utils_Array::value("field[$participantId][participant_status]", $defaults);
255 }
256 if (array_key_exists('participant_role', $this->_fields)) {
257 if ($defaults["field[{$participantId}][participant_role]"]) {
258 $roles = $defaults["field[{$participantId}][participant_role]"];
259 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $roles) as $k => $v) {
260 $defaults["field[$participantId][participant_role][{$v}]"] = 1;
261 }
262 unset($defaults["field[{$participantId}][participant_role]"]);
263 }
264 }
265 }
266
267 $this->assign('details', $details);
268 return $defaults;
269 }
270
271 /**
eceb18cc 272 * Process the form after the input has been submitted and validated.
6a488035
TO
273 */
274 public function postProcess() {
275 $params = $this->exportValues();
0f57ba7a 276 $this->submit($params);
6a488035 277 }
6a488035 278
0cf587a7 279 /**
100fef9d
CW
280 * @param int $participantId
281 * @param int $statusId
0cf587a7 282 *
90b461f1 283 * @return mixed
0cf587a7 284 */
00be9182 285 public static function updatePendingOnlineContribution($participantId, $statusId) {
6a488035 286 if (!$participantId || !$statusId) {
28a04ea9 287 return NULL;
6a488035
TO
288 }
289
290 $contributionId = CRM_Contribute_BAO_Contribution::checkOnlinePendingContribution($participantId,
291 'Event'
292 );
293 if (!$contributionId) {
294 return;
295 }
296
297 //status rules.
298 //1. participant - positive => contribution - completed.
299 //2. participant - negative => contribution - cancelled.
300
301 $positiveStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Positive'");
302 $negativeStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
303 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
304
305 $contributionStatusId = NULL;
306 if (array_key_exists($statusId, $positiveStatuses)) {
307 $contributionStatusId = array_search('Completed', $contributionStatuses);
308 }
309 if (array_key_exists($statusId, $negativeStatuses)) {
310 $contributionStatusId = array_search('Cancelled', $contributionStatuses);
311 }
312
313 if (!$contributionStatusId) {
314 return;
315 }
316
be2fb01f 317 $params = [
6a488035
TO
318 'component_id' => $participantId,
319 'componentName' => 'Event',
320 'contribution_id' => $contributionId,
321 'contribution_status_id' => $contributionStatusId,
0bad10e7 322 'IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved' => 1,
be2fb01f 323 ];
6a488035
TO
324
325 //change related contribution status.
e577770c 326 $updatedStatusId = self::updateContributionStatus($params);
6a488035
TO
327
328 return $updatedStatusId;
329 }
96025800 330
e577770c
EM
331 /**
332 * Update contribution status.
333 *
334 * @deprecated
335 * This is only called from one place in the code &
336 * it is unclear whether it is a function on the way in or on the way out
337 *
338 * @param array $params
339 *
340 * @return NULL|int
341 */
342 public static function updateContributionStatus($params) {
343 // get minimum required values.
344 $statusId = CRM_Utils_Array::value('contribution_status_id', $params);
345 $componentId = CRM_Utils_Array::value('component_id', $params);
346 $componentName = CRM_Utils_Array::value('componentName', $params);
347 $contributionId = CRM_Utils_Array::value('contribution_id', $params);
348
349 if (!$contributionId || !$componentId || !$componentName || !$statusId) {
350 return NULL;
351 }
352
be2fb01f 353 $input = $ids = $objects = [];
e577770c
EM
354
355 //get the required ids.
356 $ids['contribution'] = $contributionId;
357
358 if (!$ids['contact'] = CRM_Utils_Array::value('contact_id', $params)) {
359 $ids['contact'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
360 $contributionId,
361 'contact_id'
362 );
363 }
364
365 if ($componentName == 'Event') {
366 $name = 'event';
367 $ids['participant'] = $componentId;
368
369 if (!$ids['event'] = CRM_Utils_Array::value('event_id', $params)) {
370 $ids['event'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
371 $componentId,
372 'event_id'
373 );
374 }
375 }
376
377 if ($componentName == 'Membership') {
378 $name = 'contribute';
379 $ids['membership'] = $componentId;
380 }
381 $ids['contributionPage'] = NULL;
382 $ids['contributionRecur'] = NULL;
383 $input['component'] = $name;
384
385 $baseIPN = new CRM_Core_Payment_BaseIPN();
386 $transaction = new CRM_Core_Transaction();
387
388 // reset template values.
389 $template = CRM_Core_Smarty::singleton();
390 $template->clearTemplateVars();
391
392 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
393 CRM_Core_Error::fatal();
394 }
395
396 $contribution = &$objects['contribution'];
397
be2fb01f 398 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
e577770c
EM
399 'labelColumn' => 'name',
400 'flip' => 1,
be2fb01f 401 ]);
0bad10e7 402 $input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'] = CRM_Utils_Array::value('IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved', $params);
e577770c
EM
403 if ($statusId == $contributionStatuses['Cancelled']) {
404 $baseIPN->cancelled($objects, $transaction, $input);
405 $transaction->commit();
406 return $statusId;
407 }
408 elseif ($statusId == $contributionStatuses['Failed']) {
409 $baseIPN->failed($objects, $transaction, $input);
410 $transaction->commit();
411 return $statusId;
412 }
413
414 // status is not pending
415 if ($contribution->contribution_status_id != $contributionStatuses['Pending']) {
416 $transaction->commit();
417 return;
418 }
419
420 //set values for ipn code.
be2fb01f 421 foreach ([
90b461f1
SL
422 'fee_amount',
423 'check_number',
424 'payment_instrument_id',
425 ] as $field) {
e577770c
EM
426 if (!$input[$field] = CRM_Utils_Array::value($field, $params)) {
427 $input[$field] = $contribution->$field;
428 }
429 }
430 if (!$input['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params)) {
431 $input['trxn_id'] = $contribution->invoice_id;
432 }
433 if (!$input['amount'] = CRM_Utils_Array::value('total_amount', $params)) {
434 $input['amount'] = $contribution->total_amount;
435 }
436 $input['is_test'] = $contribution->is_test;
437 $input['net_amount'] = $contribution->net_amount;
438 if (!empty($input['fee_amount']) && !empty($input['amount'])) {
439 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
440 }
441
442 //complete the contribution.
2ea48796 443 // @todo use the api - ie civicrm_api3('Contribution', 'completetransaction', $input);
444 // as this method is not preferred / supported.
e577770c
EM
445 $baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
446
447 // reset template values before processing next transactions
448 $template->clearTemplateVars();
449
450 return $statusId;
451 }
452
3ea7ca33 453 /**
454 * Assign the minimal set of variables to the template.
455 */
456 public function assignToTemplate() {
be2fb01f 457 $notifyingStatuses = ['Pending from waitlist', 'Pending from approval', 'Expired', 'Cancelled'];
3ea7ca33 458 $notifyingStatuses = array_intersect($notifyingStatuses, CRM_Event_PseudoConstant::participantStatus());
1aa1efef 459 $this->assign('status', TRUE);
3ea7ca33 460 if (!empty($notifyingStatuses)) {
4a64b915
AH
461 $s = '<em>' . implode('</em>, <em>', $notifyingStatuses) . '</em>';
462 $this->assign('notifyingStatuses', $s);
3ea7ca33 463 }
3ea7ca33 464 }
465
0f57ba7a 466 /**
467 * @param $params
468 */
469 public function submit($params) {
470 $statusClasses = CRM_Event_PseudoConstant::participantStatusClass();
471 if (isset($params['field'])) {
472 foreach ($params['field'] as $key => $value) {
473
474 //check for custom data
475 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
476 $key,
477 'Participant'
478 );
a4f468b6 479 foreach (array_keys($value) as $fieldName) {
480 // Unset the original custom field now that it has been formatting to the 'custom'
481 // array as it may not be in the right format for the api as is (notably for
482 // multiple checkbox values).
3eb99314 483 // @todo extract submit functions on other Batch update classes &
484 // extend CRM_Event_Form_Task_BatchTest::testSubmit with a data provider to test them.
a4f468b6 485 if (substr($fieldName, 0, 7) === 'custom_') {
486 unset($value[$fieldName]);
487 }
488 }
0f57ba7a 489
490 $value['id'] = $key;
491
492 if (!empty($value['participant_role'])) {
493 if (is_array($value['participant_role'])) {
494 $value['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($value['participant_role']));
495 }
496 else {
497 $value['role_id'] = $value['participant_role'];
498 }
499 }
500
501 //need to send mail when status change
502 $statusChange = FALSE;
503 $relatedStatusChange = FALSE;
504 if (!empty($value['participant_status'])) {
505 $value['status_id'] = $value['participant_status'];
506 $fromStatusId = CRM_Utils_Array::value($key, $this->_fromStatusIds);
507 if (!$fromStatusId) {
508 $fromStatusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $key, 'status_id');
509 }
510
511 if ($fromStatusId != $value['status_id']) {
512 $relatedStatusChange = TRUE;
513 }
514 if ($statusClasses[$fromStatusId] != $statusClasses[$value['status_id']]) {
515 $statusChange = TRUE;
516 }
517 }
518
519 unset($value['participant_status']);
520
521 civicrm_api3('Participant', 'create', $value);
522
523 //need to trigger mails when we change status
524 if ($statusChange) {
be2fb01f 525 CRM_Event_BAO_Participant::transitionParticipants([$key], $value['status_id'], $fromStatusId);
0f57ba7a 526 }
527 if ($relatedStatusChange) {
528 //update related contribution status, CRM-4395
529 self::updatePendingOnlineContribution($key, $value['status_id']);
530 }
531 }
532 CRM_Core_Session::setStatus(ts('The updates have been saved.'), ts('Saved'), 'success');
533 }
534 else {
535 CRM_Core_Session::setStatus(ts('No updates have been saved.'), ts('Not Saved'), 'alert');
536 }
537 }
538
6a488035 539}