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