Merge pull request #23974 from colemanw/filterFieldsAfform
[civicrm-core.git] / CRM / Event / Form / Participant.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 * Back office participant form.
14 *
15 * @package CRM
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 */
18
19 /**
20 * Back office participant form.
21 */
22 class CRM_Event_Form_Participant extends CRM_Contribute_Form_AbstractEditPayment {
23
24 /**
25 * Participant ID - use getParticipantID.
26 *
27 * @var int
28 */
29 public $_pId;
30
31 /**
32 * ID of discount record.
33 *
34 * @var int
35 */
36 public $_discountId;
37
38 public $useLivePageJS = TRUE;
39
40 /**
41 * The values for the contribution db object.
42 *
43 * @var array
44 */
45 public $_values;
46
47 /**
48 * The values for the quickconfig for priceset.
49 *
50 * @var bool
51 */
52 public $_quickConfig = NULL;
53
54 /**
55 * Price Set ID, if the new price set method is used
56 *
57 * @var int
58 */
59 public $_priceSetId;
60
61 /**
62 * Array of fields for the price set.
63 *
64 * @var array
65 */
66 public $_priceSet;
67
68 /**
69 * The id of the participation that we are processing.
70 *
71 * @var int
72 */
73 public $_id;
74
75 /**
76 * The id of the note.
77 *
78 * @var int
79 */
80 protected $_noteId = NULL;
81
82 /**
83 *
84 * Use parent $this->contactID
85 *
86 * The id of the contact associated with this participation.
87 *
88 * @var int
89 * @deprecated
90 */
91 public $_contactId;
92
93 /**
94 * Array of event values.
95 *
96 * @var array
97 */
98 protected $_event;
99
100 /**
101 * Are we operating in "single mode", i.e. adding / editing only
102 * one participant record, or is this a batch add operation.
103 *
104 * Note the goal is to disentangle all the non-single stuff
105 * to CRM_Event_Form_Task_Register and discontinue this param.
106 *
107 * @var bool
108 */
109 public $_single = TRUE;
110
111 /**
112 * If event is paid or unpaid.
113 *
114 * @var bool
115 */
116 public $_isPaidEvent;
117
118 /**
119 * Page action.
120 *
121 * @var int
122 */
123 public $_action;
124
125 /**
126 * Event Type Id.
127 *
128 * @var int
129 */
130 protected $_eventTypeId = NULL;
131
132 /**
133 * Participant status Id.
134 *
135 * @var int
136 */
137 protected $_statusId = NULL;
138
139 /**
140 * Cache all the participant statuses.
141 *
142 * @var array
143 */
144 protected $_participantStatuses;
145
146 /**
147 * Participant mode.
148 *
149 * @var string
150 */
151 public $_mode = NULL;
152
153 /**
154 * Event ID preselect.
155 *
156 * @var int
157 */
158 public $_eID = NULL;
159
160 /**
161 * Line Item for Price Set.
162 *
163 * @var array
164 */
165 public $_lineItem = NULL;
166
167 /**
168 * Contribution mode for event registration for offline mode.
169 *
170 * @var string
171 * @deprecated
172 */
173 public $_contributeMode = 'direct';
174
175 public $_online;
176
177 /**
178 * Store id of role custom data type ( option value )
179 *
180 * @var int
181 */
182 protected $_roleCustomDataTypeID;
183
184 /**
185 * Store id of event Name custom data type ( option value)
186 *
187 * @var int
188 */
189 protected $_eventNameCustomDataTypeID;
190
191 /**
192 * Selected discount id.
193 *
194 * @var int
195 */
196 public $_originalDiscountId = NULL;
197
198 /**
199 * Event id.
200 *
201 * @var int
202 */
203 public $_eventId = NULL;
204
205 /**
206 * Id of payment, if any
207 *
208 * @var int
209 */
210 public $_paymentId = NULL;
211
212 /**
213 * @var null
214 * @todo add explanatory note about this
215 */
216 public $_onlinePendingContributionId = NULL;
217
218 /**
219 * Stored participant record.
220 *
221 * @var array
222 */
223 protected $participantRecord;
224
225 /**
226 * Params for creating a payment to add to the contribution.
227 *
228 * @var array
229 */
230 protected $createPaymentParams = [];
231
232 /**
233 * Get params to create payments.
234 *
235 * @return array
236 */
237 public function getCreatePaymentParams(): array {
238 return $this->createPaymentParams;
239 }
240
241 /**
242 * Set params to create payments.
243 *
244 * @param array $createPaymentParams
245 */
246 public function setCreatePaymentParams(array $createPaymentParams) {
247 $this->createPaymentParams = $createPaymentParams;
248 }
249
250 /**
251 * Explicitly declare the entity api name.
252 */
253 public function getDefaultEntity() {
254 return 'Participant';
255 }
256
257 /**
258 * Default form context used as part of addField()
259 */
260 public function getDefaultContext() {
261 return 'create';
262 }
263
264 /**
265 * Set variables up before form is built.
266 *
267 * @throws \CRM_Core_Exception
268 * @throws \CiviCRM_API3_Exception
269 */
270 public function preProcess() {
271 parent::preProcess();
272 $this->_showFeeBlock = $_GET['eventId'] ?? NULL;
273 $this->assign('showFeeBlock', FALSE);
274 $this->assign('feeBlockPaid', FALSE);
275
276 // @todo eliminate this duplication.
277 $this->_contactId = $this->_contactID;
278 $this->_eID = CRM_Utils_Request::retrieve('eid', 'Positive', $this);
279 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
280 $this->assign('context', $this->_context);
281
282 if ($this->_contactID) {
283 $this->setPageTitle(ts('Event Registration for %1', [1 => $this->userDisplayName]));
284 }
285 else {
286 $this->setPageTitle(ts('Event Registration'));
287 }
288
289 // check the current path, if search based, then dont get participantID
290 // CRM-5792
291 $path = CRM_Utils_System::currentPath();
292 if (
293 strpos($path, 'civicrm/contact/search') === 0 ||
294 strpos($path, 'civicrm/group/search') === 0
295 ) {
296 $this->_id = NULL;
297 }
298 else {
299 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
300 }
301
302 if ($this->_id) {
303 $this->assign('participantId', $this->_id);
304
305 $this->_paymentId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
306 $this->_id, 'id', 'participant_id'
307 );
308
309 $this->assign('hasPayment', $this->_paymentId);
310 $this->assign('componentId', $this->_id);
311 $this->assign('component', 'event');
312
313 // CRM-12615 - Get payment information from the primary registration
314 if ((!$this->_paymentId) && ($this->_action == CRM_Core_Action::UPDATE)) {
315 $registered_by_id = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
316 $this->_id, 'registered_by_id', 'id'
317 );
318 if ($registered_by_id) {
319 $this->_paymentId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
320 $registered_by_id, 'id', 'participant_id'
321 );
322 $this->assign('registeredByParticipantId', $registered_by_id);
323 }
324 }
325 }
326 $this->setCustomDataTypes();
327
328 $this->assign('participantMode', $this->_mode);
329
330 $this->assign('showFeeBlock', $this->_showFeeBlock);
331 if ($this->_showFeeBlock) {
332 $isMonetary = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_showFeeBlock, 'is_monetary');
333 if ($isMonetary) {
334 $this->assign('feeBlockPaid', TRUE);
335 }
336 return CRM_Event_Form_EventFees::preProcess($this);
337 }
338
339 $this->assignUrlPath();
340
341 $this->assign('single', $this->_single);
342
343 if (!$this->_id) {
344 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
345 }
346 $this->assign('action', $this->_action);
347
348 // check for edit permission
349 if (!CRM_Core_Permission::checkActionPermission('CiviEvent', $this->_action)) {
350 CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
351 }
352
353 if ($this->_action & CRM_Core_Action::DELETE) {
354 // check delete permission for contribution
355 if ($this->_id && $this->_paymentId && !CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
356 CRM_Core_Error::statusBounce(ts("This Participant is linked to a contribution. You must have 'delete in CiviContribute' permission in order to delete this record."));
357 }
358 return;
359 }
360
361 // assign participant id to the template
362 $this->assign('participantId', $this->_id);
363
364 // when fee amount is included in form
365 if (!empty($_POST['hidden_feeblock']) || !empty($_POST['send_receipt'])) {
366 if ($this->_submitValues['event_id']) {
367 $this->_eventId = $this->_submitValues['event_id'];
368 }
369 CRM_Event_Form_EventFees::preProcess($this);
370 $this->buildEventFeeForm($this);
371 CRM_Event_Form_EventFees::setDefaultValues($this);
372 }
373
374 // when custom data is included in this page
375 if (!empty($_POST['hidden_custom'])) {
376 $eventId = (int) ($_POST['event_id'] ?? 0);
377 // Custom data of type participant role
378 // Note: Some earlier commits imply $_POST['role_id'] could be a comma separated string,
379 // not sure if that ever really happens
380 if (!empty($_POST['role_id'])) {
381 foreach ($_POST['role_id'] as $roleID) {
382 CRM_Custom_Form_CustomData::preProcess($this, $this->_roleCustomDataTypeID, $roleID, 1, 'Participant', $this->_id);
383 CRM_Custom_Form_CustomData::buildQuickForm($this);
384 CRM_Custom_Form_CustomData::setDefaultValues($this);
385 }
386 }
387
388 //custom data of type participant event
389 CRM_Custom_Form_CustomData::preProcess($this, $this->_eventNameCustomDataTypeID, $eventId, 1, 'Participant', $this->_id);
390 CRM_Custom_Form_CustomData::buildQuickForm($this);
391 CRM_Custom_Form_CustomData::setDefaultValues($this);
392
393 // custom data of type participant event type
394 $eventTypeId = NULL;
395 if ($eventId) {
396 $eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'event_type_id', 'id');
397 }
398 CRM_Custom_Form_CustomData::preProcess($this, $this->_eventTypeCustomDataTypeID, $eventTypeId,
399 1, 'Participant', $this->_id
400 );
401 CRM_Custom_Form_CustomData::buildQuickForm($this);
402 CRM_Custom_Form_CustomData::setDefaultValues($this);
403
404 //custom data of type participant, ( we 'null' to reset subType and subName)
405 CRM_Custom_Form_CustomData::preProcess($this, 'null', 'null', 1, 'Participant', $this->_id);
406 CRM_Custom_Form_CustomData::buildQuickForm($this);
407 CRM_Custom_Form_CustomData::setDefaultValues($this);
408 }
409
410 // CRM-4395, get the online pending contribution id.
411 $this->_onlinePendingContributionId = NULL;
412 if (!$this->_mode && $this->_id && ($this->_action & CRM_Core_Action::UPDATE)) {
413 $this->_onlinePendingContributionId = CRM_Contribute_BAO_Contribution::checkOnlinePendingContribution($this->_id,
414 'Event'
415 );
416 }
417 $this->set('onlinePendingContributionId', $this->_onlinePendingContributionId);
418 }
419
420 /**
421 * This function sets the default values for the form in edit/view mode
422 * the default values are retrieved from the database
423 *
424 * @return array
425 * @throws \CRM_Core_Exception
426 */
427 public function setDefaultValues() {
428 if ($this->_showFeeBlock) {
429 return CRM_Event_Form_EventFees::setDefaultValues($this);
430 }
431
432 $defaults = [];
433
434 if ($this->_action & CRM_Core_Action::DELETE) {
435 return $defaults;
436 }
437
438 if ($this->_id) {
439 $ids = [];
440 $params = ['id' => $this->_id];
441
442 CRM_Event_BAO_Participant::getValues($params, $defaults, $ids);
443 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
444 if ($defaults[$this->_id]['role_id']) {
445 $roleIDs = explode($sep, $defaults[$this->_id]['role_id']);
446 }
447 $this->_contactId = $defaults[$this->_id]['contact_id'];
448 $this->_statusId = $defaults[$this->_id]['participant_status_id'];
449
450 //set defaults for note
451 $noteDetails = CRM_Core_BAO_Note::getNote($this->_id, 'civicrm_participant');
452 $defaults[$this->_id]['note'] = array_pop($noteDetails);
453
454 // Check if this is a primaryParticipant (registered for others) and retrieve additional participants if true (CRM-4859)
455 if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
456 $this->assign('additionalParticipants', CRM_Event_BAO_Participant::getAdditionalParticipants($this->_id));
457 }
458
459 // Get registered_by contact ID and display_name if participant was registered by someone else (CRM-4859)
460 if (!empty($defaults[$this->_id]['participant_registered_by_id'])) {
461 $registered_by_contact_id = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
462 $defaults[$this->_id]['participant_registered_by_id'],
463 'contact_id', 'id'
464 );
465 $this->assign('participant_registered_by_id', $defaults[$this->_id]['participant_registered_by_id']);
466 $this->assign('registered_by_contact_id', $registered_by_contact_id);
467 $this->assign('registered_by_display_name', CRM_Contact_BAO_Contact::displayName($registered_by_contact_id));
468 }
469 }
470 elseif ($this->_contactID) {
471 $defaults[$this->_id]['contact_id'] = $this->_contactID;
472 }
473
474 //setting default register date
475 if ($this->_action == CRM_Core_Action::ADD) {
476 $statuses = array_flip(CRM_Event_PseudoConstant::participantStatus());
477 $defaults[$this->_id]['status_id'] = $statuses['Registered'] ?? NULL;
478 if (!empty($defaults[$this->_id]['event_id'])) {
479 $financialTypeID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
480 $defaults[$this->_id]['event_id'],
481 'financial_type_id'
482 );
483 if ($financialTypeID) {
484 $defaults[$this->_id]['financial_type_id'] = $financialTypeID;
485 }
486 }
487
488 if ($this->_mode) {
489 $fields["email-{$this->_bltID}"] = 1;
490 $fields['email-Primary'] = 1;
491
492 if ($this->_contactId) {
493 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_contactId, $fields, $defaults);
494 }
495
496 if (empty($defaults["email-{$this->_bltID}"]) &&
497 !empty($defaults['email-Primary'])
498 ) {
499 $defaults[$this->_id]["email-{$this->_bltID}"] = $defaults['email-Primary'];
500 }
501 }
502
503 $submittedRole = $this->getElementValue('role_id');
504 if (!empty($submittedRole[0])) {
505 $roleID = $submittedRole[0];
506 }
507 $submittedEvent = $this->getElementValue('event_id');
508 if (!empty($submittedEvent[0])) {
509 $eventID = $submittedEvent[0];
510 }
511 $defaults[$this->_id]['register_date'] = date('Y-m-d H:i:s');
512 }
513 else {
514 $defaults[$this->_id]['record_contribution'] = 0;
515
516 if ($defaults[$this->_id]['participant_is_pay_later']) {
517 $this->assign('participant_is_pay_later', TRUE);
518 }
519
520 $this->assign('participant_status_id', $defaults[$this->_id]['participant_status_id']);
521 $eventID = $defaults[$this->_id]['event_id'];
522
523 $this->_eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventID, 'event_type_id', 'id');
524
525 $this->_discountId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'discount_id');
526 if ($this->_discountId) {
527 $this->set('discountId', $this->_discountId);
528 }
529 }
530
531 //assign event and role id, this is needed for Custom data building
532 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
533 if (!empty($defaults[$this->_id]['participant_role_id'])) {
534 $roleIDs = explode($sep, $defaults[$this->_id]['participant_role_id']);
535 }
536 if (isset($_POST['event_id'])) {
537 $eventID = $_POST['event_id'];
538 }
539
540 if ($this->_eID) {
541 $eventID = $this->_eID;
542 //@todo - rationalise the $this->_eID with $POST['event_id'], $this->_eid is set when eid=x is in the url
543 $roleID = CRM_Core_DAO::getFieldValue(
544 'CRM_Event_DAO_Event',
545 $this->_eID,
546 'default_role_id'
547 );
548 if (empty($roleIDs)) {
549 $roleIDs = (array) $defaults[$this->_id]['participant_role_id'] = $roleID;
550 }
551 $defaults[$this->_id]['event_id'] = $eventID;
552 }
553 if (!empty($eventID)) {
554 $this->_eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventID, 'event_type_id', 'id');
555 }
556 //these should take precedence so we state them last
557 $urlRoleIDS = CRM_Utils_Request::retrieve('roles', 'String');
558 if ($urlRoleIDS) {
559 $roleIDs = explode(',', $urlRoleIDS);
560 }
561 if (isset($roleIDs)) {
562 $defaults[$this->_id]['role_id'] = implode(',', $roleIDs);
563 }
564
565 if (isset($eventID)) {
566 $this->assign('eventID', $eventID);
567 $this->set('eventId', $eventID);
568 }
569
570 if (isset($this->_eventTypeId)) {
571 $this->assign('eventTypeID', $this->_eventTypeId);
572 }
573
574 $this->assign('event_is_test', CRM_Utils_Array::value('event_is_test', $defaults[$this->_id]));
575 return $defaults[$this->_id];
576 }
577
578 /**
579 * Build the form object.
580 *
581 * @return void
582 * @throws \CRM_Core_Exception
583 * @throws \CiviCRM_API3_Exception
584 */
585 public function buildQuickForm() {
586
587 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
588 $partiallyPaidStatusId = array_search('Partially paid', $participantStatuses);
589 $this->assign('partiallyPaidStatusId', $partiallyPaidStatusId);
590
591 if ($this->_showFeeBlock) {
592 return $this->buildEventFeeForm($this);
593 }
594
595 //need to assign custom data type to the template
596 $this->assign('customDataType', 'Participant');
597
598 $this->applyFilter('__ALL__', 'trim');
599
600 if ($this->_action & CRM_Core_Action::DELETE) {
601 if ($this->_single) {
602 $additionalParticipant = count(CRM_Event_BAO_Event::buildCustomProfile($this->_id,
603 NULL,
604 $this->_contactId,
605 FALSE,
606 TRUE
607 )) - 1;
608 if ($additionalParticipant) {
609 $deleteParticipants = [
610 1 => ts('Delete this participant record along with associated participant record(s).'),
611 2 => ts('Delete only this participant record.'),
612 ];
613 $this->addRadio('delete_participant', NULL, $deleteParticipants, NULL, '<br />');
614 $this->setDefaults(['delete_participant' => 1]);
615 $this->assign('additionalParticipant', $additionalParticipant);
616 }
617 }
618 $this->addButtons([
619 [
620 'type' => 'next',
621 'name' => ts('Delete'),
622 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
623 'isDefault' => TRUE,
624 ],
625 [
626 'type' => 'cancel',
627 'name' => ts('Cancel'),
628 ],
629 ]);
630 return;
631 }
632
633 if ($this->_single) {
634 $contactField = $this->addEntityRef('contact_id', ts('Participant'), ['create' => TRUE, 'api' => ['extra' => ['email']]], TRUE);
635 if ($this->_context != 'standalone') {
636 $contactField->freeze();
637 }
638 }
639
640 $eventFieldParams = [
641 'entity' => 'Event',
642 'select' => ['minimumInputLength' => 0],
643 'api' => [
644 'extra' => ['campaign_id', 'default_role_id', 'event_type_id'],
645 ],
646 ];
647
648 if ($this->_mode) {
649 // exclude events which are not monetary when credit card registration is used
650 $eventFieldParams['api']['params']['is_monetary'] = 1;
651 }
652 $this->addPaymentProcessorSelect(TRUE, FALSE, FALSE);
653
654 $element = $this->addEntityRef('event_id', ts('Event'), $eventFieldParams, TRUE);
655
656 //frozen the field fix for CRM-4171
657 if ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
658 if (CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
659 $this->_id, 'contribution_id', 'participant_id'
660 )
661 ) {
662 $element->freeze();
663 }
664 }
665
666 //CRM-7362 --add campaigns.
667 $campaignId = NULL;
668 if ($this->_id) {
669 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'campaign_id');
670 }
671 if (!$campaignId) {
672 $eventId = CRM_Utils_Request::retrieve('eid', 'Positive', $this);
673 if ($eventId) {
674 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'campaign_id');
675 }
676 }
677 CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
678 $this->add('datepicker', 'register_date', ts('Registration Date'), [], TRUE, ['time' => TRUE]);
679
680 if ($this->_id) {
681 $this->assign('entityID', $this->_id);
682 }
683
684 $this->addSelect('role_id', ['multiple' => TRUE, 'class' => 'huge'], TRUE);
685
686 // CRM-4395
687 $checkCancelledJs = ['onchange' => "return sendNotification( );"];
688 $confirmJS = NULL;
689 if ($this->_onlinePendingContributionId) {
690 $cancelledparticipantStatusId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus());
691 $cancelledContributionStatusId = array_search('Cancelled',
692 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
693 );
694 $checkCancelledJs = [
695 'onchange' => "checkCancelled( this.value, {$cancelledparticipantStatusId},{$cancelledContributionStatusId});",
696 ];
697
698 $participantStatusId = array_search('Pending from pay later',
699 CRM_Event_PseudoConstant::participantStatus()
700 );
701 $contributionStatusId = array_search('Completed',
702 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
703 );
704 $confirmJS = ['onclick' => "return confirmStatus( {$participantStatusId}, {$contributionStatusId} );"];
705 }
706
707 // get the participant status names to build special status array which is used to show notification
708 // checkbox below participant status select
709 $participantStatusName = CRM_Event_PseudoConstant::participantStatus();
710 $notificationStatuses = [
711 'Cancelled',
712 'Pending from waitlist',
713 'Pending from approval',
714 'Expired',
715 ];
716
717 // get the required status and then implode only ids
718 $notificationStatusIds = implode(',', array_keys(array_intersect($participantStatusName, $notificationStatuses)));
719 $this->assign('notificationStatusIds', $notificationStatusIds);
720
721 $this->_participantStatuses = $statusOptions = CRM_Event_BAO_Participant::buildOptions('status_id', 'create');
722
723 // Only show refund status when editing
724 if ($this->_action & CRM_Core_Action::ADD) {
725 $pendingRefundStatusId = array_search('Pending refund', $participantStatusName);
726 if ($pendingRefundStatusId) {
727 unset($statusOptions[$pendingRefundStatusId]);
728 }
729 }
730
731 $this->addSelect('status_id', $checkCancelledJs + [
732 'options' => $statusOptions,
733 'option_url' => 'civicrm/admin/participant_status',
734 ], TRUE);
735
736 $this->addElement('checkbox', 'is_notify', ts('Send Notification'), NULL);
737
738 $this->addField('source', ['entity' => 'Participant', 'name' => 'source']);
739 $noteAttributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Note');
740 $this->add('textarea', 'note', ts('Notes'), $noteAttributes['note']);
741
742 $buttons[] = [
743 'type' => 'upload',
744 'name' => ts('Save'),
745 'isDefault' => TRUE,
746 'js' => $confirmJS,
747 ];
748
749 $path = CRM_Utils_System::currentPath();
750 $excludeForPaths = [
751 'civicrm/contact/search',
752 'civicrm/group/search',
753 ];
754 if (!in_array($path, $excludeForPaths)) {
755 $buttons[] = [
756 'type' => 'upload',
757 'name' => ts('Save and New'),
758 'subName' => 'new',
759 'js' => $confirmJS,
760 ];
761 }
762
763 $buttons[] = [
764 'type' => 'cancel',
765 'name' => ts('Cancel'),
766 ];
767
768 $this->addButtons($buttons);
769 if ($this->_action == CRM_Core_Action::VIEW) {
770 $this->freeze();
771 }
772 }
773
774 /**
775 * Add local and global form rules.
776 *
777 * @return void
778 */
779 public function addRules() {
780 $this->addFormRule(['CRM_Event_Form_Participant', 'formRule'], $this);
781 }
782
783 /**
784 * Global validation rules for the form.
785 *
786 * @param array $values
787 * Posted values of the form.
788 * @param $files
789 * @param self $self
790 *
791 * @return array
792 * list of errors to be posted back to the form
793 */
794 public static function formRule($values, $files, $self) {
795 // If $values['_qf_Participant_next'] is Delete or
796 // $values['event_id'] is empty, then return
797 // instead of proceeding further.
798
799 if ((($values['_qf_Participant_next'] ?? NULL) === 'Delete') ||
800 empty($values['event_id'])
801 ) {
802 return TRUE;
803 }
804
805 $errorMsg = [];
806
807 if (!empty($values['payment_processor_id'])) {
808 // make sure that payment instrument values (e.g. credit card number and cvv) are valid
809 CRM_Core_Payment_Form::validatePaymentInstrument($values['payment_processor_id'], $values, $errorMsg, NULL);
810 }
811
812 if (!empty($values['record_contribution'])) {
813 if (empty($values['financial_type_id'])) {
814 $errorMsg['financial_type_id'] = ts('Please enter the associated Financial Type');
815 }
816 if (empty($values['payment_instrument_id'])) {
817 $errorMsg['payment_instrument_id'] = ts('Payment Method is a required field.');
818 }
819 if (!empty($values['priceSetId'])) {
820 CRM_Price_BAO_PriceField::priceSetValidation($values['priceSetId'], $values, $errorMsg);
821 }
822 }
823
824 // validate contribution status for 'Failed'.
825 if ($self->_onlinePendingContributionId && !empty($values['record_contribution']) &&
826 (CRM_Utils_Array::value('contribution_status_id', $values) ==
827 array_search('Failed', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))
828 )
829 ) {
830 $errorMsg['contribution_status_id'] = ts('Please select a valid payment status before updating.');
831 }
832
833 // do the amount validations.
834 //skip for update mode since amount is freeze, CRM-6052
835 if ((!$self->_id && empty($values['total_amount']) &&
836 empty($self->_values['line_items'])
837 ) ||
838 ($self->_id && !$self->_paymentId && isset($self->_values['line_items']) && is_array($self->_values['line_items']))
839 ) {
840 if ($priceSetId = CRM_Utils_Array::value('priceSetId', $values)) {
841 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $values, $errorMsg, TRUE);
842 }
843 }
844 // For single additions - show validation error if the contact has already been registered
845 // for this event.
846 if ($self->_single && ($self->_action & CRM_Core_Action::ADD)) {
847 if ($self->_context == 'standalone') {
848 $contactId = $values['contact_id'] ?? NULL;
849 }
850 else {
851 $contactId = $self->_contactId;
852 }
853
854 $eventId = $values['event_id'] ?? NULL;
855
856 $event = new CRM_Event_DAO_Event();
857 $event->id = $eventId;
858 $event->find(TRUE);
859
860 if (!$event->allow_same_participant_emails && !empty($contactId) && !empty($eventId)) {
861 $cancelledStatusID = CRM_Core_PseudoConstant::getKey('CRM_Event_BAO_Participant', 'status_id', 'Cancelled');
862 $dupeCheck = new CRM_Event_BAO_Participant();
863 $dupeCheck->contact_id = $contactId;
864 $dupeCheck->event_id = $eventId;
865 $dupeCheck->whereAdd("status_id != {$cancelledStatusID} ");
866 $dupeCheck->find(TRUE);
867 if (!empty($dupeCheck->id)) {
868 $errorMsg['event_id'] = ts("This contact has already been assigned to this event.");
869 }
870 }
871 }
872 return CRM_Utils_Array::crmIsEmptyArray($errorMsg) ? TRUE : $errorMsg;
873 }
874
875 /**
876 * Process the form submission.
877 */
878 public function postProcess() {
879 // get the submitted form values.
880 $params = $this->controller->exportValues($this->_name);
881
882 if ($this->_action & CRM_Core_Action::DELETE) {
883 if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
884 $additionalId = (CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id));
885 $participantLinks = (CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId));
886 }
887 if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
888 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
889 foreach ($additionalIds as $value) {
890 CRM_Event_BAO_Participant::deleteParticipant($value);
891 }
892 }
893 CRM_Event_BAO_Participant::deleteParticipant($this->_id);
894 CRM_Core_Session::setStatus(ts('Selected participant was deleted successfully.'), ts('Record Deleted'), 'success');
895 if (!empty($participantLinks)) {
896 $status = ts('The following participants no longer have an event fee recorded. You can edit their registration and record a replacement contribution by clicking the links below:') . '<br/>' . $participantLinks;
897 CRM_Core_Session::setStatus($status, ts('Group Payment Deleted'));
898 }
899 return;
900 }
901 // When adding a single contact, the formRule prevents you from adding duplicates
902 // (See above in formRule()). When adding more than one contact, the duplicates are
903 // removed automatically and the user receives one notification.
904 if ($this->_action & CRM_Core_Action::ADD) {
905 $event_id = $this->_eventId;
906 if (empty($event_id) && !empty($params['event_id'])) {
907 $event_id = $params['event_id'];
908 }
909 if (!$this->_single && !empty($event_id)) {
910 $duplicateContacts = 0;
911 foreach ($this->_contactIds as $k => $dupeCheckContactId) {
912 // Eliminate contacts that have already been assigned to this event.
913 $dupeCheck = new CRM_Event_BAO_Participant();
914 $dupeCheck->contact_id = $dupeCheckContactId;
915 $dupeCheck->event_id = $event_id;
916 $dupeCheck->find(TRUE);
917 if (!empty($dupeCheck->id)) {
918 $duplicateContacts++;
919 unset($this->_contactIds[$k]);
920 }
921 }
922 if ($duplicateContacts > 0) {
923 $msg = ts(
924 "%1 contacts have already been assigned to this event. They were not added a second time.",
925 [1 => $duplicateContacts]
926 );
927 CRM_Core_Session::setStatus($msg);
928 }
929 if (count($this->_contactIds) == 0) {
930 CRM_Core_Session::setStatus(ts("No participants were added."));
931 return;
932 }
933 // We have to re-key $this->_contactIds so each contact has the same
934 // key as their corresponding record in the $participants array that
935 // will be created below.
936 $this->_contactIds = array_values($this->_contactIds);
937 }
938 }
939
940 $statusMsg = $this->submit($params);
941 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
942 $session = CRM_Core_Session::singleton();
943 $buttonName = $this->controller->getButtonName();
944 if ($this->_context == 'standalone') {
945 if ($buttonName == $this->getButtonName('upload', 'new')) {
946 $urlParams = 'reset=1&action=add&context=standalone';
947 if ($this->_mode) {
948 $urlParams .= '&mode=' . $this->_mode;
949 }
950 if ($this->_eID) {
951 $urlParams .= '&eid=' . $this->_eID;
952 }
953 $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
954 }
955 else {
956 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
957 "reset=1&cid={$this->_contactId}&selectedChild=participant"
958 ));
959 }
960 }
961 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
962 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant',
963 "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"
964 ));
965 }
966 }
967
968 /**
969 * Submit form.
970 *
971 * @param array $params
972 *
973 * @return string
974 * @throws \CRM_Core_Exception
975 * @throws \CiviCRM_API3_Exception
976 */
977 public function submit($params) {
978 if ($this->_mode && !$this->_isPaidEvent) {
979 CRM_Core_Error::statusBounce(ts('Selected Event is not Paid Event '));
980 }
981 $participantStatus = CRM_Event_PseudoConstant::participantStatus();
982 // set the contact, when contact is selected
983 if (!empty($params['contact_id'])) {
984 $this->_contactID = $this->_contactId = $params['contact_id'];
985 }
986 if (!$this->_priceSetId && $this->_isPaidEvent) {
987 CRM_Core_Error::deprecatedFunctionWarning('this should never be true, handling to be removed');
988 }
989 if ($this->_priceSetId && $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
990 $this->_quickConfig = $isQuickConfig;
991 }
992
993 if ($this->_id) {
994 $params['id'] = $this->_id;
995 }
996
997 $config = CRM_Core_Config::singleton();
998 if (isset($params['total_amount'])) {
999 $params['total_amount'] = CRM_Utils_Rule::cleanMoney($params['total_amount']);
1000 }
1001 if ($this->_isPaidEvent) {
1002 list($contributionParams, $lineItem, $additionalParticipantDetails, $params) = $this->preparePaidEventProcessing($params);
1003 }
1004
1005 $this->_params = $params;
1006 parent::beginPostProcess();
1007 $amountOwed = NULL;
1008 if (isset($params['amount'])) {
1009 $amountOwed = $params['amount'];
1010 unset($params['amount']);
1011 }
1012 $params['contact_id'] = $this->_contactId;
1013
1014 // overwrite actual payment amount if entered
1015 if (!empty($params['total_amount'])) {
1016 $contributionParams['total_amount'] = $params['total_amount'] ?? NULL;
1017 }
1018
1019 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1020 $userName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
1021
1022 if ($this->_contactId) {
1023 list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
1024 }
1025
1026 //modify params according to parameter used in create
1027 //participant method (addParticipant)
1028 $this->_params['participant_status_id'] = $params['status_id'];
1029 $this->_params['participant_role_id'] = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']);
1030 $roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
1031
1032 $now = date('YmdHis');
1033
1034 if ($this->_mode) {
1035 // set source if not set
1036 if (empty($params['source'])) {
1037 $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', [
1038 1 => $userName,
1039 2 => $this->getEventValue('title'),
1040 ]);
1041 }
1042 else {
1043 $this->_params['participant_source'] = $params['source'];
1044 }
1045 $this->_params['description'] = $this->_params['participant_source'];
1046
1047 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
1048 $this->_mode
1049 );
1050 $fields = [];
1051
1052 // set email for primary location.
1053 $fields['email-Primary'] = 1;
1054 $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
1055
1056 // now set the values for the billing location.
1057 foreach ($this->_fields as $name => $dontCare) {
1058 $fields[$name] = 1;
1059 }
1060
1061 // also add location name to the array
1062 $params["address_name-{$this->_bltID}"]
1063 = CRM_Utils_Array::value('billing_first_name', $params) . ' ' .
1064 CRM_Utils_Array::value('billing_middle_name', $params) . ' ' .
1065 CRM_Utils_Array::value('billing_last_name', $params);
1066
1067 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1068 $fields["address_name-{$this->_bltID}"] = 1;
1069 $fields["email-{$this->_bltID}"] = 1;
1070 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
1071
1072 $nameFields = ['first_name', 'middle_name', 'last_name'];
1073
1074 foreach ($nameFields as $name) {
1075 $fields[$name] = 1;
1076 if (array_key_exists("billing_$name", $params)) {
1077 $params[$name] = $params["billing_{$name}"];
1078 $params['preserveDBName'] = TRUE;
1079 }
1080 }
1081 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
1082 }
1083
1084 if (!empty($this->_params['participant_role_id'])) {
1085 $customFieldsRole = [];
1086 foreach ($this->_params['participant_role_id'] as $roleKey) {
1087 $customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant',
1088 FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
1089 }
1090 $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant',
1091 FALSE,
1092 FALSE,
1093 CRM_Utils_Array::value('event_id', $params),
1094 $this->_eventNameCustomDataTypeID
1095 );
1096 $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant',
1097 FALSE,
1098 FALSE,
1099 $this->_eventTypeId,
1100 $this->_eventTypeCustomDataTypeID
1101 );
1102 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole,
1103 CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE)
1104 );
1105 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
1106 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
1107
1108 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_id, $this->getDefaultEntity());
1109 }
1110
1111 //do cleanup line items if participant edit the Event Fee.
1112 if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) {
1113 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant');
1114 }
1115
1116 if ($this->_mode) {
1117 // add all the additional payment params we need
1118 $this->_params = $this->prepareParamsForPaymentProcessor($this->_params);
1119 $this->_params['amount'] = $params['fee_amount'];
1120 $this->_params['amount_level'] = $params['amount_level'];
1121 $this->_params['currencyID'] = $config->defaultCurrency;
1122 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1123
1124 // at this point we've created a contact and stored its address etc
1125 // all the payment processors expect the name and address to be in the
1126 // so we copy stuff over to first_name etc.
1127 $paymentParams = $this->_params;
1128 if (!empty($this->_params['send_receipt'])) {
1129 $paymentParams['email'] = $this->_contributorEmail;
1130 }
1131
1132 // The only reason for merging in the 'contact_id' rather than ensuring it is set
1133 // is that this patch is being done around the time of the stable release
1134 // so more conservative approach is called for.
1135 // In fact the use of $params and $this->_params & $this->_contactId vs $contactID
1136 // needs rationalising.
1137 $mapParams = array_merge(['contact_id' => $contactID], $this->_params);
1138 CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
1139
1140 $payment = $this->_paymentProcessor['object'];
1141
1142 // CRM-15622: fix for incorrect contribution.fee_amount
1143 $paymentParams['fee_amount'] = NULL;
1144 try {
1145 $result = $payment->doPayment($paymentParams);
1146 }
1147 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
1148 // @todo un comment the following line out when we are creating a contribution before we get to this point
1149 // see dev/financial#53 about ensuring we create a pending contribution before we try processing payment
1150 // CRM_Contribute_BAO_Contribution::failPayment($contributionID);
1151 CRM_Core_Session::singleton()->setStatus($e->getMessage());
1152 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant',
1153 "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"
1154 ));
1155 }
1156
1157 if ($result) {
1158 $this->_params = array_merge($this->_params, $result);
1159 }
1160
1161 $this->_params['receive_date'] = $now;
1162
1163 if (!empty($this->_params['send_receipt'])) {
1164 $this->_params['receipt_date'] = $now;
1165 }
1166 else {
1167 $this->_params['receipt_date'] = NULL;
1168 }
1169
1170 $this->set('params', $this->_params);
1171 $this->assign('trxn_id', $result['trxn_id']);
1172 $this->assign('receive_date', $this->_params['receive_date']);
1173
1174 //add contribution record
1175 $this->_params['financial_type_id']
1176 = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id');
1177 $this->_params['mode'] = $this->_mode;
1178
1179 //add contribution record
1180 $contributions[] = $contribution = $this->processContribution(
1181 $this, $this->_params,
1182 $result, $contactID,
1183 FALSE,
1184 $this->_paymentProcessor
1185 );
1186
1187 // add participant record
1188 $participants = [];
1189 if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
1190 $this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR,
1191 $this->_params['role_id']
1192 );
1193 }
1194
1195 //CRM-15372 patch to fix fee amount replacing amount
1196 $this->_params['fee_amount'] = $this->_params['amount'];
1197
1198 $participants[] = $this->addParticipant($this, $this->_params, $contactID);
1199
1200 //add custom data for participant
1201 CRM_Core_BAO_CustomValueTable::postProcess($this->_params,
1202 'civicrm_participant',
1203 $participants[0]->id,
1204 'Participant'
1205 );
1206
1207 // Add participant payment
1208 $participantPaymentParams = [
1209 'participant_id' => $participants[0]->id,
1210 'contribution_id' => $contribution->id,
1211 ];
1212 civicrm_api3('ParticipantPayment', 'create', $participantPaymentParams);
1213
1214 $this->_contactIds[] = $this->_contactId;
1215 }
1216 else {
1217 if ($this->_single) {
1218 $this->_contactIds[] = $this->_contactId;
1219 }
1220 $participants = [];
1221 foreach ($this->_contactIds as $contactID) {
1222 $commonParams = $params;
1223 $commonParams['contact_id'] = $contactID;
1224 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
1225 }
1226
1227 $contributions = [];
1228 if (!empty($params['record_contribution'])) {
1229 if (!empty($params['id'])) {
1230 if ($this->_onlinePendingContributionId) {
1231 $contributionParams['id'] = $this->_onlinePendingContributionId;
1232 }
1233 else {
1234 $contributionParams['id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
1235 $params['id'],
1236 'contribution_id',
1237 'participant_id'
1238 );
1239 }
1240 }
1241 unset($params['note']);
1242
1243 //build contribution params
1244 if (!$this->_onlinePendingContributionId) {
1245 if (empty($params['source'])) {
1246 $contributionParams['source'] = ts('%1 : Offline registration (by %2)', [
1247 1 => $this->getEventValue('title'),
1248 2 => $userName,
1249 ]);
1250 }
1251 else {
1252 $contributionParams['source'] = $params['source'];
1253 }
1254 }
1255
1256 $contributionParams['currency'] = $config->defaultCurrency;
1257 $contributionParams['non_deductible_amount'] = 'null';
1258 $contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
1259 $contributionParams['contact_id'] = $this->_contactID;
1260 $contributionParams['receive_date'] = $params['receive_date'] ?? date('Y-m-d');
1261
1262 $recordContribution = [
1263 'financial_type_id',
1264 'payment_instrument_id',
1265 'trxn_id',
1266 'contribution_status_id',
1267 'check_number',
1268 'campaign_id',
1269 'pan_truncation',
1270 'card_type_id',
1271 ];
1272
1273 foreach ($recordContribution as $f) {
1274 $contributionParams[$f] = $this->_params[$f] ?? NULL;
1275 if ($f == 'trxn_id') {
1276 $this->assign('trxn_id', $contributionParams[$f]);
1277 }
1278 }
1279
1280 //insert financial type name in receipt.
1281 $this->assign('financialTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
1282 $contributionParams['financial_type_id']));
1283 // legacy support
1284 $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
1285 $contributionParams['skipLineItem'] = 1;
1286 if ($this->_id) {
1287 $contributionParams['contribution_mode'] = 'participant';
1288 $contributionParams['participant_id'] = $this->_id;
1289 }
1290 // Set is_pay_later flag for back-office offline Pending status contributions
1291 if ($contributionParams['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Pending')) {
1292 $contributionParams['is_pay_later'] = 1;
1293 }
1294 elseif ($contributionParams['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Completed')) {
1295 $contributionParams['is_pay_later'] = 0;
1296 }
1297
1298 if ($params['status_id'] == array_search('Partially paid', $participantStatus)) {
1299 if (!$amountOwed && $this->_action & CRM_Core_Action::UPDATE) {
1300 $amountOwed = $params['fee_amount'];
1301 }
1302
1303 // if multiple participants are link, consider contribution total amount as the amount Owed
1304 if ($this->_id && CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
1305 $amountOwed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1306 $contributionParams['id'],
1307 'total_amount'
1308 );
1309 }
1310
1311 // CRM-13964 partial payment
1312 if ($amountOwed > $params['total_amount']) {
1313 // the owed amount
1314 $contributionParams['total_amount'] = $amountOwed;
1315 $contributionParams['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1316 $this->assign('balanceAmount', $amountOwed - $params['total_amount']);
1317 $this->storePaymentCreateParams($params);
1318 }
1319 }
1320
1321 if (!empty($this->_params['tax_amount'])) {
1322 $contributionParams['tax_amount'] = $this->_params['tax_amount'];
1323 }
1324
1325 if ($this->_single) {
1326 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams);
1327 }
1328 else {
1329 foreach ($this->_contactIds as $contactID) {
1330 $contributionParams['contact_id'] = $contactID;
1331 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams);
1332 }
1333 }
1334
1335 // Insert payment record for this participant
1336 if (empty($contributionParams['id'])) {
1337 foreach ($this->_contactIds as $num => $contactID) {
1338 $participantPaymentParams = [
1339 'participant_id' => $participants[$num]->id,
1340 'contribution_id' => $contributions[$num]->id,
1341 ];
1342 civicrm_api3('ParticipantPayment', 'create', $participantPaymentParams);
1343 }
1344 }
1345
1346 // CRM-11124
1347 if ($this->_params['discount_id']) {
1348 CRM_Event_BAO_Participant::createDiscountTrxn(
1349 $this->_eventId,
1350 $contributionParams,
1351 NULL,
1352 CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($this->_params)
1353 );
1354 }
1355 }
1356 }
1357
1358 // also store lineitem stuff here
1359 if ((($this->_lineItem && $this->_action & CRM_Core_Action::ADD) ||
1360 ($this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId))
1361 ) {
1362 foreach ($this->_contactIds as $num => $contactID) {
1363 foreach ($this->_lineItem as $key => $value) {
1364 if (is_array($value) && $value != 'skip') {
1365 foreach ($value as $lineKey => $line) {
1366 //10117 update the line items for participants if contribution amount is recorded
1367 if ($this->_quickConfig && !empty($params['total_amount']) &&
1368 ($params['status_id'] != array_search('Partially paid', $participantStatus))
1369 ) {
1370 $line['unit_price'] = $line['line_total'] = $params['total_amount'];
1371 if (!empty($params['tax_amount'])) {
1372 $line['unit_price'] = $line['unit_price'] - $params['tax_amount'];
1373 $line['line_total'] = $line['line_total'] - $params['tax_amount'];
1374 }
1375 }
1376 $lineItem[$this->_priceSetId][$lineKey] = $line;
1377 }
1378 CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
1379 }
1380 }
1381 }
1382 foreach ($contributions as $contribution) {
1383 if (!empty($this->getCreatePaymentParams())) {
1384 civicrm_api3('Payment', 'create', array_merge(['contribution_id' => $contribution->id], $this->getCreatePaymentParams()));
1385 }
1386 }
1387 }
1388
1389 $updateStatusMsg = NULL;
1390 //send mail when participant status changed, CRM-4326
1391 if ($this->_id && $this->_statusId &&
1392 $this->_statusId != CRM_Utils_Array::value('status_id', $params) && !empty($params['is_notify'])
1393 ) {
1394
1395 $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id,
1396 $params['status_id'],
1397 $this->_statusId
1398 );
1399 }
1400
1401 $sent = [];
1402 $notSent = [];
1403 if (!empty($params['send_receipt'])) {
1404
1405 $this->assign('module', 'Event Registration');
1406 $this->assignEventDetailsToTpl($params['event_id'], CRM_Utils_Array::value('role_id', $params), CRM_Utils_Array::value('receipt_text', $params), $this->_isPaidEvent);
1407 $this->assign('isAmountzero', 1);
1408
1409 if ($this->_isPaidEvent) {
1410 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
1411 if (!$this->_mode) {
1412 if (isset($params['payment_instrument_id'])) {
1413 $this->assign('paidBy',
1414 CRM_Utils_Array::value($params['payment_instrument_id'],
1415 $paymentInstrument
1416 )
1417 );
1418 }
1419 }
1420
1421 $this->assign('totalAmount', $params['total_amount'] ?? $contributionParams['total_amount']);
1422 $this->assign('isPrimary', 1);
1423 $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
1424 }
1425 if ($this->_mode) {
1426 $this->assignBillingName($params);
1427 $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
1428 $this->_params,
1429 $this->_bltID
1430 ));
1431
1432 $valuesForForm = CRM_Contribute_Form_AbstractEditPayment::formatCreditCardDetails($params);
1433 $this->assignVariables($valuesForForm, ['credit_card_exp_date', 'credit_card_type', 'credit_card_number']);
1434
1435 // The concept of contributeMode is deprecated.
1436 $this->assign('contributeMode', 'direct');
1437 $this->assign('isAmountzero', 0);
1438 $this->assign('is_pay_later', 0);
1439 $this->assign('isPrimary', 1);
1440 }
1441
1442 $this->assign('register_date', $params['register_date']);
1443 if (isset($params['receive_date'])) {
1444 $this->assign('receive_date', $params['receive_date']);
1445 }
1446
1447 $customGroup = [];
1448 //format submitted data
1449 foreach ($params['custom'] as $fieldID => $values) {
1450 foreach ($values as $fieldValue) {
1451 $isPublic = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $fieldValue['custom_group_id'], 'is_public');
1452 if ($isPublic) {
1453 $customFields[$fieldID]['id'] = $fieldID;
1454 $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id);
1455 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
1456 }
1457 }
1458 }
1459
1460 foreach ($this->_contactIds as $num => $contactID) {
1461 // Retrieve the name and email of the contact - this will be the TO for receipt email
1462 list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
1463
1464 $this->_contributorDisplayName = ($this->_contributorDisplayName == ' ') ? $this->_contributorEmail : $this->_contributorDisplayName;
1465
1466 $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
1467 if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
1468 $this->assign('isOnWaitlist', TRUE);
1469 }
1470
1471 $this->assign('customGroup', $customGroup);
1472 $this->assign('contactID', $contactID);
1473 $this->assign('participantID', $participants[$num]->id);
1474
1475 $this->_id = $participants[$num]->id;
1476
1477 if ($this->_isPaidEvent) {
1478 // fix amount for each of participants ( for bulk mode )
1479 $eventAmount = [];
1480 $totalTaxAmount = 0;
1481
1482 //add dataArray in the receipts in ADD and UPDATE condition
1483 $dataArray = [];
1484 if ($this->_action & CRM_Core_Action::ADD) {
1485 $line = $lineItem[0] ?? [];
1486 }
1487 elseif ($this->_action & CRM_Core_Action::UPDATE) {
1488 $line = $this->_values['line_items'];
1489 }
1490 if (Civi::settings()->get('invoicing')) {
1491 foreach ($line as $key => $value) {
1492 if (isset($value['tax_amount'])) {
1493 $totalTaxAmount += $value['tax_amount'];
1494 if (isset($dataArray[(string) $value['tax_rate']])) {
1495 $dataArray[(string) $value['tax_rate']] = $dataArray[(string) $value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
1496 }
1497 else {
1498 $dataArray[(string) $value['tax_rate']] = $value['tax_amount'] ?? NULL;
1499 }
1500 }
1501 }
1502 $this->assign('taxTerm', $this->getSalesTaxTerm());
1503 $this->assign('dataArray', $dataArray);
1504 }
1505 if (!empty($additionalParticipantDetails)) {
1506 $params['amount_level'] = preg_replace('/\ 1/', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
1507 }
1508
1509 $eventAmount[$num] = [
1510 'label' => preg_replace('/\ 1/', '', $params['amount_level']),
1511 'amount' => $params['fee_amount'],
1512 ];
1513 //as we are using same template for online & offline registration.
1514 //So we have to build amount as array.
1515 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
1516 $this->assign('amount', $eventAmount);
1517 }
1518 $this->assign('totalTaxAmount', $totalTaxAmount ?? 0);
1519 $sendTemplateParams = [
1520 'workflow' => 'event_offline_receipt',
1521 'contactId' => $contactID,
1522 'isTest' => !empty($this->_defaultValues['is_test']),
1523 'PDFFilename' => ts('confirmation') . '.pdf',
1524 'modelProps' => [
1525 'participantID' => $this->_id,
1526 'eventID' => $params['event_id'],
1527 ],
1528 ];
1529
1530 // try to send emails only if email id is present
1531 // and the do-not-email option is not checked for that contact
1532 if ($this->_contributorEmail and !$this->_toDoNotEmail) {
1533 if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
1534 $receiptFrom = $params['from_email_address'];
1535 }
1536 $sendTemplateParams['from'] = $receiptFrom;
1537 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
1538 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
1539 $sendTemplateParams['cc'] = $this->_fromEmails['cc'] ?? NULL;
1540 $sendTemplateParams['bcc'] = $this->_fromEmails['bcc'] ?? NULL;
1541 }
1542
1543 //send email with pdf invoice
1544 $template = CRM_Core_Smarty::singleton();
1545 $taxAmt = $template->get_template_vars('dataArray');
1546 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
1547 $this->_id, 'contribution_id', 'participant_id'
1548 );
1549 if (Civi::settings()->get('invoice_is_email_pdf')) {
1550 $sendTemplateParams['isEmailPdf'] = TRUE;
1551 $sendTemplateParams['contributionId'] = $contributionId;
1552 }
1553 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
1554 if ($mailSent) {
1555 $sent[] = $contactID;
1556 foreach ($participants as $ids => $values) {
1557 if ($values->contact_id == $contactID) {
1558 $values->details = $params['receipt_text'] ?? NULL;
1559 CRM_Activity_BAO_Activity::addActivity($values, 'Email');
1560 break;
1561 }
1562 }
1563 }
1564 else {
1565 $notSent[] = $contactID;
1566 }
1567 }
1568 }
1569
1570 // set the participant id if it is not set
1571 if (!$this->_id) {
1572 $this->_id = $participants[0]->id;
1573 }
1574
1575 return $this->getStatusMsg($params, $sent, $updateStatusMsg, $notSent);
1576 }
1577
1578 /**
1579 * Set the various IDs relating to custom data types.
1580 */
1581 public function setCustomDataTypes() {
1582 $customDataType = CRM_Core_OptionGroup::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name');
1583 $this->_roleCustomDataTypeID = array_search('ParticipantRole', $customDataType);
1584 $this->_eventNameCustomDataTypeID = array_search('ParticipantEventName', $customDataType);
1585 $this->_eventTypeCustomDataTypeID = array_search('ParticipantEventType', $customDataType);
1586 $this->assign('roleCustomDataTypeID', $this->_roleCustomDataTypeID);
1587 $this->assign('eventNameCustomDataTypeID', $this->_eventNameCustomDataTypeID);
1588 $this->assign('eventTypeCustomDataTypeID', $this->_eventTypeCustomDataTypeID);
1589 }
1590
1591 /**
1592 * Get status message
1593 *
1594 * @param array $params
1595 * @param int $sent
1596 * @param string $updateStatusMsg
1597 * @param int $notSent
1598 *
1599 * @return string
1600 */
1601 protected function getStatusMsg($params, $sent, $updateStatusMsg, $notSent) {
1602 $statusMsg = '';
1603 if (($this->_action & CRM_Core_Action::UPDATE)) {
1604 $statusMsg = ts('Event registration information for %1 has been updated.', [1 => $this->_contributorDisplayName]);
1605 if (!empty($params['send_receipt']) && count($sent)) {
1606 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', [1 => $this->_contributorEmail]);
1607 }
1608
1609 if ($updateStatusMsg) {
1610 $statusMsg = "{$statusMsg} {$updateStatusMsg}";
1611 }
1612 }
1613 elseif ($this->_action & CRM_Core_Action::ADD) {
1614 if ($this->_single) {
1615 $statusMsg = ts('Event registration for %1 has been added.', [1 => $this->_contributorDisplayName]);
1616 if (!empty($params['send_receipt']) && count($sent)) {
1617 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', [1 => $this->_contributorEmail]);
1618 }
1619 }
1620 else {
1621 $statusMsg = ts('Total Participant(s) added to event: %1.', [1 => count($this->_contactIds)]);
1622 if (count($notSent) > 0) {
1623 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', [1 => count($notSent)]);
1624 }
1625 elseif (isset($params['send_receipt'])) {
1626 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
1627 }
1628 }
1629 }
1630 return $statusMsg;
1631 }
1632
1633 /**
1634 * Build the form object.
1635 *
1636 * @param \CRM_Event_Form_Participant $form
1637 *
1638 * @return bool
1639 * @throws \CRM_Core_Exception
1640 * @throws \Exception
1641 */
1642 public function buildEventFeeForm($form) {
1643 if ($form->_eventId) {
1644 $form->_isPaidEvent = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $form->_eventId, 'is_monetary');
1645 if ($form->_isPaidEvent) {
1646 $form->addElement('hidden', 'hidden_feeblock', 1);
1647 }
1648
1649 $eventfullMsg = CRM_Event_BAO_Participant::eventFullMessage($form->_eventId, $this->getParticipantID());
1650 $form->addElement('hidden', 'hidden_eventFullMsg', $eventfullMsg, ['id' => 'hidden_eventFullMsg']);
1651 }
1652
1653 if ($form->_isPaidEvent) {
1654 $params = ['id' => $form->_eventId];
1655 CRM_Event_BAO_Event::retrieve($params, $event);
1656
1657 //retrieve custom information
1658 $form->_values = [];
1659 CRM_Event_Form_Registration::initEventFee($form, $event['id'], FALSE);
1660 CRM_Event_Form_Registration_Register::buildAmount($form, TRUE, $form->_discountId);
1661 $lineItem = [];
1662 $totalTaxAmount = 0;
1663 if (!CRM_Utils_System::isNull(CRM_Utils_Array::value('line_items', $form->_values))) {
1664 $lineItem[] = $form->_values['line_items'];
1665 foreach ($form->_values['line_items'] as $key => $value) {
1666 $totalTaxAmount = $value['tax_amount'] + $totalTaxAmount;
1667 }
1668 }
1669 $form->assign('totalTaxAmount', Civi::settings()->get('invoicing') ? ($totalTaxAmount ?? NULL) : NULL);
1670 $form->assign('lineItem', empty($lineItem) ? FALSE : $lineItem);
1671 $discounts = [];
1672 if (!empty($form->_values['discount'])) {
1673 foreach ($form->_values['discount'] as $key => $value) {
1674 $value = current($value);
1675 $discounts[$key] = $value['name'];
1676 }
1677
1678 $element = $form->add('select', 'discount_id',
1679 ts('Discount Set'),
1680 [
1681 0 => ts('- select -'),
1682 ] + $discounts,
1683 FALSE,
1684 ['class' => "crm-select2"]
1685 );
1686 }
1687 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
1688 && empty($form->_values['fee'])
1689 && CRM_Utils_Array::value('snippet', $_REQUEST) == CRM_Core_Smarty::PRINT_NOFORM
1690 ) {
1691 CRM_Core_Session::setStatus(ts('You do not have all the permissions needed for this page.'), 'Permission Denied', 'error');
1692 return FALSE;
1693 }
1694
1695 CRM_Core_Payment_Form::buildPaymentForm($form, $form->_paymentProcessor, FALSE, TRUE, self::getDefaultPaymentInstrumentId());
1696 if (!$form->_mode) {
1697 $form->addElement('checkbox', 'record_contribution', ts('Record Payment?'), NULL,
1698 ['onclick' => "return showHideByValue('record_contribution','','payment_information','table-row','radio',false);"]
1699 );
1700 // Check permissions for financial type first
1701 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
1702 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $form->_action);
1703 }
1704 else {
1705 $financialTypes = CRM_Contribute_PseudoConstant::financialType();
1706 }
1707
1708 $form->add('select', 'financial_type_id',
1709 ts('Financial Type'),
1710 ['' => ts('- select -')] + $financialTypes
1711 );
1712
1713 $form->add('datepicker', 'receive_date', ts('Received'), [], FALSE, ['time' => TRUE]);
1714
1715 $form->add('select', 'payment_instrument_id',
1716 ts('Payment Method'),
1717 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
1718 FALSE, ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
1719 );
1720 // don't show transaction id in batch update mode
1721 $path = CRM_Utils_System::currentPath();
1722 $form->assign('showTransactionId', FALSE);
1723 if ($path != 'civicrm/contact/search/basic') {
1724 $form->add('text', 'trxn_id', ts('Transaction ID'));
1725 $form->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
1726 'objectExists', ['CRM_Contribute_DAO_Contribution', $form->_eventId, 'trxn_id']
1727 );
1728 $form->assign('showTransactionId', TRUE);
1729 }
1730
1731 $form->add('select', 'contribution_status_id',
1732 ts('Payment Status'), CRM_Contribute_BAO_Contribution_Utils::getPendingAndCompleteStatuses()
1733 );
1734
1735 $form->add('text', 'check_number', ts('Check Number'),
1736 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
1737 );
1738
1739 $form->add('text', 'total_amount', ts('Amount'),
1740 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'total_amount')
1741 );
1742 }
1743 }
1744 else {
1745 $form->add('text', 'amount', ts('Event Fee(s)'));
1746 }
1747 $form->assign('onlinePendingContributionId', $form->get('onlinePendingContributionId'));
1748
1749 $form->assign('paid', $form->_isPaidEvent);
1750
1751 $form->addElement('checkbox',
1752 'send_receipt',
1753 ts('Send Confirmation?'), NULL,
1754 ['onclick' => "showHideByValue('send_receipt','','notice','table-row','radio',false); showHideByValue('send_receipt','','from-email','table-row','radio',false);"]
1755 );
1756
1757 $form->add('select', 'from_email_address', ts('Receipt From'), $form->_fromEmails['from_email_id']);
1758
1759 $form->add('textarea', 'receipt_text', ts('Confirmation Message'));
1760
1761 // Retrieve the name and email of the contact - form will be the TO for receipt email ( only if context is not standalone)
1762 if ($form->_context != 'standalone') {
1763 if ($form->_contactId) {
1764 list($form->_contributorDisplayName,
1765 $form->_contributorEmail
1766 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($form->_contactId);
1767 $form->assign('email', $form->_contributorEmail);
1768 }
1769 else {
1770 //show email block for batch update for event
1771 $form->assign('batchEmail', TRUE);
1772 }
1773 }
1774
1775 $mailingInfo = Civi::settings()->get('mailing_backend');
1776 $form->assign('outBound_option', $mailingInfo['outBound_option']);
1777 $form->assign('hasPayment', $form->_paymentId);
1778 }
1779
1780 /**
1781 * Extracted code relating to paid events.
1782 *
1783 * @param $params
1784 *
1785 * @return array
1786 *
1787 * @throws \CiviCRM_API3_Exception
1788 */
1789 protected function preparePaidEventProcessing($params): array {
1790 $participantStatus = CRM_Event_PseudoConstant::participantStatus();
1791 $contributionParams = [
1792 'skipCleanMoney' => TRUE,
1793 'revenue_recognition_date' => $this->getRevenueRecognitionDate(),
1794 ];
1795 $lineItem = [];
1796 $additionalParticipantDetails = [];
1797
1798 if ($this->isPaymentOnExistingContribution()) {
1799 $contributionParams['total_amount'] = $this->getParticipantValue('fee_amount');
1800
1801 $params['discount_id'] = NULL;
1802 //re-enter the values for UPDATE mode
1803 $params['fee_level'] = $params['amount_level'] = $this->getParticipantValue('fee_level');
1804 $params['fee_amount'] = $this->getParticipantValue('fee_amount');
1805 if (isset($params['priceSetId'])) {
1806 CRM_Core_Error::deprecatedFunctionWarning('It seems this line is never hit & can go.');
1807 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
1808 }
1809 //also add additional participant's fee level/priceset
1810 if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
1811 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
1812 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE);
1813 $additionalParticipantDetails = $this->getFeeDetails($additionalIds, $hasLineItems);
1814 }
1815 }
1816 else {
1817
1818 // check that discount_id is set
1819 if (empty($params['discount_id'])) {
1820 $params['discount_id'] = 'null';
1821 }
1822
1823 //lets carry currency, CRM-4453
1824 $params['fee_currency'] = CRM_Core_Config::singleton()->defaultCurrency;
1825 if (!isset($lineItem[0])) {
1826 $lineItem[0] = [];
1827 }
1828 CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'],
1829 $params, $lineItem[0]
1830 );
1831 //CRM-11529 for quick config backoffice transactions
1832 //when financial_type_id is passed in form, update the
1833 //lineitems with the financial type selected in form
1834 $submittedFinancialType = $params['financial_type_id'] ?? NULL;
1835 $isPaymentRecorded = $params['record_contribution'] ?? NULL;
1836 if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) {
1837 foreach ($lineItem[0] as &$values) {
1838 $values['financial_type_id'] = $submittedFinancialType;
1839 }
1840 }
1841
1842 $params['fee_level'] = $params['amount_level'];
1843 $contributionParams['total_amount'] = $params['amount'];
1844 if ($this->_quickConfig && !empty($params['total_amount']) &&
1845 $params['status_id'] != array_search('Partially paid', $participantStatus)
1846 ) {
1847 $params['fee_amount'] = $params['total_amount'];
1848 }
1849 else {
1850 //fix for CRM-3086
1851 $params['fee_amount'] = $params['amount'];
1852 }
1853 }
1854
1855 if (isset($params['priceSetId'])) {
1856 if (!empty($lineItem[0])) {
1857 $this->set('lineItem', $lineItem);
1858
1859 $this->_lineItem = $lineItem;
1860 $lineItem = array_merge($lineItem, $additionalParticipantDetails);
1861
1862 $participantCount = [];
1863 foreach ($lineItem as $k) {
1864 foreach ($k as $v) {
1865 if (CRM_Utils_Array::value('participant_count', $v) > 0) {
1866 $participantCount[] = $v['participant_count'];
1867 }
1868 }
1869 }
1870 }
1871 if (isset($participantCount)) {
1872 $this->assign('pricesetFieldsCount', $participantCount);
1873 }
1874 $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig ? FALSE : $lineItem);
1875 }
1876 else {
1877 $this->assign('amount_level', $params['amount_level']);
1878 }
1879 return [$contributionParams, $lineItem, $additionalParticipantDetails, $params];
1880 }
1881
1882 /**
1883 * @param $eventID
1884 * @param $participantRoles
1885 * @param $receiptText
1886 * @param $isPaidEvent
1887 *
1888 * @return void
1889 */
1890 protected function assignEventDetailsToTpl($eventID, $participantRoles, $receiptText, $isPaidEvent) {
1891 //use of the message template below requires variables in different format
1892 $events = [];
1893 $returnProperties = ['event_type_id', 'fee_label', 'start_date', 'end_date', 'is_show_location', 'title'];
1894
1895 //get all event details.
1896 CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $eventID, $events, $returnProperties);
1897 $event = $events[$eventID];
1898 unset($event['start_date']);
1899 unset($event['end_date']);
1900
1901 $role = CRM_Event_PseudoConstant::participantRole();
1902
1903 if (is_array($participantRoles)) {
1904 $selectedRoles = [];
1905 foreach ($participantRoles as $roleId) {
1906 $selectedRoles[] = $role[$roleId];
1907 }
1908 $event['participant_role'] = implode(', ', $selectedRoles);
1909 }
1910 else {
1911 $event['participant_role'] = $role[$participantRoles] ?? NULL;
1912 }
1913 $event['is_monetary'] = $isPaidEvent;
1914
1915 if ($receiptText) {
1916 $event['confirm_email_text'] = $receiptText;
1917 }
1918 $this->assign('event', $event);
1919 $this->assign('isShowLocation', $event['is_show_location']);
1920 if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
1921 $locationParams = [
1922 'entity_id' => $eventID,
1923 'entity_table' => 'civicrm_event',
1924 ];
1925 $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
1926 $this->assign('location', $location);
1927 }
1928 }
1929
1930 /**
1931 * Process the contribution.
1932 *
1933 * @param CRM_Core_Form $form
1934 * @param array $params
1935 * @param array $result
1936 * @param int $contactID
1937 * @param bool $pending
1938 * @param array $paymentProcessor
1939 *
1940 * @return \CRM_Contribute_BAO_Contribution
1941 *
1942 * @throws \CRM_Core_Exception
1943 * @throws \CiviCRM_API3_Exception
1944 */
1945 public function processContribution(
1946 &$form, $params, $result, $contactID,
1947 $pending = FALSE,
1948 $paymentProcessor = NULL
1949 ) {
1950 $transaction = new CRM_Core_Transaction();
1951
1952 $now = date('YmdHis');
1953 $receiptDate = NULL;
1954
1955 if (!empty($form->_values['event']['is_email_confirm'])) {
1956 $receiptDate = $now;
1957 }
1958
1959 // CRM-20264: fetch CC type ID and number (last 4 digit) and assign it back to $params
1960 CRM_Contribute_Form_AbstractEditPayment::formatCreditCardDetails($params);
1961
1962 $contribParams = [
1963 'contact_id' => $contactID,
1964 'financial_type_id' => !empty($form->_values['event']['financial_type_id']) ? $form->_values['event']['financial_type_id'] : $params['financial_type_id'],
1965 'receive_date' => $now,
1966 'total_amount' => $params['amount'],
1967 'tax_amount' => $params['tax_amount'],
1968 'amount_level' => $params['amount_level'],
1969 'invoice_id' => $params['invoiceID'],
1970 'currency' => $params['currencyID'],
1971 'source' => !empty($params['participant_source']) ? $params['participant_source'] : $params['description'],
1972 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
1973 'campaign_id' => $params['campaign_id'] ?? NULL,
1974 'card_type_id' => $params['card_type_id'] ?? NULL,
1975 'pan_truncation' => $params['pan_truncation'] ?? NULL,
1976 ];
1977
1978 if ($paymentProcessor) {
1979 $contribParams['payment_instrument_id'] = $paymentProcessor['payment_instrument_id'];
1980 $contribParams['payment_processor'] = $paymentProcessor['id'];
1981 }
1982
1983 if (!$pending && $result) {
1984 $contribParams += [
1985 'fee_amount' => $result['fee_amount'] ?? NULL,
1986 'trxn_id' => $result['trxn_id'],
1987 'receipt_date' => $receiptDate,
1988 ];
1989 }
1990
1991 $allStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1992 $contribParams['contribution_status_id'] = array_search('Completed', $allStatuses);
1993 if ($pending) {
1994 $contribParams['contribution_status_id'] = array_search('Pending', $allStatuses);
1995 }
1996
1997 $contribParams['is_test'] = 0;
1998 if ($form->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
1999 $contribParams['is_test'] = 1;
2000 }
2001
2002 if (!empty($contribParams['invoice_id'])) {
2003 $contribParams['id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
2004 $contribParams['invoice_id'],
2005 'id',
2006 'invoice_id'
2007 );
2008 }
2009 $contribParams['revenue_recognition_date'] = $this->getRevenueRecognitionDate();
2010
2011 //create an contribution address
2012 // The concept of contributeMode is deprecated. Elsewhere we use the function processBillingAddress() - although
2013 // currently that is only inherited by back-office forms.
2014 if ($form->_contributeMode != 'notify' && empty($params['is_pay_later'])) {
2015 $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
2016 }
2017
2018 $contribParams['skipLineItem'] = 1;
2019 $contribParams['skipCleanMoney'] = 1;
2020 // create contribution record
2021 $contribution = CRM_Contribute_BAO_Contribution::add($contribParams);
2022 // CRM-11124
2023 CRM_Event_BAO_Participant::createDiscountTrxn($form->_eventId, $contribParams, NULL, CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($params));
2024
2025 // process soft credit / pcp pages
2026 if (!empty($params['pcp_made_through_id'])) {
2027 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($params, $form);
2028 CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
2029 }
2030
2031 $transaction->commit();
2032
2033 return $contribution;
2034 }
2035
2036 /**
2037 * Process the participant.
2038 *
2039 * @param CRM_Core_Form $form
2040 * @param array $params
2041 * @param int $contactID
2042 *
2043 * @return \CRM_Event_BAO_Participant
2044 * @throws \CRM_Core_Exception
2045 * @throws \CiviCRM_API3_Exception
2046 */
2047 protected function addParticipant(&$form, $params, $contactID) {
2048 $transaction = new CRM_Core_Transaction();
2049
2050 $participantFields = CRM_Event_DAO_Participant::fields();
2051 $participantParams = [
2052 'id' => $params['participant_id'] ?? NULL,
2053 'contact_id' => $contactID,
2054 'event_id' => $form->_eventId ? $form->_eventId : $params['event_id'],
2055 'status_id' => CRM_Utils_Array::value('participant_status',
2056 $params, 1
2057 ),
2058 'role_id' => CRM_Utils_Array::value('participant_role_id', $params) ?: CRM_Event_BAO_Participant::getDefaultRoleID(),
2059 'register_date' => $params['register_date'],
2060 'source' => CRM_Utils_String::ellipsify(
2061 isset($params['participant_source']) ? CRM_Utils_Array::value('participant_source', $params) : CRM_Utils_Array::value('description', $params),
2062 $participantFields['participant_source']['maxlength']
2063 ),
2064 'fee_level' => $params['amount_level'] ?? NULL,
2065 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
2066 'fee_amount' => $params['fee_amount'] ?? NULL,
2067 'registered_by_id' => $params['registered_by_id'] ?? NULL,
2068 'discount_id' => $params['discount_id'] ?? NULL,
2069 'fee_currency' => $params['currencyID'] ?? NULL,
2070 'campaign_id' => $params['campaign_id'] ?? NULL,
2071 ];
2072
2073 if ($form->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
2074 $participantParams['is_test'] = 1;
2075 }
2076 else {
2077 $participantParams['is_test'] = 0;
2078 }
2079
2080 if (!empty($form->_params['note'])) {
2081 $participantParams['note'] = $form->_params['note'];
2082 }
2083 elseif (!empty($form->_params['participant_note'])) {
2084 $participantParams['note'] = $form->_params['participant_note'];
2085 }
2086
2087 // reuse id if one already exists for this one (can happen
2088 // with back button being hit etc)
2089 if (!$participantParams['id'] && !empty($params['contributionID'])) {
2090 $pID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
2091 $params['contributionID'],
2092 'participant_id',
2093 'contribution_id'
2094 );
2095 $participantParams['id'] = $pID;
2096 }
2097 $participantParams['discount_id'] = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event');
2098
2099 if (!$participantParams['discount_id']) {
2100 $participantParams['discount_id'] = "null";
2101 }
2102
2103 $participant = CRM_Event_BAO_Participant::create($participantParams);
2104
2105 $transaction->commit();
2106
2107 return $participant;
2108 }
2109
2110 /**
2111 * Is a payment being made on an existing contribution.
2112 *
2113 * Note
2114 * 1) ideally we should not permit this on this form! Perhaps we don't & this is just cruft.
2115 * 2) _paymentID is the contribution id.
2116 *
2117 * @return bool
2118 */
2119 protected function isPaymentOnExistingContribution(): bool {
2120 return ($this->getParticipantID() && $this->_action & CRM_Core_Action::UPDATE) && $this->_paymentId;
2121 }
2122
2123 /**
2124 * Get the value for a field relating to the event.
2125 *
2126 * @param string $fieldName
2127 *
2128 * @return mixed
2129 * @throws \CiviCRM_API3_Exception
2130 */
2131 protected function getEventValue(string $fieldName) {
2132 if (!isset($this->_event)) {
2133 $this->_event = civicrm_api3('Event', 'getsingle', ['id' => $this->_eventId]);
2134 }
2135 return $this->_event[$fieldName];
2136 }
2137
2138 /**
2139 * Get a value from the existing participant record (applies to edits).
2140 *
2141 * @param string $fieldName
2142 *
2143 * @return array
2144 * @throws \CiviCRM_API3_Exception
2145 */
2146 protected function getParticipantValue($fieldName) {
2147 if (!$this->participantRecord) {
2148 $this->participantRecord = civicrm_api3('Participant', 'getsingle', ['id' => $this->_id]);
2149 }
2150 return $this->participantRecord[$fieldName] ?? $this->participantRecord['participant_' . $fieldName];
2151 }
2152
2153 /**
2154 * Get id of participant being edited.
2155 *
2156 * @return int|null
2157 */
2158 protected function getParticipantID() {
2159 return $this->_id ?? $this->_pId;
2160 }
2161
2162 /**
2163 * Get the value for the revenue recognition date field.
2164 *
2165 * @return string
2166 *
2167 * @throws \CiviCRM_API3_Exception
2168 */
2169 protected function getRevenueRecognitionDate() {
2170 if (Civi::settings()->get('deferred_revenue_enabled')) {
2171 $eventStartDate = $this->getEventValue('start_date');
2172 if (strtotime($eventStartDate) > strtotime(date('Ymt'))) {
2173 return date('Ymd', strtotime($eventStartDate));
2174 }
2175 }
2176 return '';
2177 }
2178
2179 /**
2180 * Store the parameters to create a payment, if appropriate, on the form.
2181 *
2182 * @param array $params
2183 * Params as submitted.
2184 */
2185 protected function storePaymentCreateParams($params) {
2186 if ('Completed' === CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution_status_id'])) {
2187 $this->setCreatePaymentParams([
2188 'total_amount' => $params['total_amount'],
2189 'is_send_contribution_notification' => FALSE,
2190 'payment_instrument_id' => $params['payment_instrument_id'],
2191 'trxn_date' => $params['receive_date'] ?? date('Y-m-d'),
2192 'trxn_id' => $params['trxn_id'],
2193 'pan_truncation' => $params['pan_truncation'] ?? '',
2194 'card_type_id' => $params['card_type_id'] ?? '',
2195 'check_number' => $params['check_number'] ?? '',
2196 'skipCleanMoney' => TRUE,
2197 ]);
2198 }
2199 }
2200
2201 /**
2202 * Get the event fee info for given participant ids
2203 * either from line item table / participant table.
2204 *
2205 * @param array $participantIds
2206 * Participant ids.
2207 * @param bool $hasLineItems
2208 * Do fetch from line items.
2209 *
2210 * @return array
2211 */
2212 public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
2213 $feeDetails = [];
2214 if (!is_array($participantIds) || empty($participantIds)) {
2215 return $feeDetails;
2216 }
2217
2218 $select = '
2219 SELECT participant.id as id,
2220 participant.fee_level as fee_level,
2221 participant.fee_amount as fee_amount';
2222 $from = 'FROM civicrm_participant participant';
2223 if ($hasLineItems) {
2224 $select .= ' ,
2225 lineItem.id as lineId,
2226 lineItem.label as label,
2227 lineItem.qty as qty,
2228 lineItem.unit_price as unit_price,
2229 lineItem.line_total as line_total,
2230 field.label as field_title,
2231 field.html_type as html_type,
2232 field.id as price_field_id,
2233 value.id as price_field_value_id,
2234 value.description as description,
2235 IF( value.count, value.count, 0 ) as participant_count';
2236 $from .= "
2237 INNER JOIN civicrm_line_item lineItem ON ( lineItem.entity_table = 'civicrm_participant'
2238 AND lineItem.entity_id = participant.id )
2239 INNER JOIN civicrm_price_field field ON ( field.id = lineItem.price_field_id )
2240 INNER JOIN civicrm_price_field_value value ON ( value.id = lineItem.price_field_value_id )
2241 ";
2242 }
2243 $where = 'WHERE participant.id IN ( ' . implode(', ', $participantIds) . ' )';
2244 $query = "$select $from $where";
2245
2246 $feeInfo = CRM_Core_DAO::executeQuery($query);
2247 $feeProperties = ['fee_level', 'fee_amount'];
2248 $lineProperties = [
2249 'lineId',
2250 'label',
2251 'qty',
2252 'unit_price',
2253 'line_total',
2254 'field_title',
2255 'html_type',
2256 'price_field_id',
2257 'participant_count',
2258 'price_field_value_id',
2259 'description',
2260 ];
2261 while ($feeInfo->fetch()) {
2262 if ($hasLineItems) {
2263 foreach ($lineProperties as $property) {
2264 $feeDetails[$feeInfo->id][$feeInfo->lineId][$property] = $feeInfo->$property;
2265 }
2266 }
2267 else {
2268 foreach ($feeProperties as $property) {
2269 $feeDetails[$feeInfo->id][$property] = $feeInfo->$property;
2270 }
2271 }
2272 }
2273
2274 return $feeDetails;
2275 }
2276
2277 /**
2278 * Assign the url path to the template.
2279 */
2280 protected function assignUrlPath() {
2281 $this->assign('urlPath', 'civicrm/contact/view/participant');
2282 if (!$this->_id && !$this->_contactId) {
2283 $breadCrumbs = [
2284 [
2285 'title' => ts('CiviEvent Dashboard'),
2286 'url' => CRM_Utils_System::url('civicrm/event', 'reset=1'),
2287 ],
2288 ];
2289
2290 CRM_Utils_System::appendBreadCrumb($breadCrumbs);
2291 }
2292 else {
2293 $this->assign('id', $this->_id);
2294 $this->assign('contact_id', $this->_contactId);
2295 }
2296 }
2297
2298 }