Merge pull request #10306 from aydun/CRM-20525
[civicrm-core.git] / CRM / Event / Form / Task / Batch.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
32 * $Id$
33 *
34 */
35
36 /**
37 * This class provides the functionality for batch profile update for events
38 */
39 class CRM_Event_Form_Task_Batch extends CRM_Event_Form_Task {
40
41 /**
42 * The title of the group.
43 *
44 * @var string
45 */
46 protected $_title;
47
48 /**
49 * Maximum profile fields that will be displayed.
50 */
51 protected $_maxFields = 9;
52
53 /**
54 * Variable to store redirect path.
55 */
56 protected $_userContext;
57
58 /**
59 * Variable to store previous status id.
60 */
61 protected $_fromStatusIds;
62
63 /**
64 * Build all the data structures needed to build the form.
65 *
66 * @return void
67 */
68 public function preProcess() {
69 /*
70 * initialize the task and row fields
71 */
72 parent::preProcess();
73
74 //get the contact read only fields to display.
75 $readOnlyFields = array_merge(array('sort_name' => ts('Name')),
76 CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
77 'contact_autocomplete_options',
78 TRUE, NULL, FALSE, 'name', TRUE
79 )
80 );
81 //get the read only field data.
82 $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
83 $contactDetails = CRM_Contact_BAO_Contact_Utils::contactDetails($this->_participantIds,
84 'CiviEvent', $returnProperties
85 );
86 $this->assign('contactDetails', $contactDetails);
87 $this->assign('readOnlyFields', $readOnlyFields);
88 }
89
90 /**
91 * Build the form object.
92 *
93 *
94 * @return void
95 */
96 public function buildQuickForm() {
97 $ufGroupId = $this->get('ufGroupId');
98 if (!$ufGroupId) {
99 CRM_Core_Error::fatal('ufGroupId is missing');
100 }
101
102 $this->_title = ts('Update multiple participants') . ' - ' . CRM_Core_BAO_UFGroup::getTitle($ufGroupId);
103 CRM_Utils_System::setTitle($this->_title);
104 $this->addDefaultButtons(ts('Save'));
105 $this->_fields = array();
106 $this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW);
107 if (array_key_exists('participant_status', $this->_fields)) {
108 $this->assign('statusProfile', 1);
109 $this->assignToTemplate();
110 }
111
112 // remove file type field and then limit fields
113 $suppressFields = FALSE;
114 $removehtmlTypes = array('File', 'Autocomplete-Select');
115 foreach ($this->_fields as $name => $field) {
116 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) &&
117 in_array($this->_fields[$name]['html_type'], $removehtmlTypes)
118 ) {
119 $suppressFields = TRUE;
120 unset($this->_fields[$name]);
121 }
122
123 //fix to reduce size as we are using this field in grid
124 if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) {
125 //shrink class to "form-text-medium"
126 $this->_fields[$name]['attributes']['size'] = 19;
127 }
128 }
129
130 $this->_fields = array_slice($this->_fields, 0, $this->_maxFields);
131
132 $this->addButtons(array(
133 array(
134 'type' => 'submit',
135 'name' => ts('Update Participant(s)'),
136 'isDefault' => TRUE,
137 ),
138 array(
139 'type' => 'cancel',
140 'name' => ts('Cancel'),
141 ),
142 )
143 );
144
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)) {
151 $this->_componentCampaigns = array();
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
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);
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);
170 $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, $this->_eventTypeCustomDataTypeID);
171
172 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole,
173 CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE)
174 );
175 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
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');
181 $eventTypeId = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $eventId, 'event_type_id');
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);
185 $entityColumnValue = array();
186 if (!empty($customValue['extends_entity_column_value'])) {
187 $entityColumnValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
188 $customValue['extends_entity_column_value']
189 );
190 }
191 $entityColumnValueRole = CRM_Utils_Array::value($roleId, $entityColumnValue);
192 $entityColumnValueEventType = in_array($eventTypeId, $entityColumnValue) ? $eventTypeId : NULL;
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 }
203 elseif ($this->_eventTypeCustomDataTypeID == $customValue['extends_entity_column_id'] &&
204 ($entityColumnValueEventType == $eventTypeId)
205 ) {
206 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
207 }
208 elseif (CRM_Utils_System::isNull($entityColumnValueRole)) {
209 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
210 }
211 }
212 else {
213 if ($field['name'] == 'participant_role') {
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') {
228 CRM_Core_Session::setStatus(ts("File or Autocomplete-Select type field(s) in the selected profile are not supported for Update multiple participants."), ts('Unsupported Field Type'), 'info');
229 }
230
231 $this->addDefaultButtons(ts('Update Participant(s)'));
232 }
233
234 /**
235 * Set default values for the form.
236 *
237 *
238 * @return void
239 */
240 public function setDefaultValues() {
241 if (empty($this->_fields)) {
242 return;
243 }
244
245 $defaults = array();
246 foreach ($this->_participantIds as $participantId) {
247 $details[$participantId] = array();
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 /**
272 * Process the form after the input has been submitted and validated.
273 */
274 public function postProcess() {
275 $params = $this->exportValues();
276 $statusClasses = CRM_Event_PseudoConstant::participantStatusClass();
277 if (isset($params['field'])) {
278 foreach ($params['field'] as $key => $value) {
279
280 //check for custom data
281 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
282 $key,
283 'Participant'
284 );
285
286 $value['id'] = $key;
287
288 if (!empty($value['participant_role'])) {
289 if (is_array($value['participant_role'])) {
290 $value['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($value['participant_role']));
291 }
292 else {
293 $value['role_id'] = $value['participant_role'];
294 }
295 }
296
297 //need to send mail when status change
298 $statusChange = FALSE;
299 $relatedStatusChange = FALSE;
300 if (!empty($value['participant_status'])) {
301 $value['status_id'] = $value['participant_status'];
302 $fromStatusId = CRM_Utils_Array::value($key, $this->_fromStatusIds);
303 if (!$fromStatusId) {
304 $fromStatusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $key, 'status_id');
305 }
306
307 if ($fromStatusId != $value['status_id']) {
308 $relatedStatusChange = TRUE;
309 }
310 if ($statusClasses[$fromStatusId] != $statusClasses[$value['status_id']]) {
311 $statusChange = TRUE;
312 }
313 }
314
315 unset($value['participant_status']);
316
317 civicrm_api3('Participant', 'create', $value);
318
319 //need to trigger mails when we change status
320 if ($statusChange) {
321 CRM_Event_BAO_Participant::transitionParticipants(array($key), $value['status_id'], $fromStatusId);
322 }
323 if ($relatedStatusChange) {
324 //update related contribution status, CRM-4395
325 self::updatePendingOnlineContribution($key, $value['status_id']);
326 }
327 }
328 CRM_Core_Session::setStatus(ts('The updates have been saved.'), ts('Saved'), 'success');
329 }
330 else {
331 CRM_Core_Session::setStatus(ts('No updates have been saved.'), ts('Not Saved'), 'alert');
332 }
333 }
334
335 /**
336 * @param int $participantId
337 * @param int $statusId
338 *
339 * @return Ambigous|void
340 */
341 public static function updatePendingOnlineContribution($participantId, $statusId) {
342 if (!$participantId || !$statusId) {
343 return NULL;
344 }
345
346 $contributionId = CRM_Contribute_BAO_Contribution::checkOnlinePendingContribution($participantId,
347 'Event'
348 );
349 if (!$contributionId) {
350 return;
351 }
352
353 //status rules.
354 //1. participant - positive => contribution - completed.
355 //2. participant - negative => contribution - cancelled.
356
357 $positiveStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Positive'");
358 $negativeStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
359 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
360
361 $contributionStatusId = NULL;
362 if (array_key_exists($statusId, $positiveStatuses)) {
363 $contributionStatusId = array_search('Completed', $contributionStatuses);
364 }
365 if (array_key_exists($statusId, $negativeStatuses)) {
366 $contributionStatusId = array_search('Cancelled', $contributionStatuses);
367 }
368
369 if (!$contributionStatusId) {
370 return;
371 }
372
373 $params = array(
374 'component_id' => $participantId,
375 'componentName' => 'Event',
376 'contribution_id' => $contributionId,
377 'contribution_status_id' => $contributionStatusId,
378 'IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved' => 1,
379 );
380
381 //change related contribution status.
382 $updatedStatusId = self::updateContributionStatus($params);
383
384 return $updatedStatusId;
385 }
386
387 /**
388 * Update contribution status.
389 *
390 * @deprecated
391 * This is only called from one place in the code &
392 * it is unclear whether it is a function on the way in or on the way out
393 *
394 * @param array $params
395 *
396 * @return NULL|int
397 */
398 public static function updateContributionStatus($params) {
399 // get minimum required values.
400 $statusId = CRM_Utils_Array::value('contribution_status_id', $params);
401 $componentId = CRM_Utils_Array::value('component_id', $params);
402 $componentName = CRM_Utils_Array::value('componentName', $params);
403 $contributionId = CRM_Utils_Array::value('contribution_id', $params);
404
405 if (!$contributionId || !$componentId || !$componentName || !$statusId) {
406 return NULL;
407 }
408
409 $input = $ids = $objects = array();
410
411 //get the required ids.
412 $ids['contribution'] = $contributionId;
413
414 if (!$ids['contact'] = CRM_Utils_Array::value('contact_id', $params)) {
415 $ids['contact'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
416 $contributionId,
417 'contact_id'
418 );
419 }
420
421 if ($componentName == 'Event') {
422 $name = 'event';
423 $ids['participant'] = $componentId;
424
425 if (!$ids['event'] = CRM_Utils_Array::value('event_id', $params)) {
426 $ids['event'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
427 $componentId,
428 'event_id'
429 );
430 }
431 }
432
433 if ($componentName == 'Membership') {
434 $name = 'contribute';
435 $ids['membership'] = $componentId;
436 }
437 $ids['contributionPage'] = NULL;
438 $ids['contributionRecur'] = NULL;
439 $input['component'] = $name;
440
441 $baseIPN = new CRM_Core_Payment_BaseIPN();
442 $transaction = new CRM_Core_Transaction();
443
444 // reset template values.
445 $template = CRM_Core_Smarty::singleton();
446 $template->clearTemplateVars();
447
448 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
449 CRM_Core_Error::fatal();
450 }
451
452 $contribution = &$objects['contribution'];
453
454 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
455 'labelColumn' => 'name',
456 'flip' => 1,
457 ));
458 $input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'] = CRM_Utils_Array::value('IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved', $params);
459 if ($statusId == $contributionStatuses['Cancelled']) {
460 $baseIPN->cancelled($objects, $transaction, $input);
461 $transaction->commit();
462 return $statusId;
463 }
464 elseif ($statusId == $contributionStatuses['Failed']) {
465 $baseIPN->failed($objects, $transaction, $input);
466 $transaction->commit();
467 return $statusId;
468 }
469
470 // status is not pending
471 if ($contribution->contribution_status_id != $contributionStatuses['Pending']) {
472 $transaction->commit();
473 return;
474 }
475
476 //set values for ipn code.
477 foreach (array(
478 'fee_amount',
479 'check_number',
480 'payment_instrument_id',
481 ) as $field) {
482 if (!$input[$field] = CRM_Utils_Array::value($field, $params)) {
483 $input[$field] = $contribution->$field;
484 }
485 }
486 if (!$input['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params)) {
487 $input['trxn_id'] = $contribution->invoice_id;
488 }
489 if (!$input['amount'] = CRM_Utils_Array::value('total_amount', $params)) {
490 $input['amount'] = $contribution->total_amount;
491 }
492 $input['is_test'] = $contribution->is_test;
493 $input['net_amount'] = $contribution->net_amount;
494 if (!empty($input['fee_amount']) && !empty($input['amount'])) {
495 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
496 }
497
498 //complete the contribution.
499 // @todo use the api - ie civicrm_api3('Contribution', 'completetransaction', $input);
500 // as this method is not preferred / supported.
501 $baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
502
503 // reset template values before processing next transactions
504 $template->clearTemplateVars();
505
506 return $statusId;
507 }
508
509 /**
510 * Assign the minimal set of variables to the template.
511 */
512 public function assignToTemplate() {
513 $notifyingStatuses = array('Pending from waitlist', 'Pending from approval', 'Expired', 'Cancelled');
514 $notifyingStatuses = array_intersect($notifyingStatuses, CRM_Event_PseudoConstant::participantStatus());
515 $this->assign('status', TRUE);
516 if (!empty($notifyingStatuses)) {
517 $s = '<em>' . implode('</em>, <em>', $notifyingStatuses) . '</em>';
518 $this->assign('notifyingStatuses', $s);
519 }
520 }
521
522 }