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