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