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