3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This form records additional payments needed when event/contribution is partially paid.
21 class CRM_Contribute_Form_AdditionalPayment
extends CRM_Contribute_Form_AbstractEditPayment
{
22 public $_contributeMode = 'direct';
25 * Id of the component entity
30 protected $entity = 'Contribution';
32 protected $_owed = NULL;
34 protected $_refund = NULL;
38 * @deprecated - use parent $this->contactID
40 protected $_contactId = NULL;
42 protected $_contributorDisplayName = NULL;
44 protected $_contributorEmail = NULL;
46 protected $_toDoNotEmail = NULL;
48 protected $_paymentType = NULL;
50 protected $_contributionId = NULL;
52 protected $fromEmailId = NULL;
54 protected $_view = NULL;
56 public $_action = NULL;
61 * @throws \CRM_Core_Exception
63 public function preProcess() {
65 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this, TRUE);
67 $this->_contactId
= $this->_contactID
;
68 $this->_component
= CRM_Utils_Request
::retrieve('component', 'String', $this, FALSE, 'contribution');
69 $this->_view
= CRM_Utils_Request
::retrieve('view', 'String', $this, FALSE);
70 $this->assign('component', $this->_component
);
71 $this->assign('id', $this->_id
);
72 $this->assign('suppressPaymentFormButtons', $this->isBeingCalledFromSelectorContext());
74 if ($this->_view
== 'transaction' && ($this->_action
& CRM_Core_Action
::BROWSE
)) {
75 $title = $this->assignPaymentInfoBlock();
76 CRM_Utils_System
::setTitle($title);
79 if ($this->_component
== 'event') {
80 $this->_contributionId
= CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'contribution_id', 'participant_id');
83 $this->_contributionId
= $this->_id
;
86 $paymentDetails = CRM_Contribute_BAO_Contribution
::getPaymentInfo($this->_id
, $this->_component
, FALSE, TRUE);
87 $paymentAmt = CRM_Contribute_BAO_Contribution
::getContributionBalance($this->_contributionId
);
89 $this->_amtPaid
= $paymentDetails['paid'];
90 $this->_amtTotal
= $paymentDetails['total'];
92 if ($paymentAmt < 0) {
93 $this->_refund
= $paymentAmt;
94 $this->_paymentType
= 'refund';
96 elseif ($paymentAmt > 0) {
97 $this->_owed
= $paymentAmt;
98 $this->_paymentType
= 'owed';
101 throw new CRM_Core_Exception(ts('No payment information found for this record'));
104 if (!empty($this->_mode
) && $this->_paymentType
== 'refund') {
105 throw new CRM_Core_Exception(ts('Credit card payment is not for Refund payments use'));
108 list($this->_contributorDisplayName
, $this->_contributorEmail
) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
110 $this->assign('contributionMode', $this->_mode
);
111 $this->assign('contactId', $this->_contactID
);
112 $this->assign('paymentType', $this->_paymentType
);
113 $this->assign('paymentAmt', abs($paymentAmt));
115 $this->setPageTitle($this->_refund ?
ts('Refund') : ts('Payment'));
119 * Is this function being called from a datatable selector.
121 * If so we don't want to show the buttons.
123 * @throws \CRM_Core_Exception
125 protected function isBeingCalledFromSelectorContext() {
126 return CRM_Utils_Request
::retrieve('selector', 'Positive');
130 * This virtual function is used to set the default values of
131 * various form elements
136 * reference to the array of default values
142 public function setDefaultValues() {
143 if ($this->_view
== 'transaction' && ($this->_action
& CRM_Core_Action
::BROWSE
)) {
148 CRM_Core_Payment_Form
::setDefaultValues($this, $this->_contactId
);
149 $defaults = array_merge($defaults, $this->_defaults
);
152 if (empty($defaults['trxn_date'])) {
153 $defaults['trxn_date'] = date('Y-m-d H:i:s');
156 if ($this->_refund
) {
157 $defaults['total_amount'] = CRM_Utils_Money
::format(abs($this->_refund
), NULL, NULL, TRUE);
159 elseif ($this->_owed
) {
160 $defaults['total_amount'] = CRM_Utils_Money
::formatLocaleNumericRoundedForDefaultCurrency($this->_owed
);
163 // Set $newCredit variable in template to control whether link to credit card mode is included
164 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
169 * Build the form object.
171 public function buildQuickForm() {
172 if ($this->_view
== 'transaction' && ($this->_action
& CRM_Core_Action
::BROWSE
)) {
176 'name' => ts('Done'),
177 'spacing' => ' ',
184 CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE, CRM_Utils_Request
::retrieve('payment_instrument_id', 'Integer'));
185 $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors
, NULL);
187 $attributes = CRM_Core_DAO
::getAttribute('CRM_Financial_DAO_FinancialTrxn');
189 $label = ($this->_refund
) ?
ts('Refund Amount') : ts('Payment Amount');
190 $this->addMoney('total_amount',
193 $attributes['total_amount'],
194 TRUE, 'currency', NULL
197 //add receipt for offline contribution
198 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
200 if ($this->_component
=== 'event') {
201 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $this->_id
, 'event_id', 'id');
204 $this->add('select', 'from_email_address', ts('Receipt From'), CRM_Financial_BAO_Payment
::getValidFromEmailsForPayment($eventID ??
NULL));
206 $this->add('textarea', 'receipt_text', ts('Confirmation Message'));
208 $dateLabel = ($this->_refund
) ?
ts('Refund Date') : ts('Date Received');
209 $this->addField('trxn_date', ['entity' => 'FinancialTrxn', 'label' => $dateLabel, 'context' => 'Contribution'], FALSE, FALSE);
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]);
219 $this->assign('displayName', $this->_contributorDisplayName
);
220 $this->assign('component', $this->_component
);
221 $this->assign('email', $this->_contributorEmail
);
224 // render backoffice payment fields only on offline mode
226 $js = ['onclick' => 'return verify( );'];
228 $this->add('select', 'payment_instrument_id',
229 ts('Payment Method'),
230 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::paymentInstrument(),
232 ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
235 $this->add('text', 'check_number', ts('Check Number'), $attributes['financial_trxn_check_number']);
236 $this->add('text', 'trxn_id', ts('Transaction ID'), ['class' => 'twelve'] +
$attributes['trxn_id']);
238 $this->add('text', 'fee_amount', ts('Fee Amount'),
239 $attributes['fee_amount']
241 $this->addRule('fee_amount', ts('Please enter a valid monetary value for Fee Amount.'), 'money');
244 $buttonName = $this->_refund ?
ts('Record Refund') : ts('Record Payment');
248 'name' => $buttonName,
254 'name' => ts('Cancel'),
257 $mailingInfo = Civi
::settings()->get('mailing_backend');
258 $this->assign('outBound_option', $mailingInfo['outBound_option']);
260 $this->addFormRule(['CRM_Contribute_Form_AdditionalPayment', 'formRule'], $this);
270 public static function formRule($fields, $files, $self) {
272 if ($self->_paymentType
== 'owed' && (int) $fields['total_amount'] > (int) $self->_owed
) {
273 $errors['total_amount'] = ts('Payment amount cannot be greater than owed amount');
275 if ($self->_paymentType
== 'refund' && $fields['total_amount'] != abs($self->_refund
)) {
276 $errors['total_amount'] = ts('Refund amount must equal refund due amount.');
279 if ($self->_paymentProcessor
['id'] === 0 && empty($fields['payment_instrument_id'])) {
280 $errors['payment_instrument_id'] = ts('Payment method is a required field');
287 * Process the form submission.
289 public function postProcess() {
290 $submittedValues = $this->controller
->exportValues($this->_name
);
291 $this->submit($submittedValues);
292 $childTab = 'contribute';
293 if ($this->_component
== 'event') {
294 $childTab = 'participant';
296 $session = CRM_Core_Session
::singleton();
297 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
298 "reset=1&cid={$this->_contactId}&selectedChild={$childTab}"
305 * @param array $submittedValues
307 * @throws \CiviCRM_API3_Exception
309 public function submit($submittedValues) {
310 $this->_params
= $submittedValues;
311 $this->beginPostProcess();
312 $this->_contributorContactID
= $this->_contactID
;
313 $this->processBillingAddress();
314 $participantId = NULL;
315 if ($this->_component
== 'event') {
316 $participantId = $this->_id
;
320 // process credit card
321 $this->assign('contributeMode', 'direct');
322 $this->processCreditCard();
325 // @todo we should clean $ on the form & pass in skipCleanMoney
326 $trxnsData = $this->_params
;
327 if ($this->_paymentType
== 'refund') {
328 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
330 $trxnsData['participant_id'] = $participantId;
331 $trxnsData['contribution_id'] = $this->_contributionId
;
333 $trxnsData['is_send_contribution_notification'] = FALSE;
334 $paymentID = civicrm_api3('Payment', 'create', $trxnsData)['id'];
336 if ($this->_contributionId
&& CRM_Core_Permission
::access('CiviMember')) {
337 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', ['contribution_id' => $this->_contributionId
]);
338 if ($membershipPaymentCount) {
339 $this->ajaxResponse
['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactID
);
342 if ($this->_contributionId
&& CRM_Core_Permission
::access('CiviEvent')) {
343 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', ['contribution_id' => $this->_contributionId
]);
344 if ($participantPaymentCount) {
345 $this->ajaxResponse
['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact
::getCountComponent('participant', $this->_contactID
);
349 $statusMsg = ts('The payment record has been processed.');
351 if (!empty($paymentID) && !empty($this->_params
['is_email_receipt'])) {
352 $sendResult = civicrm_api3('Payment', 'sendconfirmation', ['id' => $paymentID, 'from' => $submittedValues['from_email_address']])['values'][$paymentID];
353 if ($sendResult['is_sent']) {
354 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
358 CRM_Core_Session
::setStatus($statusMsg, ts('Saved'), 'success');
361 public function processCreditCard() {
362 $config = CRM_Core_Config
::singleton();
363 $session = CRM_Core_Session
::singleton();
365 $now = date('YmdHis');
368 // we need to retrieve email address
369 if ($this->_context
== 'standalone' && !empty($this->_params
['is_email_receipt'])) {
370 list($this->userDisplayName
,
372 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactId
);
373 $this->assign('displayName', $this->userDisplayName
);
376 $this->_params
['amount'] = $this->_params
['total_amount'];
377 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
378 // function to get correct amount level consistently. Remove setting of the amount level in
379 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
380 // to cover all variants.
381 $this->_params
['amount_level'] = 0;
382 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
384 $config->defaultCurrency
387 if (empty($this->_params
['invoice_id'])) {
388 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
391 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
394 $this->assign('address', CRM_Utils_Address
::getFormattedBillingAddressFieldsFromParameters(
399 //Add common data to formatted params
400 $params = $this->_params
;
401 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
402 // at this point we've created a contact and stored its address etc
403 // all the payment processors expect the name and address to be in the
404 // so we copy stuff over to first_name etc.
405 $paymentParams = $this->_params
;
406 $paymentParams['contactID'] = $this->_contactId
;
407 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
409 $paymentParams['contributionPageID'] = NULL;
410 if (!empty($this->_params
['is_email_receipt'])) {
411 $paymentParams['email'] = $this->_contributorEmail
;
412 $paymentParams['is_email_receipt'] = TRUE;
415 $paymentParams['is_email_receipt'] = $this->_params
['is_email_receipt'] = FALSE;
420 if ($paymentParams['amount'] > 0.0) {
422 // force a reget of the payment processor in case the form changed it, CRM-7179
423 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
424 $result = $payment->doPayment($paymentParams);
426 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
427 Civi
::log()->error('Payment processor exception: ' . $e->getMessage());
428 $urlParams = "action=add&cid={$this->_contactId}&id={$this->_contributionId}&component={$this->_component}&mode={$this->_mode}";
429 CRM_Core_Error
::statusBounce($e->getMessage(), CRM_Utils_System
::url('civicrm/payment/add', $urlParams));
433 if (!empty($result)) {
434 $this->_params
= array_merge($this->_params
, $result);
437 $this->set('params', $this->_params
);
439 // set source if not set
440 if (empty($this->_params
['source'])) {
441 $userID = $session->get('userID');
442 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
445 $this->_params
['source'] = ts('Submit Credit Card Payment by: %1', [1 => $userSortName]);
450 * Wrapper for unit testing the post process submit function.
452 * @param array $params
453 * @param string|null $creditCardMode
454 * @param string $entityType
456 * @throws \CiviCRM_API3_Exception
458 public function testSubmit($params, $creditCardMode = NULL, $entityType = 'contribute') {
460 // Required because processCreditCard calls set method on this.
461 $_SERVER['REQUEST_METHOD'] = 'GET';
462 $this->controller
= new CRM_Core_Controller();
464 $this->assignPaymentRelatedVariables();
466 if (!empty($params['contribution_id'])) {
467 $this->_contributionId
= $params['contribution_id'];
469 $paymentDetails = CRM_Contribute_BAO_Contribution
::getPaymentInfo($this->_contributionId
, $entityType, FALSE, TRUE);
471 $paymentAmount = CRM_Contribute_BAO_Contribution
::getContributionBalance($this->_contributionId
);
472 $this->_amtPaid
= $paymentDetails['paid'];
473 $this->_amtTotal
= $paymentDetails['total'];
475 if ($paymentAmount < 0) {
476 $this->_refund
= $paymentAmount;
477 $this->_paymentType
= 'refund';
479 elseif ($paymentAmount > 0) {
480 $this->_owed
= $paymentAmount;
481 $this->_paymentType
= 'owed';
485 if (!empty($params['contact_id'])) {
486 $this->_contactId
= $params['contact_id'];
489 if ($creditCardMode) {
490 $this->_mode
= $creditCardMode;
494 $this->set('cid', $this->_contactId
);
495 parent
::preProcess();
496 $this->submit($params);