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