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