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