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
45 protected $entity = 'Contribution';
47 protected $_owed = NULL;
49 protected $_refund = NULL;
52 * @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 $_fromEmails = NULL;
72 protected $_view = NULL;
74 public $_action = NULL;
76 public function preProcess() {
78 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this, TRUE);
80 $this->_contactId
= $this->_contactID
;
81 $this->_component
= CRM_Utils_Request
::retrieve('component', 'String', $this, FALSE, 'contribution');
82 $this->_view
= CRM_Utils_Request
::retrieve('view', 'String', $this, FALSE);
83 $this->assign('component', $this->_component
);
84 $this->assign('id', $this->_id
);
85 $this->assign('suppressPaymentFormButtons', $this->isBeingCalledFromSelectorContext());
87 if ($this->_view
== 'transaction' && ($this->_action
& CRM_Core_Action
::BROWSE
)) {
88 $title = $this->assignPaymentInfoBlock();
89 CRM_Utils_System
::setTitle($title);
92 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
94 $entityType = 'contribution';
95 if ($this->_component
== 'event') {
96 $entityType = 'participant';
97 $this->_contributionId
= CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'contribution_id', 'participant_id');
98 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $this->_id
, 'event_id', 'id');
99 $this->_fromEmails
= CRM_Event_BAO_Event
::getFromEmailIds($eventId);
102 $this->_contributionId
= $this->_id
;
103 $this->_fromEmails
['from_email_id'] = CRM_Core_BAO_Email
::getFromEmail();
106 $paymentInfo = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($this->_id
, $entityType);
107 $paymentDetails = CRM_Contribute_BAO_Contribution
::getPaymentInfo($this->_id
, $this->_component
, FALSE, TRUE);
109 $this->_amtPaid
= $paymentDetails['paid'];
110 $this->_amtTotal
= $paymentDetails['total'];
112 if (!empty($paymentInfo['refund_due'])) {
113 $paymentAmt = $this->_refund
= $paymentInfo['refund_due'];
114 $this->_paymentType
= 'refund';
116 elseif (!empty($paymentInfo['amount_owed'])) {
117 $paymentAmt = $this->_owed
= $paymentInfo['amount_owed'];
118 $this->_paymentType
= 'owed';
121 CRM_Core_Error
::fatal(ts('No payment information found for this record'));
124 if (!empty($this->_mode
) && $this->_paymentType
== 'refund') {
125 CRM_Core_Error
::fatal(ts('Credit card payment is not for Refund payments use'));
128 list($this->_contributorDisplayName
, $this->_contributorEmail
) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
130 $this->assign('contributionMode', $this->_mode
);
131 $this->assign('contactId', $this->_contactID
);
132 $this->assign('paymentType', $this->_paymentType
);
133 $this->assign('paymentAmt', abs($paymentAmt));
135 $this->setPageTitle($this->_refund ?
ts('Refund') : ts('Payment'));
139 * Is this function being called from a datatable selector.
141 * If so we don't want to show the buttons.
143 protected function isBeingCalledFromSelectorContext() {
144 return CRM_Utils_Request
::retrieve('selector', 'Positive');
148 * This virtual function is used to set the default values of
149 * various form elements
154 * reference to the array of default values
159 public function setDefaultValues() {
160 if ($this->_view
== 'transaction' && ($this->_action
& CRM_Core_Action
::BROWSE
)) {
165 CRM_Core_Payment_Form
::setDefaultValues($this, $this->_contactId
);
166 $defaults = array_merge($defaults, $this->_defaults
);
169 if (empty($defaults['trxn_date'])) {
170 $defaults['trxn_date'] = date('Y-m-d H:i:s');
173 if ($this->_refund
) {
174 $defaults['total_amount'] = CRM_Utils_Money
::format(abs($this->_refund
), NULL, NULL, TRUE);
176 elseif ($this->_owed
) {
177 $defaults['total_amount'] = CRM_Utils_Money
::formatLocaleNumericRoundedForDefaultCurrency($this->_owed
);
180 // Set $newCredit variable in template to control whether link to credit card mode is included
181 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
186 * Build the form object.
188 public function buildQuickForm() {
189 if ($this->_view
== 'transaction' && ($this->_action
& CRM_Core_Action
::BROWSE
)) {
190 $this->addButtons(array(
193 'name' => ts('Done'),
194 'spacing' => ' ',
202 CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE, CRM_Utils_Request
::retrieve('payment_instrument_id', 'Integer'));
203 $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors
, NULL);
205 $attributes = CRM_Core_DAO
::getAttribute('CRM_Financial_DAO_FinancialTrxn');
207 $label = ($this->_refund
) ?
ts('Refund Amount') : ts('Payment Amount');
208 $this->addMoney('total_amount',
211 $attributes['total_amount'],
212 TRUE, 'currency', NULL
215 //add receipt for offline contribution
216 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
218 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
['from_email_id']);
220 $this->add('textarea', 'receipt_text', ts('Confirmation Message'));
222 $dateLabel = ($this->_refund
) ?
ts('Refund Date') : ts('Date Received');
223 $this->addField('trxn_date', array('entity' => 'FinancialTrxn', 'label' => $dateLabel, 'context' => 'Contribution'), FALSE, FALSE);
225 if ($this->_contactId
&& $this->_id
) {
226 if ($this->_component
== 'event') {
227 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $this->_id
, 'event_id', 'id');
228 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
229 $this->assign('eventName', $event[$eventId]);
233 $this->assign('displayName', $this->_contributorDisplayName
);
234 $this->assign('component', $this->_component
);
235 $this->assign('email', $this->_contributorEmail
);
238 // render backoffice payment fields only on offline mode
240 $js = array('onclick' => "return verify( );");
242 $this->add('select', 'payment_instrument_id',
243 ts('Payment Method'),
244 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
246 array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
249 $this->add('text', 'check_number', ts('Check Number'), $attributes['financial_trxn_check_number']);
250 $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
252 $this->add('text', 'fee_amount', ts('Fee Amount'),
253 $attributes['fee_amount']
255 $this->addRule('fee_amount', ts('Please enter a valid monetary value for Fee Amount.'), 'money');
257 $this->add('text', 'net_amount', ts('Net Amount'),
258 $attributes['net_amount']
260 $this->addRule('net_amount', ts('Please enter a valid monetary value for Net Amount.'), 'money');
263 $buttonName = $this->_refund ?
'Record Refund' : 'Record Payment';
264 $this->addButtons(array(
267 'name' => ts('%1', array(1 => $buttonName)),
273 'name' => ts('Cancel'),
277 $mailingInfo = Civi
::settings()->get('mailing_backend');
278 $this->assign('outBound_option', $mailingInfo['outBound_option']);
280 $this->addFormRule(array('CRM_Contribute_Form_AdditionalPayment', 'formRule'), $this);
290 public static function formRule($fields, $files, $self) {
292 if ($self->_paymentType
== 'owed' && $fields['total_amount'] > $self->_owed
) {
293 $errors['total_amount'] = ts('Payment amount cannot be greater than owed amount');
295 if ($self->_paymentType
== 'refund' && $fields['total_amount'] != abs($self->_refund
)) {
296 $errors['total_amount'] = ts('Refund amount must equal refund due amount.');
298 $netAmt = $fields['total_amount'] - CRM_Utils_Array
::value('fee_amount', $fields, 0);
299 if (!empty($fields['net_amount']) && $netAmt != $fields['net_amount']) {
300 $errors['net_amount'] = ts('Net amount should be equal to the difference between payment amount and fee amount.');
302 if ($self->_paymentProcessor
['id'] === 0 && empty($fields['payment_instrument_id'])) {
303 $errors['payment_instrument_id'] = ts('Payment method is a required field');
310 * Process the form submission.
312 public function postProcess() {
313 $submittedValues = $this->controller
->exportValues($this->_name
);
314 $this->submit($submittedValues);
315 $childTab = 'contribute';
316 if ($this->_component
== 'event') {
317 $childTab = 'participant';
319 $session = CRM_Core_Session
::singleton();
320 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
321 "reset=1&cid={$this->_contactId}&selectedChild={$childTab}"
327 * @param array $submittedValues
330 public function submit($submittedValues) {
331 $this->_params
= $submittedValues;
332 $this->beginPostProcess();
333 $this->_contributorContactID
= $this->_contactID
;
334 $this->processBillingAddress();
335 $participantId = NULL;
336 if ($this->_component
== 'event') {
337 $participantId = $this->_id
;
339 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution',
340 'contribution_status_id',
341 array('labelColumn' => 'name')
343 $contributionStatusID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_contributionId
, 'contribution_status_id');
344 if ($contributionStatuses[$contributionStatusID] == 'Pending') {
345 civicrm_api3('Contribution', 'create',
347 'id' => $this->_contributionId
,
348 'contribution_status_id' => array_search('Partially paid', $contributionStatuses),
355 // process credit card
356 $this->assign('contributeMode', 'direct');
357 $this->processCreditCard();
361 $contribution = civicrm_api3('Contribution', 'getsingle', array(
362 'return' => array("contribution_status_id"),
363 'id' => $this->_contributionId
,
365 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $contribution);
366 $result = CRM_Contribute_BAO_Contribution
::recordAdditionalPayment($this->_contributionId
, $this->_params
, $this->_paymentType
, $participantId);
367 // Fetch the contribution & do proportional line item assignment
368 $params = array('id' => $this->_contributionId
);
369 $contribution = CRM_Contribute_BAO_Contribution
::retrieve($params, $defaults, $params);
370 CRM_Contribute_BAO_Contribution
::addPayments(array($contribution), $contributionStatusId);
371 if ($this->_contributionId
&& CRM_Core_Permission
::access('CiviMember')) {
372 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', array('contribution_id' => $this->_contributionId
));
373 if ($membershipPaymentCount) {
374 $this->ajaxResponse
['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactID
);
377 if ($this->_contributionId
&& CRM_Core_Permission
::access('CiviEvent')) {
378 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', array('contribution_id' => $this->_contributionId
));
379 if ($participantPaymentCount) {
380 $this->ajaxResponse
['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact
::getCountComponent('participant', $this->_contactID
);
384 $statusMsg = ts('The payment record has been processed.');
386 if (!empty($result) && !empty($this->_params
['is_email_receipt'])) {
387 $this->_params
['contact_id'] = $this->_contactId
;
388 $this->_params
['contribution_id'] = $this->_contributionId
;
390 // These 2 rows are temporarily added for sequencing of adding commits. They won't be needed when we
391 // switch to Payment.send_confirmation api
392 $contact = civicrm_api3('Contact', 'getsingle', ['id' => $this->_contactId
, 'return' => 'email_greeting']);
393 $this->assign('emailGreeting', $contact['email_greeting_display']);
395 $sendReceipt = $this->emailReceipt($this->_params
);
397 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
401 CRM_Core_Session
::setStatus($statusMsg, ts('Saved'), 'success');
404 public function processCreditCard() {
405 $config = CRM_Core_Config
::singleton();
406 $session = CRM_Core_Session
::singleton();
408 $now = date('YmdHis');
411 // we need to retrieve email address
412 if ($this->_context
== 'standalone' && !empty($this->_params
['is_email_receipt'])) {
413 list($this->userDisplayName
,
415 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactId
);
416 $this->assign('displayName', $this->userDisplayName
);
419 $this->formatParamsForPaymentProcessor($this->_params
);
421 $this->_params
['amount'] = $this->_params
['total_amount'];
422 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
423 // function to get correct amount level consistently. Remove setting of the amount level in
424 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
425 // to cover all variants.
426 $this->_params
['amount_level'] = 0;
427 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
429 $config->defaultCurrency
432 if (!empty($this->_params
['trxn_date'])) {
433 $this->_params
['receive_date'] = $this->_params
['trxn_date'];
436 if (empty($this->_params
['receive_date'])) {
437 $this->_params
['receive_date'] = date('YmdHis');
440 if (empty($this->_params
['invoice_id'])) {
441 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
444 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
447 $this->assign('address', CRM_Utils_Address
::getFormattedBillingAddressFieldsFromParameters(
452 //Add common data to formatted params
453 $params = $this->_params
;
454 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
455 // at this point we've created a contact and stored its address etc
456 // all the payment processors expect the name and address to be in the
457 // so we copy stuff over to first_name etc.
458 $paymentParams = $this->_params
;
459 $paymentParams['contactID'] = $this->_contactId
;
460 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
462 $paymentParams['contributionPageID'] = NULL;
463 if (!empty($this->_params
['is_email_receipt'])) {
464 $paymentParams['email'] = $this->_contributorEmail
;
465 $paymentParams['is_email_receipt'] = TRUE;
468 $paymentParams['is_email_receipt'] = $this->_params
['is_email_receipt'] = FALSE;
473 if ($paymentParams['amount'] > 0.0) {
475 // force a reget of the payment processor in case the form changed it, CRM-7179
476 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
477 $result = $payment->doPayment($paymentParams);
479 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
480 Civi
::log()->error('Payment processor exception: ' . $e->getMessage());
481 $urlParams = "action=add&cid={$this->_contactId}&id={$this->_contributionId}&component={$this->_component}&mode={$this->_mode}";
482 CRM_Core_Error
::statusBounce(CRM_Utils_System
::url($e->getMessage(), 'civicrm/payment/add', $urlParams));
486 if (!empty($result)) {
487 $this->_params
= array_merge($this->_params
, $result);
490 if (empty($this->_params
['receive_date'])) {
491 $this->_params
['receive_date'] = $now;
494 $this->set('params', $this->_params
);
496 // set source if not set
497 if (empty($this->_params
['source'])) {
498 $userID = $session->get('userID');
499 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
502 $this->_params
['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
507 * Function to send email receipt.
509 * @param array $params
513 public function emailReceipt(&$params) {
514 $templateEngine = CRM_Core_Smarty
::singleton();
515 // email receipt sending
516 list($contributorDisplayName, $contributorEmail, $doNotMail) = CRM_Contact_BAO_Contact
::getContactDetails($params['contact_id']);
517 if (!$contributorEmail ||
$doNotMail) {
520 $templateEngine->assign('contactDisplayName', $contributorDisplayName);
521 // send message template
522 if ($this->_component
== 'event') {
524 // fetch event information from participant ID using API
525 $eventId = civicrm_api3('Participant', 'getvalue', array(
526 'return' => "event_id",
529 $event = civicrm_api3('Event', 'getsingle', array('id' => $eventId));
531 $templateEngine->assign('event', $event);
532 $templateEngine->assign('isShowLocation', $event['is_show_location']);
533 if (CRM_Utils_Array
::value('is_show_location', $event) == 1) {
534 $locationParams = array(
535 'entity_id' => $eventId,
536 'entity_table' => 'civicrm_event',
538 $location = CRM_Core_BAO_Location
::getValues($locationParams, TRUE);
539 $templateEngine->assign('location', $location);
543 // assign payment info here
544 $paymentConfig['confirm_email_text'] = CRM_Utils_Array
::value('confirm_email_text', $params);
545 $templateEngine->assign('paymentConfig', $paymentConfig);
547 $templateEngine->assign('totalAmount', $this->_amtTotal
);
549 $isRefund = ($this->_paymentType
== 'refund') ?
TRUE : FALSE;
550 $templateEngine->assign('isRefund', $isRefund);
552 $templateEngine->assign('totalPaid', $this->_amtPaid
);
553 $templateEngine->assign('refundAmount', $params['total_amount']);
556 $balance = $this->_amtTotal
- ($this->_amtPaid +
$params['total_amount']);
557 $paymentsComplete = ($balance == 0) ?
1 : 0;
558 $templateEngine->assign('amountOwed', $balance);
559 $templateEngine->assign('paymentAmount', $params['total_amount']);
560 $templateEngine->assign('paymentsComplete', $paymentsComplete);
563 // assign trxn details
564 $templateEngine->assign('trxn_id', CRM_Utils_Array
::value('trxn_id', $params));
565 $templateEngine->assign('receive_date', CRM_Utils_Array
::value('trxn_date', $params));
566 $templateEngine->assign('paidBy', CRM_Core_PseudoConstant
::getLabel(
567 'CRM_Contribute_BAO_Contribution',
568 'payment_instrument_id',
569 $params['payment_instrument_id']
571 $templateEngine->assign('checkNumber', CRM_Utils_Array
::value('check_number', $params));
573 $sendTemplateParams = array(
574 'groupName' => 'msg_tpl_workflow_contribution',
575 'valueName' => 'payment_or_refund_notification',
576 'contactId' => $params['contact_id'],
577 'PDFFilename' => ts('notification') . '.pdf',
580 $sendTemplateParams['from'] = $params['from_email_address'];
581 $sendTemplateParams['toName'] = $contributorDisplayName;
582 $sendTemplateParams['toEmail'] = $contributorEmail;
584 list($mailSent) = CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
589 * Wrapper for unit testing the post process submit function.
591 * @param array $params
592 * @param string|null $creditCardMode
593 * @param string $entityType
595 * @throws \CiviCRM_API3_Exception
597 public function testSubmit($params, $creditCardMode = NULL, $entityType = 'contribute') {
599 // Required because processCreditCard calls set method on this.
600 $_SERVER['REQUEST_METHOD'] = 'GET';
601 $this->controller
= new CRM_Core_Controller();
603 $this->assignPaymentRelatedVariables();
605 if (!empty($params['contribution_id'])) {
606 $this->_contributionId
= $params['contribution_id'];
608 $paymentInfo = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($this->_contributionId
, $entityType);
609 $paymentDetails = CRM_Contribute_BAO_Contribution
::getPaymentInfo($this->_contributionId
, $entityType, FALSE, TRUE);
611 $this->_amtPaid
= $paymentDetails['paid'];
612 $this->_amtTotal
= $paymentDetails['total'];
614 if (!empty($paymentInfo['refund_due'])) {
615 $this->_refund
= $paymentInfo['refund_due'];
616 $this->_paymentType
= 'refund';
618 elseif (!empty($paymentInfo['amount_owed'])) {
619 $this->_owed
= $paymentInfo['amount_owed'];
620 $this->_paymentType
= 'owed';
624 if (!empty($params['contact_id'])) {
625 $this->_contactId
= $params['contact_id'];
628 if ($creditCardMode) {
629 $this->_mode
= $creditCardMode;
632 $this->_fields
= array();
633 $this->set('cid', $this->_contactId
);
634 parent
::preProcess();
635 $this->submit($params);