3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 * Related component whose financial payment is being processed.
45 protected $_component = NULL;
48 * Id of the component entity
52 protected $entity = 'Contribution';
54 protected $_owed = NULL;
56 protected $_refund = NULL;
59 * @deprecated - use parent $this->contactID
63 protected $_contactId = NULL;
65 protected $_contributorDisplayName = NULL;
67 protected $_contributorEmail = NULL;
69 protected $_toDoNotEmail = NULL;
71 protected $_paymentType = NULL;
73 protected $_contributionId = NULL;
75 protected $fromEmailId = NULL;
77 protected $_fromEmails = NULL;
79 protected $_view = NULL;
81 public $_action = NULL;
83 public function preProcess() {
85 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this, TRUE);
87 $this->_contactId
= $this->_contactID
;
88 $this->_component
= CRM_Utils_Request
::retrieve('component', 'String', $this, FALSE, 'contribution');
89 $this->_view
= CRM_Utils_Request
::retrieve('view', 'String', $this, FALSE);
90 $this->assign('component', $this->_component
);
91 $this->assign('id', $this->_id
);
92 $this->assign('suppressPaymentFormButtons', $this->isBeingCalledFromSelectorContext());
94 if ($this->_view
== 'transaction' && ($this->_action
& CRM_Core_Action
::BROWSE
)) {
95 $title = $this->assignPaymentInfoBlock();
96 CRM_Utils_System
::setTitle($title);
99 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
101 $entityType = 'contribution';
102 if ($this->_component
== 'event') {
103 $entityType = 'participant';
104 $this->_contributionId
= CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'contribution_id', 'participant_id');
105 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $this->_id
, 'event_id', 'id');
106 $this->_fromEmails
= CRM_Event_BAO_Event
::getFromEmailIds($eventId);
109 $this->_contributionId
= $this->_id
;
110 $this->_fromEmails
['from_email_id'] = CRM_Core_BAO_Email
::getFromEmail();
113 $paymentInfo = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($this->_id
, $entityType);
114 $paymentDetails = CRM_Contribute_BAO_Contribution
::getPaymentInfo($this->_id
, $this->_component
, FALSE, TRUE);
116 $this->_amtPaid
= $paymentDetails['paid'];
117 $this->_amtTotal
= $paymentDetails['total'];
119 if (!empty($paymentInfo['refund_due'])) {
120 $paymentAmt = $this->_refund
= $paymentInfo['refund_due'];
121 $this->_paymentType
= 'refund';
123 elseif (!empty($paymentInfo['amount_owed'])) {
124 $paymentAmt = $this->_owed
= $paymentInfo['amount_owed'];
125 $this->_paymentType
= 'owed';
128 CRM_Core_Error
::fatal(ts('No payment information found for this record'));
131 if (!empty($this->_mode
) && $this->_paymentType
== 'refund') {
132 CRM_Core_Error
::fatal(ts('Credit card payment is not for Refund payments use'));
135 list($this->_contributorDisplayName
, $this->_contributorEmail
) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
137 $this->assign('contributionMode', $this->_mode
);
138 $this->assign('contactId', $this->_contactID
);
139 $this->assign('paymentType', $this->_paymentType
);
140 $this->assign('paymentAmt', abs($paymentAmt));
142 $this->setPageTitle($this->_refund ?
ts('Refund') : ts('Payment'));
146 * Is this function being called from a datatable selector.
148 * If so we don't want to show the buttons.
150 protected function isBeingCalledFromSelectorContext() {
151 return CRM_Utils_Request
::retrieve('selector', 'Positive');
155 * This virtual function is used to set the default values of
156 * various form elements
161 * reference to the array of default values
166 public function setDefaultValues() {
167 if ($this->_view
== 'transaction' && ($this->_action
& CRM_Core_Action
::BROWSE
)) {
172 CRM_Core_Payment_Form
::setDefaultValues($this, $this->_contactId
);
173 $defaults = array_merge($defaults, $this->_defaults
);
176 if (empty($defaults['trxn_date'])) {
177 $defaults['trxn_date'] = date('Y-m-d H:i:s');
180 if ($this->_refund
) {
181 $defaults['total_amount'] = CRM_Utils_Money
::format(abs($this->_refund
), NULL, NULL, TRUE);
183 elseif ($this->_owed
) {
184 $defaults['total_amount'] = number_format($this->_owed
, 2);
187 // Set $newCredit variable in template to control whether link to credit card mode is included
188 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
193 * Build the form object.
195 public function buildQuickForm() {
196 if ($this->_view
== 'transaction' && ($this->_action
& CRM_Core_Action
::BROWSE
)) {
197 $this->addButtons(array(
200 'name' => ts('Done'),
201 'spacing' => ' ',
209 CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE, CRM_Utils_Request
::retrieve('payment_instrument_id', 'Integer'));
210 $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors
, NULL);
212 $attributes = CRM_Core_DAO
::getAttribute('CRM_Financial_DAO_FinancialTrxn');
214 $label = ($this->_refund
) ?
ts('Refund Amount') : ts('Payment Amount');
215 $this->addMoney('total_amount',
218 $attributes['total_amount'],
219 TRUE, 'currency', NULL
222 //add receipt for offline contribution
223 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
225 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
['from_email_id']);
227 $this->add('textarea', 'receipt_text', ts('Confirmation Message'));
229 $dateLabel = ($this->_refund
) ?
ts('Refund Date') : ts('Date Received');
230 $this->addField('trxn_date', array('entity' => 'FinancialTrxn', 'label' => $dateLabel, 'context' => 'Contribution'), FALSE, FALSE);
232 if ($this->_contactId
&& $this->_id
) {
233 if ($this->_component
== 'event') {
234 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $this->_id
, 'event_id', 'id');
235 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
236 $this->assign('eventName', $event[$eventId]);
240 $this->assign('displayName', $this->_contributorDisplayName
);
241 $this->assign('component', $this->_component
);
242 $this->assign('email', $this->_contributorEmail
);
245 // render backoffice payment fields only on offline mode
247 $js = array('onclick' => "return verify( );");
249 $this->add('select', 'payment_instrument_id',
250 ts('Payment Method'),
251 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
253 array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
256 $this->add('text', 'check_number', ts('Check Number'), $attributes['financial_trxn_check_number']);
257 $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
259 $this->add('text', 'fee_amount', ts('Fee Amount'),
260 $attributes['fee_amount']
262 $this->addRule('fee_amount', ts('Please enter a valid monetary value for Fee Amount.'), 'money');
264 $this->add('text', 'net_amount', ts('Net Amount'),
265 $attributes['net_amount']
267 $this->addRule('net_amount', ts('Please enter a valid monetary value for Net Amount.'), 'money');
270 $buttonName = $this->_refund ?
'Record Refund' : 'Record Payment';
271 $this->addButtons(array(
274 'name' => ts('%1', array(1 => $buttonName)),
280 'name' => ts('Cancel'),
284 $mailingInfo = Civi
::settings()->get('mailing_backend');
285 $this->assign('outBound_option', $mailingInfo['outBound_option']);
287 $this->addFormRule(array('CRM_Contribute_Form_AdditionalPayment', 'formRule'), $this);
297 public static function formRule($fields, $files, $self) {
299 if ($self->_paymentType
== 'owed' && $fields['total_amount'] > $self->_owed
) {
300 $errors['total_amount'] = ts('Payment amount cannot be greater than owed amount');
302 if ($self->_paymentType
== 'refund' && $fields['total_amount'] != abs($self->_refund
)) {
303 $errors['total_amount'] = ts('Refund amount must equal refund due amount.');
305 $netAmt = $fields['total_amount'] - CRM_Utils_Array
::value('fee_amount', $fields, 0);
306 if (!empty($fields['net_amount']) && $netAmt != $fields['net_amount']) {
307 $errors['net_amount'] = ts('Net amount should be equal to the difference between payment amount and fee amount.');
309 if ($self->_paymentProcessor
['id'] === 0 && empty($fields['payment_instrument_id'])) {
310 $errors['payment_instrument_id'] = ts('Payment method is a required field');
317 * Process the form submission.
319 public function postProcess() {
320 $submittedValues = $this->controller
->exportValues($this->_name
);
321 $this->submit($submittedValues);
322 $childTab = 'contribute';
323 if ($this->_component
== 'event') {
324 $childTab = 'participant';
326 $session = CRM_Core_Session
::singleton();
327 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
328 "reset=1&cid={$this->_contactId}&selectedChild={$childTab}"
334 * @param array $submittedValues
337 public function submit($submittedValues) {
338 $this->_params
= $submittedValues;
339 $this->beginPostProcess();
340 $this->_contributorContactID
= $this->_contactID
;
341 $this->processBillingAddress();
342 $participantId = NULL;
343 if ($this->_component
== 'event') {
344 $participantId = $this->_id
;
346 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution',
347 'contribution_status_id',
348 array('labelColumn' => 'name')
350 $contributionStatusID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_contributionId
, 'contribution_status_id');
351 if ($contributionStatuses[$contributionStatusID] == 'Pending') {
352 civicrm_api3('Contribution', 'create',
354 'id' => $this->_contributionId
,
355 'contribution_status_id' => array_search('Partially paid', $contributionStatuses),
362 // process credit card
363 $this->assign('contributeMode', 'direct');
364 $this->processCreditCard();
368 $contribution = civicrm_api3('Contribution', 'getsingle', array(
369 'return' => array("contribution_status_id"),
370 'id' => $this->_contributionId
,
372 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $contribution);
373 $result = CRM_Contribute_BAO_Contribution
::recordAdditionalPayment($this->_contributionId
, $this->_params
, $this->_paymentType
, $participantId);
374 // Fetch the contribution & do proportional line item assignment
375 $params = array('id' => $this->_contributionId
);
376 $contribution = CRM_Contribute_BAO_Contribution
::retrieve($params, $defaults, $params);
377 CRM_Contribute_BAO_Contribution
::addPayments(array($contribution), $contributionStatusId);
378 if ($this->_contributionId
&& CRM_Core_Permission
::access('CiviMember')) {
379 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', array('contribution_id' => $this->_contributionId
));
380 if ($membershipPaymentCount) {
381 $this->ajaxResponse
['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactID
);
384 if ($this->_contributionId
&& CRM_Core_Permission
::access('CiviEvent')) {
385 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', array('contribution_id' => $this->_contributionId
));
386 if ($participantPaymentCount) {
387 $this->ajaxResponse
['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact
::getCountComponent('participant', $this->_contactID
);
391 $statusMsg = ts('The payment record has been processed.');
393 if (!empty($result) && !empty($this->_params
['is_email_receipt'])) {
394 $this->_params
['contact_id'] = $this->_contactId
;
395 $this->_params
['contribution_id'] = $this->_contributionId
;
396 // to get 'from email id' for send receipt
397 $this->fromEmailId
= $this->_params
['from_email_address'];
398 $sendReceipt = $this->emailReceipt($this->_params
);
400 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
404 CRM_Core_Session
::setStatus($statusMsg, ts('Saved'), 'success');
407 public function processCreditCard() {
408 $config = CRM_Core_Config
::singleton();
409 $session = CRM_Core_Session
::singleton();
411 $now = date('YmdHis');
414 // we need to retrieve email address
415 if ($this->_context
== 'standalone' && !empty($this->_params
['is_email_receipt'])) {
416 list($this->userDisplayName
,
418 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactId
);
419 $this->assign('displayName', $this->userDisplayName
);
422 $this->formatParamsForPaymentProcessor($this->_params
);
424 $this->_params
['amount'] = $this->_params
['total_amount'];
425 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
426 // function to get correct amount level consistently. Remove setting of the amount level in
427 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
428 // to cover all variants.
429 $this->_params
['amount_level'] = 0;
430 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
432 $config->defaultCurrency
435 if (!empty($this->_params
['trxn_date'])) {
436 $this->_params
['receive_date'] = $this->_params
['trxn_date'];
439 if (empty($this->_params
['receive_date'])) {
440 $this->_params
['receive_date'] = date('YmdHis');
443 if (empty($this->_params
['invoice_id'])) {
444 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
447 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
450 $this->assign('address', CRM_Utils_Address
::getFormattedBillingAddressFieldsFromParameters(
455 //Add common data to formatted params
456 $params = $this->_params
;
457 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
458 // at this point we've created a contact and stored its address etc
459 // all the payment processors expect the name and address to be in the
460 // so we copy stuff over to first_name etc.
461 $paymentParams = $this->_params
;
462 $paymentParams['contactID'] = $this->_contactId
;
463 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
465 $paymentParams['contributionPageID'] = NULL;
466 if (!empty($this->_params
['is_email_receipt'])) {
467 $paymentParams['email'] = $this->_contributorEmail
;
468 $paymentParams['is_email_receipt'] = TRUE;
471 $paymentParams['is_email_receipt'] = $this->_params
['is_email_receipt'] = FALSE;
476 if ($paymentParams['amount'] > 0.0) {
478 // force a reget of the payment processor in case the form changed it, CRM-7179
479 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
480 $result = $payment->doPayment($paymentParams);
482 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
483 Civi
::log()->error('Payment processor exception: ' . $e->getMessage());
484 $urlParams = "action=add&cid={$this->_contactId}&id={$this->_contributionId}&component={$this->_component}&mode={$this->_mode}";
485 CRM_Core_Error
::statusBounce(CRM_Utils_System
::url($e->getMessage(), 'civicrm/payment/add', $urlParams));
489 if (!empty($result)) {
490 $this->_params
= array_merge($this->_params
, $result);
493 if (empty($this->_params
['receive_date'])) {
494 $this->_params
['receive_date'] = $now;
497 $this->set('params', $this->_params
);
499 // set source if not set
500 if (empty($this->_params
['source'])) {
501 $userID = $session->get('userID');
502 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
505 $this->_params
['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
510 * Function to send email receipt.
512 * @param array $params
516 public function emailReceipt(&$params) {
517 // email receipt sending
518 // send message template
519 if ($this->_component
== 'event') {
521 // fetch event information from participant ID using API
522 $eventId = civicrm_api3('Participant', 'getvalue', array(
523 'return' => "event_id",
526 $event = civicrm_api3('Event', 'getsingle', array('id' => $eventId));
528 $this->assign('event', $event);
529 $this->assign('isShowLocation', $event['is_show_location']);
530 if (CRM_Utils_Array
::value('is_show_location', $event) == 1) {
531 $locationParams = array(
532 'entity_id' => $eventId,
533 'entity_table' => 'civicrm_event',
535 $location = CRM_Core_BAO_Location
::getValues($locationParams, TRUE);
536 $this->assign('location', $location);
540 // assign payment info here
541 $paymentConfig['confirm_email_text'] = CRM_Utils_Array
::value('confirm_email_text', $params);
542 $this->assign('paymentConfig', $paymentConfig);
544 $this->assign('totalAmount', $this->_amtTotal
);
546 $isRefund = ($this->_paymentType
== 'refund') ?
TRUE : FALSE;
547 $this->assign('isRefund', $isRefund);
549 $this->assign('totalPaid', $this->_amtPaid
);
550 $this->assign('refundAmount', $params['total_amount']);
553 $balance = $this->_amtTotal
- ($this->_amtPaid +
$params['total_amount']);
554 $paymentsComplete = ($balance == 0) ?
1 : 0;
555 $this->assign('amountOwed', $balance);
556 $this->assign('paymentAmount', $params['total_amount']);
557 $this->assign('paymentsComplete', $paymentsComplete);
559 $this->assign('contactDisplayName', $this->_contributorDisplayName
);
561 // assign trxn details
562 $this->assign('trxn_id', CRM_Utils_Array
::value('trxn_id', $params));
563 $this->assign('receive_date', CRM_Utils_Array
::value('trxn_date', $params));
564 $this->assign('paidBy', CRM_Core_PseudoConstant
::getLabel(
565 'CRM_Contribute_BAO_Contribution',
566 'payment_instrument_id',
567 $params['payment_instrument_id']
569 $this->assign('checkNumber', CRM_Utils_Array
::value('check_number', $params));
571 $sendTemplateParams = array(
572 'groupName' => 'msg_tpl_workflow_contribution',
573 'valueName' => 'payment_or_refund_notification',
574 'contactId' => $this->_contactId
,
575 'PDFFilename' => ts('notification') . '.pdf',
578 // try to send emails only if email id is present
579 // and the do-not-email option is not checked for that contact
580 if ($this->_contributorEmail
&& !$this->_toDoNotEmail
) {
581 if (array_key_exists($params['from_email_address'], $this->_fromEmails
['from_email_id'])) {
582 $receiptFrom = $params['from_email_address'];
585 $sendTemplateParams['from'] = $receiptFrom;
586 $sendTemplateParams['toName'] = $this->_contributorDisplayName
;
587 $sendTemplateParams['toEmail'] = $this->_contributorEmail
;
589 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
594 * Wrapper for unit testing the post process submit function.
596 * @param array $params
597 * @param string|null $creditCardMode
598 * @param string $entityType
600 * @throws \CiviCRM_API3_Exception
602 public function testSubmit($params, $creditCardMode = NULL, $entityType = 'contribute') {
604 // Required because processCreditCard calls set method on this.
605 $_SERVER['REQUEST_METHOD'] = 'GET';
606 $this->controller
= new CRM_Core_Controller();
608 $this->assignPaymentRelatedVariables();
610 if (!empty($params['contribution_id'])) {
611 $this->_contributionId
= $params['contribution_id'];
613 $paymentInfo = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($this->_contributionId
, $entityType);
614 $paymentDetails = CRM_Contribute_BAO_Contribution
::getPaymentInfo($this->_contributionId
, $entityType, FALSE, TRUE);
616 $this->_amtPaid
= $paymentDetails['paid'];
617 $this->_amtTotal
= $paymentDetails['total'];
619 if (!empty($paymentInfo['refund_due'])) {
620 $this->_refund
= $paymentInfo['refund_due'];
621 $this->_paymentType
= 'refund';
623 elseif (!empty($paymentInfo['amount_owed'])) {
624 $this->_owed
= $paymentInfo['amount_owed'];
625 $this->_paymentType
= 'owed';
629 if (!empty($params['contact_id'])) {
630 $this->_contactId
= $params['contact_id'];
633 if ($creditCardMode) {
634 $this->_mode
= $creditCardMode;
637 $this->_fields
= array();
638 $this->set('cid', $this->_contactId
);
639 parent
::preProcess();
640 $this->submit($params);