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