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');
263 $buttonName = $this->_refund ?
ts('Record Refund') : ts('Record Payment');
267 'name' => $buttonName,
273 'name' => ts('Cancel'),
276 $mailingInfo = Civi
::settings()->get('mailing_backend');
277 $this->assign('outBound_option', $mailingInfo['outBound_option']);
279 $this->addFormRule(['CRM_Contribute_Form_AdditionalPayment', 'formRule'], $this);
289 public static function formRule($fields, $files, $self) {
291 if ($self->_paymentType
== 'owed' && $fields['total_amount'] > $self->_owed
) {
292 $errors['total_amount'] = ts('Payment amount cannot be greater than owed amount');
294 if ($self->_paymentType
== 'refund' && $fields['total_amount'] != abs($self->_refund
)) {
295 $errors['total_amount'] = ts('Refund amount must equal refund due amount.');
298 if ($self->_paymentProcessor
['id'] === 0 && empty($fields['payment_instrument_id'])) {
299 $errors['payment_instrument_id'] = ts('Payment method is a required field');
306 * Process the form submission.
308 public function postProcess() {
309 $submittedValues = $this->controller
->exportValues($this->_name
);
310 $this->submit($submittedValues);
311 $childTab = 'contribute';
312 if ($this->_component
== 'event') {
313 $childTab = 'participant';
315 $session = CRM_Core_Session
::singleton();
316 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
317 "reset=1&cid={$this->_contactId}&selectedChild={$childTab}"
324 * @param array $submittedValues
326 * @throws \CiviCRM_API3_Exception
328 public function submit($submittedValues) {
329 $this->_params
= $submittedValues;
330 $this->beginPostProcess();
331 $this->_contributorContactID
= $this->_contactID
;
332 $this->processBillingAddress();
333 $participantId = NULL;
334 if ($this->_component
== 'event') {
335 $participantId = $this->_id
;
339 // process credit card
340 $this->assign('contributeMode', 'direct');
341 $this->processCreditCard();
344 // @todo we should clean $ on the form & pass in skipCleanMoney
345 $trxnsData = $this->_params
;
346 if ($this->_paymentType
== 'refund') {
347 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
349 $trxnsData['participant_id'] = $participantId;
350 $trxnsData['contribution_id'] = $this->_contributionId
;
352 $trxnsData['is_send_contribution_notification'] = FALSE;
353 $paymentID = civicrm_api3('Payment', 'create', $trxnsData)['id'];
355 if ($this->_contributionId
&& CRM_Core_Permission
::access('CiviMember')) {
356 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', ['contribution_id' => $this->_contributionId
]);
357 if ($membershipPaymentCount) {
358 $this->ajaxResponse
['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactID
);
361 if ($this->_contributionId
&& CRM_Core_Permission
::access('CiviEvent')) {
362 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', ['contribution_id' => $this->_contributionId
]);
363 if ($participantPaymentCount) {
364 $this->ajaxResponse
['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact
::getCountComponent('participant', $this->_contactID
);
368 $statusMsg = ts('The payment record has been processed.');
370 if (!empty($paymentID) && !empty($this->_params
['is_email_receipt'])) {
371 $sendResult = civicrm_api3('Payment', 'sendconfirmation', ['id' => $paymentID, 'from' => $submittedValues['from_email_address']])['values'][$paymentID];
372 if ($sendResult['is_sent']) {
373 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
377 CRM_Core_Session
::setStatus($statusMsg, ts('Saved'), 'success');
380 public function processCreditCard() {
381 $config = CRM_Core_Config
::singleton();
382 $session = CRM_Core_Session
::singleton();
384 $now = date('YmdHis');
387 // we need to retrieve email address
388 if ($this->_context
== 'standalone' && !empty($this->_params
['is_email_receipt'])) {
389 list($this->userDisplayName
,
391 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactId
);
392 $this->assign('displayName', $this->userDisplayName
);
395 $this->_params
['amount'] = $this->_params
['total_amount'];
396 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
397 // function to get correct amount level consistently. Remove setting of the amount level in
398 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
399 // to cover all variants.
400 $this->_params
['amount_level'] = 0;
401 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
403 $config->defaultCurrency
406 if (empty($this->_params
['invoice_id'])) {
407 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
410 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
413 $this->assign('address', CRM_Utils_Address
::getFormattedBillingAddressFieldsFromParameters(
418 //Add common data to formatted params
419 $params = $this->_params
;
420 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
421 // at this point we've created a contact and stored its address etc
422 // all the payment processors expect the name and address to be in the
423 // so we copy stuff over to first_name etc.
424 $paymentParams = $this->_params
;
425 $paymentParams['contactID'] = $this->_contactId
;
426 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
428 $paymentParams['contributionPageID'] = NULL;
429 if (!empty($this->_params
['is_email_receipt'])) {
430 $paymentParams['email'] = $this->_contributorEmail
;
431 $paymentParams['is_email_receipt'] = TRUE;
434 $paymentParams['is_email_receipt'] = $this->_params
['is_email_receipt'] = FALSE;
439 if ($paymentParams['amount'] > 0.0) {
441 // force a reget of the payment processor in case the form changed it, CRM-7179
442 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
443 $result = $payment->doPayment($paymentParams);
445 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
446 Civi
::log()->error('Payment processor exception: ' . $e->getMessage());
447 $urlParams = "action=add&cid={$this->_contactId}&id={$this->_contributionId}&component={$this->_component}&mode={$this->_mode}";
448 CRM_Core_Error
::statusBounce($e->getMessage(), CRM_Utils_System
::url('civicrm/payment/add', $urlParams));
452 if (!empty($result)) {
453 $this->_params
= array_merge($this->_params
, $result);
456 $this->set('params', $this->_params
);
458 // set source if not set
459 if (empty($this->_params
['source'])) {
460 $userID = $session->get('userID');
461 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
464 $this->_params
['source'] = ts('Submit Credit Card Payment by: %1', [1 => $userSortName]);
469 * Wrapper for unit testing the post process submit function.
471 * @param array $params
472 * @param string|null $creditCardMode
473 * @param string $entityType
475 * @throws \CiviCRM_API3_Exception
477 public function testSubmit($params, $creditCardMode = NULL, $entityType = 'contribute') {
479 // Required because processCreditCard calls set method on this.
480 $_SERVER['REQUEST_METHOD'] = 'GET';
481 $this->controller
= new CRM_Core_Controller();
483 $this->assignPaymentRelatedVariables();
485 if (!empty($params['contribution_id'])) {
486 $this->_contributionId
= $params['contribution_id'];
488 $paymentDetails = CRM_Contribute_BAO_Contribution
::getPaymentInfo($this->_contributionId
, $entityType, FALSE, TRUE);
490 $paymentAmount = CRM_Contribute_BAO_Contribution
::getContributionBalance($this->_contributionId
);
491 $this->_amtPaid
= $paymentDetails['paid'];
492 $this->_amtTotal
= $paymentDetails['total'];
494 if ($paymentAmount < 0) {
495 $this->_refund
= $paymentAmount;
496 $this->_paymentType
= 'refund';
498 elseif ($paymentAmount > 0) {
499 $this->_owed
= $paymentAmount;
500 $this->_paymentType
= 'owed';
504 if (!empty($params['contact_id'])) {
505 $this->_contactId
= $params['contact_id'];
508 if ($creditCardMode) {
509 $this->_mode
= $creditCardMode;
513 $this->set('cid', $this->_contactId
);
514 parent
::preProcess();
515 $this->submit($params);