Merge pull request #15942 from seamuslee001/contact_fields_metadata
[civicrm-core.git] / CRM / Contribute / Form / AdditionalPayment.php
CommitLineData
0f602e3f
PJ
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
0f602e3f 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 |
0f602e3f 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
0f602e3f
PJ
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
0f602e3f
PJ
16 */
17
18/**
07f8d162 19 * This form records additional payments needed when event/contribution is partially paid.
0f602e3f
PJ
20 */
21class CRM_Contribute_Form_AdditionalPayment extends CRM_Contribute_Form_AbstractEditPayment {
22 public $_contributeMode = 'direct';
23
0f602e3f 24 /**
100fef9d 25 * Id of the component entity
1330f57a 26 * @var int
0f602e3f
PJ
27 */
28 public $_id = NULL;
29
c0406a91 30 protected $entity = 'Contribution';
31
0f602e3f
PJ
32 protected $_owed = NULL;
33
34 protected $_refund = NULL;
35
0dc4ef42 36 /**
0dc4ef42 37 * @var int
1330f57a 38 * @deprecated - use parent $this->contactID
0dc4ef42 39 */
0f602e3f
PJ
40 protected $_contactId = NULL;
41
42 protected $_contributorDisplayName = NULL;
43
44 protected $_contributorEmail = NULL;
45
46 protected $_toDoNotEmail = NULL;
47
48 protected $_paymentType = NULL;
49
50 protected $_contributionId = NULL;
51
bd99f5fe
PJ
52 protected $fromEmailId = NULL;
53
81f3d017
PJ
54 protected $_view = NULL;
55
56 public $_action = NULL;
57
bd981689 58 /**
59 * Pre process form.
60 *
61 * @throws \CRM_Core_Exception
62 */
0f602e3f 63 public function preProcess() {
8f262a0b 64
0f602e3f 65 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
c0406a91 66 parent::preProcess();
67 $this->_contactId = $this->_contactID;
68 $this->_component = CRM_Utils_Request::retrieve('component', 'String', $this, FALSE, 'contribution');
81f3d017 69 $this->_view = CRM_Utils_Request::retrieve('view', 'String', $this, FALSE);
81f3d017
PJ
70 $this->assign('component', $this->_component);
71 $this->assign('id', $this->_id);
d4c0653f 72 $this->assign('suppressPaymentFormButtons', $this->isBeingCalledFromSelectorContext());
ad96d702 73
81f3d017 74 if ($this->_view == 'transaction' && ($this->_action & CRM_Core_Action::BROWSE)) {
c0406a91 75 $title = $this->assignPaymentInfoBlock();
536b8316 76 CRM_Utils_System::setTitle($title);
81f3d017
PJ
77 return;
78 }
8f4f19ca 79 $entityType = 'contribution';
0f602e3f 80 if ($this->_component == 'event') {
8f4f19ca 81 $entityType = 'participant';
0f602e3f 82 $this->_contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id');
685dc433 83 $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id');
685dc433
PN
84 }
85 else {
86 $this->_contributionId = $this->_id;
0f602e3f
PJ
87 }
88
d5397f2f 89 $paymentDetails = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_id, $this->_component, FALSE, TRUE);
a168b222 90 $paymentAmt = CRM_Contribute_BAO_Contribution::getContributionBalance($this->_id);
7cdb890a
PJ
91
92 $this->_amtPaid = $paymentDetails['paid'];
93 $this->_amtTotal = $paymentDetails['total'];
0f602e3f 94
a168b222 95 if ($paymentAmt < 0) {
96 $this->_refund = $paymentAmt;
0f602e3f
PJ
97 $this->_paymentType = 'refund';
98 }
a168b222 99 elseif ($paymentAmt > 0) {
100 $this->_owed = $paymentAmt;
0f602e3f
PJ
101 $this->_paymentType = 'owed';
102 }
103 else {
bd981689 104 throw new CRM_Core_Exception(ts('No payment information found for this record'));
0f602e3f
PJ
105 }
106
e8cf3013 107 if (!empty($this->_mode) && $this->_paymentType == 'refund') {
bd981689 108 throw new CRM_Core_Exception(ts('Credit card payment is not for Refund payments use'));
e8cf3013
PJ
109 }
110
c0406a91 111 list($this->_contributorDisplayName, $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
e8cf3013 112
0f602e3f 113 $this->assign('contributionMode', $this->_mode);
c0406a91 114 $this->assign('contactId', $this->_contactID);
0f602e3f 115 $this->assign('paymentType', $this->_paymentType);
e8cf3013 116 $this->assign('paymentAmt', abs($paymentAmt));
0f602e3f 117
2c13688c 118 $this->setPageTitle($this->_refund ? ts('Refund') : ts('Payment'));
0f602e3f
PJ
119 }
120
d4c0653f 121 /**
122 * Is this function being called from a datatable selector.
123 *
124 * If so we don't want to show the buttons.
bd981689 125 *
126 * @throws \CRM_Core_Exception
d4c0653f 127 */
128 protected function isBeingCalledFromSelectorContext() {
129 return CRM_Utils_Request::retrieve('selector', 'Positive');
130 }
131
186c9c17
EM
132 /**
133 * This virtual function is used to set the default values of
134 * various form elements
135 *
136 * access public
137 *
a6c01b45
CW
138 * @return array
139 * reference to the array of default values
186c9c17 140 */
1330f57a 141
186c9c17
EM
142 /**
143 * @return array
144 */
0f602e3f 145 public function setDefaultValues() {
81f3d017 146 if ($this->_view == 'transaction' && ($this->_action & CRM_Core_Action::BROWSE)) {
acb1052e 147 return NULL;
81f3d017 148 }
be2fb01f 149 $defaults = [];
0f602e3f 150 if ($this->_mode) {
9f89c7a2
PN
151 CRM_Core_Payment_Form::setDefaultValues($this, $this->_contactId);
152 $defaults = array_merge($defaults, $this->_defaults);
0f602e3f
PJ
153 }
154
f7fb5615 155 if (empty($defaults['trxn_date'])) {
156 $defaults['trxn_date'] = date('Y-m-d H:i:s');
efa3d1d1
PJ
157 }
158
820fbcfb 159 if ($this->_refund) {
7583896b 160 $defaults['total_amount'] = CRM_Utils_Money::format(abs($this->_refund), NULL, NULL, TRUE);
820fbcfb 161 }
aea78df0 162 elseif ($this->_owed) {
28c249a9 163 $defaults['total_amount'] = CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($this->_owed);
aea78df0 164 }
820fbcfb 165
0f602e3f 166 // Set $newCredit variable in template to control whether link to credit card mode is included
9be1374d 167 $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
efa3d1d1 168 return $defaults;
0f602e3f
PJ
169 }
170
9f89c7a2
PN
171 /**
172 * Build the form object.
173 */
0f602e3f 174 public function buildQuickForm() {
81f3d017 175 if ($this->_view == 'transaction' && ($this->_action & CRM_Core_Action::BROWSE)) {
be2fb01f 176 $this->addButtons([
1330f57a
SL
177 [
178 'type' => 'cancel',
179 'name' => ts('Done'),
180 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
181 'isDefault' => TRUE,
182 ],
183 ]);
81f3d017
PJ
184 return;
185 }
254ce393 186
18135422 187 CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE, CRM_Utils_Request::retrieve('payment_instrument_id', 'Integer'));
23cb875c 188 $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors, NULL);
189
0f602e3f
PJ
190 $attributes = CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialTrxn');
191
58438e5b 192 $label = ($this->_refund) ? ts('Refund Amount') : ts('Payment Amount');
0f602e3f 193 $this->addMoney('total_amount',
58438e5b 194 $label,
43c6eb86 195 TRUE,
0f602e3f
PJ
196 $attributes['total_amount'],
197 TRUE, 'currency', NULL
198 );
199
0f602e3f
PJ
200 //add receipt for offline contribution
201 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
202
44a2f017 203 if ($this->_component === 'event') {
204 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id');
205 }
206
9fabaa56 207 $this->add('select', 'from_email_address', ts('Receipt From'), CRM_Financial_BAO_Payment::getValidFromEmailsForPayment($eventID ?? NULL));
0f602e3f 208
7cdb890a
PJ
209 $this->add('textarea', 'receipt_text', ts('Confirmation Message'));
210
7bc6b5bb 211 $dateLabel = ($this->_refund) ? ts('Refund Date') : ts('Date Received');
be2fb01f 212 $this->addField('trxn_date', ['entity' => 'FinancialTrxn', 'label' => $dateLabel, 'context' => 'Contribution'], FALSE, FALSE);
0f602e3f
PJ
213
214 if ($this->_contactId && $this->_id) {
215 if ($this->_component == 'event') {
216 $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id');
217 $event = CRM_Event_BAO_Event::getEvents(0, $eventId);
218 $this->assign('eventName', $event[$eventId]);
219 }
220 }
221
222 $this->assign('displayName', $this->_contributorDisplayName);
223 $this->assign('component', $this->_component);
224 $this->assign('email', $this->_contributorEmail);
225
0f602e3f 226 $js = NULL;
23cb875c 227 // render backoffice payment fields only on offline mode
0f602e3f 228 if (!$this->_mode) {
f5269434 229 $js = ['onclick' => 'return verify( );'];
23cb875c 230
231 $this->add('select', 'payment_instrument_id',
232 ts('Payment Method'),
be2fb01f 233 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
1f24c7f5 234 TRUE,
be2fb01f 235 ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
23cb875c 236 );
237
238 $this->add('text', 'check_number', ts('Check Number'), $attributes['financial_trxn_check_number']);
be2fb01f 239 $this->add('text', 'trxn_id', ts('Transaction ID'), ['class' => 'twelve'] + $attributes['trxn_id']);
23cb875c 240
241 $this->add('text', 'fee_amount', ts('Fee Amount'),
242 $attributes['fee_amount']
243 );
244 $this->addRule('fee_amount', ts('Please enter a valid monetary value for Fee Amount.'), 'money');
0f602e3f
PJ
245 }
246
78e1e6b4 247 $buttonName = $this->_refund ? ts('Record Refund') : ts('Record Payment');
be2fb01f 248 $this->addButtons([
1330f57a
SL
249 [
250 'type' => 'upload',
78e1e6b4 251 'name' => $buttonName,
1330f57a
SL
252 'js' => $js,
253 'isDefault' => TRUE,
254 ],
255 [
256 'type' => 'cancel',
257 'name' => ts('Cancel'),
258 ],
259 ]);
aaffa79f 260 $mailingInfo = Civi::settings()->get('mailing_backend');
0f602e3f
PJ
261 $this->assign('outBound_option', $mailingInfo['outBound_option']);
262
be2fb01f 263 $this->addFormRule(['CRM_Contribute_Form_AdditionalPayment', 'formRule'], $this);
0f602e3f
PJ
264 }
265
186c9c17
EM
266 /**
267 * @param $fields
268 * @param $files
269 * @param $self
270 *
271 * @return array
272 */
00be9182 273 public static function formRule($fields, $files, $self) {
be2fb01f 274 $errors = [];
0f602e3f
PJ
275 if ($self->_paymentType == 'owed' && $fields['total_amount'] > $self->_owed) {
276 $errors['total_amount'] = ts('Payment amount cannot be greater than owed amount');
277 }
e8cf3013 278 if ($self->_paymentType == 'refund' && $fields['total_amount'] != abs($self->_refund)) {
0f2c3c03 279 $errors['total_amount'] = ts('Refund amount must equal refund due amount.');
0f602e3f 280 }
f5269434 281
43c6eb86 282 if ($self->_paymentProcessor['id'] === 0 && empty($fields['payment_instrument_id'])) {
283 $errors['payment_instrument_id'] = ts('Payment method is a required field');
284 }
285
0f602e3f
PJ
286 return $errors;
287 }
288
922becfb
PN
289 /**
290 * Process the form submission.
291 */
0f602e3f 292 public function postProcess() {
922becfb
PN
293 $submittedValues = $this->controller->exportValues($this->_name);
294 $this->submit($submittedValues);
685dc433 295 $childTab = 'contribute';
0f602e3f 296 if ($this->_component == 'event') {
685dc433 297 $childTab = 'participant';
0f602e3f 298 }
922becfb
PN
299 $session = CRM_Core_Session::singleton();
300 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
301 "reset=1&cid={$this->_contactId}&selectedChild={$childTab}"
302 ));
303 }
304
305 /**
306 * Process Payments.
44a2f017 307 *
922becfb
PN
308 * @param array $submittedValues
309 *
44a2f017 310 * @throws \CiviCRM_API3_Exception
922becfb
PN
311 */
312 public function submit($submittedValues) {
80c9b98c
PN
313 $this->_params = $submittedValues;
314 $this->beginPostProcess();
23cb875c 315 $this->_contributorContactID = $this->_contactID;
316 $this->processBillingAddress();
922becfb
PN
317 $participantId = NULL;
318 if ($this->_component == 'event') {
319 $participantId = $this->_id;
320 }
f7fb5615 321
0f602e3f
PJ
322 if ($this->_mode) {
323 // process credit card
820fbcfb 324 $this->assign('contributeMode', 'direct');
23cb875c 325 $this->processCreditCard();
0f602e3f 326 }
aac57c29 327
b4c48831 328 // @todo we should clean $ on the form & pass in skipCleanMoney
bd981689 329 $trxnsData = $this->_params;
330 if ($this->_paymentType == 'refund') {
331 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
332 }
333 $trxnsData['participant_id'] = $participantId;
334 $trxnsData['contribution_id'] = $this->_contributionId;
335 // From the
336 $trxnsData['is_send_contribution_notification'] = FALSE;
337 $paymentID = civicrm_api3('Payment', 'create', $trxnsData)['id'];
338
94c8aed1 339 if ($this->_contributionId && CRM_Core_Permission::access('CiviMember')) {
be2fb01f 340 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', ['contribution_id' => $this->_contributionId]);
5a53dd1f 341 if ($membershipPaymentCount) {
94c8aed1
E
342 $this->ajaxResponse['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact::getCountComponent('membership', $this->_contactID);
343 }
344 }
5a53dd1f 345 if ($this->_contributionId && CRM_Core_Permission::access('CiviEvent')) {
be2fb01f 346 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', ['contribution_id' => $this->_contributionId]);
5a53dd1f
E
347 if ($participantPaymentCount) {
348 $this->ajaxResponse['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact::getCountComponent('participant', $this->_contactID);
349 }
350 }
922becfb
PN
351
352 $statusMsg = ts('The payment record has been processed.');
353 // send email
957655fe 354 if (!empty($paymentID) && !empty($this->_params['is_email_receipt'])) {
44a2f017 355 $sendResult = civicrm_api3('Payment', 'sendconfirmation', ['id' => $paymentID, 'from' => $submittedValues['from_email_address']])['values'][$paymentID];
08d0eaac 356 if ($sendResult['is_sent']) {
aac57c29
PJ
357 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
358 }
0f602e3f 359 }
922becfb
PN
360
361 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
0f602e3f 362 }
bd99f5fe 363
23cb875c 364 public function processCreditCard() {
b4989753
PJ
365 $config = CRM_Core_Config::singleton();
366 $session = CRM_Core_Session::singleton();
367
b4989753 368 $now = date('YmdHis');
be2fb01f 369 $fields = [];
b4989753
PJ
370
371 // we need to retrieve email address
23cb875c 372 if ($this->_context == 'standalone' && !empty($this->_params['is_email_receipt'])) {
b4989753
PJ
373 list($this->userDisplayName,
374 $this->userEmail
353ffa53 375 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactId);
b4989753
PJ
376 $this->assign('displayName', $this->userDisplayName);
377 }
378
b4989753 379 $this->_params['amount'] = $this->_params['total_amount'];
c039f658 380 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
381 // function to get correct amount level consistently. Remove setting of the amount level in
382 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
383 // to cover all variants.
b4989753
PJ
384 $this->_params['amount_level'] = 0;
385 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
386 $this->_params,
387 $config->defaultCurrency
388 );
aefd7f6b 389
b4989753
PJ
390 if (empty($this->_params['invoice_id'])) {
391 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
392 }
393 else {
394 $this->_params['invoiceID'] = $this->_params['invoice_id'];
395 }
396
0b50eca0 397 $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
23cb875c 398 $this->_params,
0b50eca0 399 $this->_bltID
400 ));
401
b4989753 402 //Add common data to formatted params
23cb875c 403 $params = $this->_params;
b4989753
PJ
404 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
405 // at this point we've created a contact and stored its address etc
406 // all the payment processors expect the name and address to be in the
407 // so we copy stuff over to first_name etc.
408 $paymentParams = $this->_params;
409 $paymentParams['contactID'] = $this->_contactId;
410 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
411
b4989753 412 $paymentParams['contributionPageID'] = NULL;
a7488080 413 if (!empty($this->_params['is_email_receipt'])) {
b4989753 414 $paymentParams['email'] = $this->_contributorEmail;
23cb875c 415 $paymentParams['is_email_receipt'] = TRUE;
b4989753
PJ
416 }
417 else {
23cb875c 418 $paymentParams['is_email_receipt'] = $this->_params['is_email_receipt'] = FALSE;
b4989753
PJ
419 }
420
421 $result = NULL;
422
423 if ($paymentParams['amount'] > 0.0) {
248141b9
EM
424 try {
425 // force a reget of the payment processor in case the form changed it, CRM-7179
426 $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
427 $result = $payment->doPayment($paymentParams);
428 }
429 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
23cb875c 430 Civi::log()->error('Payment processor exception: ' . $e->getMessage());
431 $urlParams = "action=add&cid={$this->_contactId}&id={$this->_contributionId}&component={$this->_component}&mode={$this->_mode}";
c042247c 432 CRM_Core_Error::statusBounce($e->getMessage(), CRM_Utils_System::url('civicrm/payment/add', $urlParams));
b4989753 433 }
b4989753
PJ
434 }
435
23cb875c 436 if (!empty($result)) {
b4989753
PJ
437 $this->_params = array_merge($this->_params, $result);
438 }
439
b4989753 440 $this->set('params', $this->_params);
b4989753
PJ
441
442 // set source if not set
443 if (empty($this->_params['source'])) {
444 $userID = $session->get('userID');
445 $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
446 'sort_name'
447 );
be2fb01f 448 $this->_params['source'] = ts('Submit Credit Card Payment by: %1', [1 => $userSortName]);
b4989753 449 }
b4989753
PJ
450 }
451
61bfc595
PN
452 /**
453 * Wrapper for unit testing the post process submit function.
454 *
61bfc595
PN
455 * @param array $params
456 * @param string|null $creditCardMode
9fbf312f 457 * @param string $entityType
61bfc595
PN
458 *
459 * @throws \CiviCRM_API3_Exception
460 */
9fbf312f 461 public function testSubmit($params, $creditCardMode = NULL, $entityType = 'contribute') {
61bfc595 462 $this->_bltID = 5;
80c9b98c
PN
463 // Required because processCreditCard calls set method on this.
464 $_SERVER['REQUEST_METHOD'] = 'GET';
465 $this->controller = new CRM_Core_Controller();
466
467 $this->assignPaymentRelatedVariables();
9fbf312f 468
61bfc595
PN
469 if (!empty($params['contribution_id'])) {
470 $this->_contributionId = $params['contribution_id'];
471
9fbf312f 472 $paymentDetails = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_contributionId, $entityType, FALSE, TRUE);
61bfc595 473
a168b222 474 $paymentAmount = CRM_Contribute_BAO_Contribution::getContributionBalance($this->_contributionId);
61bfc595
PN
475 $this->_amtPaid = $paymentDetails['paid'];
476 $this->_amtTotal = $paymentDetails['total'];
477
a168b222 478 if ($paymentAmount < 0) {
479 $this->_refund = $paymentAmount;
61bfc595
PN
480 $this->_paymentType = 'refund';
481 }
a168b222 482 elseif ($paymentAmount > 0) {
483 $this->_owed = $paymentAmount;
61bfc595
PN
484 $this->_paymentType = 'owed';
485 }
486 }
487
488 if (!empty($params['contact_id'])) {
489 $this->_contactId = $params['contact_id'];
490 }
491
492 if ($creditCardMode) {
493 $this->_mode = $creditCardMode;
494 }
495
be2fb01f 496 $this->_fields = [];
23cb875c 497 $this->set('cid', $this->_contactId);
498 parent::preProcess();
61bfc595
PN
499 $this->submit($params);
500 }
501
d5397f2f 502}