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