3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * This form records additional payments needed when event/contribution is partially paid.
37 class CRM_Contribute_Form_AdditionalPayment
extends CRM_Contribute_Form_AbstractEditPayment
{
38 public $_contributeMode = 'direct';
41 * Id of the component entity
46 protected $entity = 'Contribution';
48 protected $_owed = NULL;
50 protected $_refund = NULL;
54 * @deprecated - use parent $this->contactID
56 protected $_contactId = NULL;
58 protected $_contributorDisplayName = NULL;
60 protected $_contributorEmail = NULL;
62 protected $_toDoNotEmail = NULL;
64 protected $_paymentType = NULL;
66 protected $_contributionId = NULL;
68 protected $fromEmailId = NULL;
70 protected $_view = NULL;
72 public $_action = NULL;
77 * @throws \CRM_Core_Exception
79 public function preProcess() {
81 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this, TRUE);
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());
90 if ($this->_view
== 'transaction' && ($this->_action
& CRM_Core_Action
::BROWSE
)) {
91 $title = $this->assignPaymentInfoBlock();
92 CRM_Utils_System
::setTitle($title);
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');
102 $this->_contributionId
= $this->_id
;
105 $paymentDetails = CRM_Contribute_BAO_Contribution
::getPaymentInfo($this->_id
, $this->_component
, FALSE, TRUE);
106 $paymentAmt = CRM_Contribute_BAO_Contribution
::getContributionBalance($this->_id
);
108 $this->_amtPaid
= $paymentDetails['paid'];
109 $this->_amtTotal
= $paymentDetails['total'];
111 if ($paymentAmt < 0) {
112 $this->_refund
= $paymentAmt;
113 $this->_paymentType
= 'refund';
115 elseif ($paymentAmt > 0) {
116 $this->_owed
= $paymentAmt;
117 $this->_paymentType
= 'owed';
120 throw new CRM_Core_Exception(ts('No payment information found for this record'));
123 if (!empty($this->_mode
) && $this->_paymentType
== 'refund') {
124 throw new CRM_Core_Exception(ts('Credit card payment is not for Refund payments use'));
127 list($this->_contributorDisplayName
, $this->_contributorEmail
) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
129 $this->assign('contributionMode', $this->_mode
);
130 $this->assign('contactId', $this->_contactID
);
131 $this->assign('paymentType', $this->_paymentType
);
132 $this->assign('paymentAmt', abs($paymentAmt));
134 $this->setPageTitle($this->_refund ?
ts('Refund') : ts('Payment'));
138 * Is this function being called from a datatable selector.
140 * If so we don't want to show the buttons.
142 * @throws \CRM_Core_Exception
144 protected function isBeingCalledFromSelectorContext() {
145 return CRM_Utils_Request
::retrieve('selector', 'Positive');
149 * This virtual function is used to set the default values of
150 * various form elements
155 * reference to the array of default values
161 public function setDefaultValues() {
162 if ($this->_view
== 'transaction' && ($this->_action
& CRM_Core_Action
::BROWSE
)) {
167 CRM_Core_Payment_Form
::setDefaultValues($this, $this->_contactId
);
168 $defaults = array_merge($defaults, $this->_defaults
);
171 if (empty($defaults['trxn_date'])) {
172 $defaults['trxn_date'] = date('Y-m-d H:i:s');
175 if ($this->_refund
) {
176 $defaults['total_amount'] = CRM_Utils_Money
::format(abs($this->_refund
), NULL, NULL, TRUE);
178 elseif ($this->_owed
) {
179 $defaults['total_amount'] = CRM_Utils_Money
::formatLocaleNumericRoundedForDefaultCurrency($this->_owed
);
182 // Set $newCredit variable in template to control whether link to credit card mode is included
183 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
188 * Build the form object.
190 public function buildQuickForm() {
191 if ($this->_view
== 'transaction' && ($this->_action
& CRM_Core_Action
::BROWSE
)) {
195 'name' => ts('Done'),
196 'spacing' => ' ',
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);
206 $attributes = CRM_Core_DAO
::getAttribute('CRM_Financial_DAO_FinancialTrxn');
208 $label = ($this->_refund
) ?
ts('Refund Amount') : ts('Payment Amount');
209 $this->addMoney('total_amount',
212 $attributes['total_amount'],
213 TRUE, 'currency', NULL
216 //add receipt for offline contribution
217 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
219 if ($this->_component
=== 'event') {
220 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $this->_id
, 'event_id', 'id');
223 $this->add('select', 'from_email_address', ts('Receipt From'), CRM_Financial_BAO_Payment
::getValidFromEmailsForPayment($eventID ??
NULL));
225 $this->add('textarea', 'receipt_text', ts('Confirmation Message'));
227 $dateLabel = ($this->_refund
) ?
ts('Refund Date') : ts('Date Received');
228 $this->addField('trxn_date', ['entity' => 'FinancialTrxn', 'label' => $dateLabel, 'context' => 'Contribution'], FALSE, FALSE);
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]);
238 $this->assign('displayName', $this->_contributorDisplayName
);
239 $this->assign('component', $this->_component
);
240 $this->assign('email', $this->_contributorEmail
);
243 // render backoffice payment fields only on offline mode
245 $js = ['onclick' => "return verify( );"];
247 $this->add('select', 'payment_instrument_id',
248 ts('Payment Method'),
249 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::paymentInstrument(),
251 ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
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']);
257 $this->add('text', 'fee_amount', ts('Fee Amount'),
258 $attributes['fee_amount']
260 $this->addRule('fee_amount', ts('Please enter a valid monetary value for Fee Amount.'), 'money');
262 $this->add('text', 'net_amount', ts('Net Amount'),
263 $attributes['net_amount']
265 $this->addRule('net_amount', ts('Please enter a valid monetary value for Net Amount.'), 'money');
268 $buttonName = $this->_refund ?
ts('Record Refund') : ts('Record Payment');
272 'name' => $buttonName,
278 'name' => ts('Cancel'),
281 $mailingInfo = Civi
::settings()->get('mailing_backend');
282 $this->assign('outBound_option', $mailingInfo['outBound_option']);
284 $this->addFormRule(['CRM_Contribute_Form_AdditionalPayment', 'formRule'], $this);
294 public static function formRule($fields, $files, $self) {
296 if ($self->_paymentType
== 'owed' && $fields['total_amount'] > $self->_owed
) {
297 $errors['total_amount'] = ts('Payment amount cannot be greater than owed amount');
299 if ($self->_paymentType
== 'refund' && $fields['total_amount'] != abs($self->_refund
)) {
300 $errors['total_amount'] = ts('Refund amount must equal refund due amount.');
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.');
306 if ($self->_paymentProcessor
['id'] === 0 && empty($fields['payment_instrument_id'])) {
307 $errors['payment_instrument_id'] = ts('Payment method is a required field');
314 * Process the form submission.
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';
323 $session = CRM_Core_Session
::singleton();
324 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
325 "reset=1&cid={$this->_contactId}&selectedChild={$childTab}"
332 * @param array $submittedValues
334 * @throws \CiviCRM_API3_Exception
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
;
347 // process credit card
348 $this->assign('contributeMode', 'direct');
349 $this->processCreditCard();
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'];
357 $trxnsData['participant_id'] = $participantId;
358 $trxnsData['contribution_id'] = $this->_contributionId
;
360 $trxnsData['is_send_contribution_notification'] = FALSE;
361 $paymentID = civicrm_api3('Payment', 'create', $trxnsData)['id'];
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
);
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
);
376 $statusMsg = ts('The payment record has been processed.');
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.');
385 CRM_Core_Session
::setStatus($statusMsg, ts('Saved'), 'success');
388 public function processCreditCard() {
389 $config = CRM_Core_Config
::singleton();
390 $session = CRM_Core_Session
::singleton();
392 $now = date('YmdHis');
395 // we need to retrieve email address
396 if ($this->_context
== 'standalone' && !empty($this->_params
['is_email_receipt'])) {
397 list($this->userDisplayName
,
399 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactId
);
400 $this->assign('displayName', $this->userDisplayName
);
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',
411 $config->defaultCurrency
414 if (empty($this->_params
['invoice_id'])) {
415 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
418 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
421 $this->assign('address', CRM_Utils_Address
::getFormattedBillingAddressFieldsFromParameters(
426 //Add common data to formatted params
427 $params = $this->_params
;
428 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
429 // at this point we've created a contact and stored its address etc
430 // all the payment processors expect the name and address to be in the
431 // so we copy stuff over to first_name etc.
432 $paymentParams = $this->_params
;
433 $paymentParams['contactID'] = $this->_contactId
;
434 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
436 $paymentParams['contributionPageID'] = NULL;
437 if (!empty($this->_params
['is_email_receipt'])) {
438 $paymentParams['email'] = $this->_contributorEmail
;
439 $paymentParams['is_email_receipt'] = TRUE;
442 $paymentParams['is_email_receipt'] = $this->_params
['is_email_receipt'] = FALSE;
447 if ($paymentParams['amount'] > 0.0) {
449 // force a reget of the payment processor in case the form changed it, CRM-7179
450 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
451 $result = $payment->doPayment($paymentParams);
453 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
454 Civi
::log()->error('Payment processor exception: ' . $e->getMessage());
455 $urlParams = "action=add&cid={$this->_contactId}&id={$this->_contributionId}&component={$this->_component}&mode={$this->_mode}";
456 CRM_Core_Error
::statusBounce($e->getMessage(), CRM_Utils_System
::url('civicrm/payment/add', $urlParams));
460 if (!empty($result)) {
461 $this->_params
= array_merge($this->_params
, $result);
464 $this->set('params', $this->_params
);
466 // set source if not set
467 if (empty($this->_params
['source'])) {
468 $userID = $session->get('userID');
469 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
472 $this->_params
['source'] = ts('Submit Credit Card Payment by: %1', [1 => $userSortName]);
477 * Wrapper for unit testing the post process submit function.
479 * @param array $params
480 * @param string|null $creditCardMode
481 * @param string $entityType
483 * @throws \CiviCRM_API3_Exception
485 public function testSubmit($params, $creditCardMode = NULL, $entityType = 'contribute') {
487 // Required because processCreditCard calls set method on this.
488 $_SERVER['REQUEST_METHOD'] = 'GET';
489 $this->controller
= new CRM_Core_Controller();
491 $this->assignPaymentRelatedVariables();
493 if (!empty($params['contribution_id'])) {
494 $this->_contributionId
= $params['contribution_id'];
496 $paymentDetails = CRM_Contribute_BAO_Contribution
::getPaymentInfo($this->_contributionId
, $entityType, FALSE, TRUE);
498 $paymentAmount = CRM_Contribute_BAO_Contribution
::getContributionBalance($this->_contributionId
);
499 $this->_amtPaid
= $paymentDetails['paid'];
500 $this->_amtTotal
= $paymentDetails['total'];
502 if ($paymentAmount < 0) {
503 $this->_refund
= $paymentAmount;
504 $this->_paymentType
= 'refund';
506 elseif ($paymentAmount > 0) {
507 $this->_owed
= $paymentAmount;
508 $this->_paymentType
= 'owed';
512 if (!empty($params['contact_id'])) {
513 $this->_contactId
= $params['contact_id'];
516 if ($creditCardMode) {
517 $this->_mode
= $creditCardMode;
521 $this->set('cid', $this->_contactId
);
522 parent
::preProcess();
523 $this->submit($params);