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