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';
34 protected $_owed = NULL;
36 protected $_refund = NULL;
40 * @deprecated - use parent $this->contactID
42 protected $_contactId = NULL;
44 protected $_contributorDisplayName = NULL;
46 protected $_contributorEmail = NULL;
48 protected $_toDoNotEmail = NULL;
50 protected $_paymentType = NULL;
52 protected $_contributionId = NULL;
54 protected $fromEmailId = NULL;
56 protected $_view = NULL;
58 public $_action = NULL;
63 * @throws \CRM_Core_Exception
64 * @throws \CiviCRM_API3_Exception
66 public function preProcess() {
68 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this, TRUE);
70 $this->_contactId
= $this->_contactID
;
71 $this->_component
= CRM_Utils_Request
::retrieve('component', 'String', $this, FALSE, 'contribution');
72 $this->_view
= CRM_Utils_Request
::retrieve('view', 'String', $this, FALSE);
73 $this->assign('component', $this->_component
);
74 $this->assign('id', $this->_id
);
75 $this->assign('suppressPaymentFormButtons', $this->isBeingCalledFromSelectorContext());
77 if ($this->_view
== 'transaction' && ($this->_action
& CRM_Core_Action
::BROWSE
)) {
78 $title = $this->assignPaymentInfoBlock();
79 CRM_Utils_System
::setTitle($title);
82 if ($this->_component
== 'event') {
83 $this->_contributionId
= CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'contribution_id', 'participant_id');
86 $this->_contributionId
= $this->_id
;
89 $paymentDetails = CRM_Contribute_BAO_Contribution
::getPaymentInfo($this->_id
, $this->_component
, FALSE, TRUE);
90 $paymentAmt = $this->getAmountDue();
92 $this->_amtPaid
= $paymentDetails['paid'];
93 $this->_amtTotal
= $paymentDetails['total'];
95 if ($paymentAmt >= 0) {
96 $this->_owed
= $paymentAmt;
99 $this->_paymentType
= $this->getPaymentType();
101 if (!empty($this->_mode
) && $this->isARefund()) {
102 throw new CRM_Core_Exception(ts('Credit card payment is not for Refund payments use'));
105 list($this->_contributorDisplayName
, $this->_contributorEmail
) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
107 $this->assign('contributionMode', $this->_mode
);
108 $this->assign('contactId', $this->_contactID
);
109 $this->assign('paymentType', $this->_paymentType
);
110 $this->assign('paymentAmt', $paymentAmt);
111 // It's easier to strip the minus sign for display purposes in php than smarty.
112 $this->assign('absolutePaymentAmount', abs($paymentAmt));
114 $this->setPageTitle($this->isARefund() ?
ts('Refund') : ts('Payment'));
118 * Is this function being called from a datatable selector.
120 * If so we don't want to show the buttons.
122 * @throws \CRM_Core_Exception
124 protected function isBeingCalledFromSelectorContext() {
125 return CRM_Utils_Request
::retrieve('selector', 'Positive');
129 * This virtual function is used to set the default values of
130 * various form elements
135 * reference to the array of default values
140 * @throws \CRM_Core_Exception
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->isARefund() && $this->amountDue
< 0) {
157 $defaults['total_amount'] = CRM_Utils_Money
::format(abs($this->amountDue
), NULL, NULL, TRUE);
159 elseif ($this->_owed
&& $this->amountDue
> 0) {
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 * @throws \CRM_Core_Exception
172 * @throws \CiviCRM_API3_Exception
174 public function buildQuickForm() {
175 if ($this->_view
=== 'transaction' && ($this->_action
& CRM_Core_Action
::BROWSE
)) {
179 'name' => ts('Done'),
180 'spacing' => ' ',
187 CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE, CRM_Utils_Request
::retrieve('payment_instrument_id', 'Integer'));
188 $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors
, NULL);
190 $attributes = CRM_Core_DAO
::getAttribute('CRM_Financial_DAO_FinancialTrxn');
192 $this->addMoney('total_amount',
193 $this->isARefund() ?
ts('Refund Amount') : ts('Payment Amount'),
195 $attributes['total_amount'],
196 TRUE, 'currency', NULL
199 //add receipt for offline contribution
200 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
202 if ($this->_component
=== 'event') {
203 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $this->_id
, 'event_id', 'id');
206 $this->add('select', 'from_email_address', ts('Receipt From'), CRM_Financial_BAO_Payment
::getValidFromEmailsForPayment($eventID ??
NULL));
208 $this->add('textarea', 'receipt_text', ts('Confirmation Message'));
210 $this->addField('trxn_date', ['entity' => 'FinancialTrxn', 'label' => $this->isARefund() ?
ts('Refund Date') : ts('Date Received'), 'context' => 'Contribution'], FALSE, FALSE);
212 if ($this->_contactId
&& $this->_id
) {
213 if ($this->_component
== 'event') {
214 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $this->_id
, 'event_id', 'id');
215 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
216 $this->assign('eventName', $event[$eventId]);
220 $this->assign('displayName', $this->_contributorDisplayName
);
221 $this->assign('component', $this->_component
);
222 $this->assign('email', $this->_contributorEmail
);
225 // render backoffice payment fields only on offline mode
227 $js = ['onclick' => 'return verify( );'];
229 $this->add('select', 'payment_instrument_id',
230 ts('Payment Method'),
231 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::paymentInstrument(),
233 ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
236 $this->add('text', 'check_number', ts('Check Number'), $attributes['financial_trxn_check_number']);
237 $this->add('text', 'trxn_id', ts('Transaction ID'), ['class' => 'twelve'] +
$attributes['trxn_id']);
239 $this->add('text', 'fee_amount', ts('Fee Amount'),
240 $attributes['fee_amount']
242 $this->addRule('fee_amount', ts('Please enter a valid monetary value for Fee Amount.'), 'money');
245 $buttonName = $this->isARefund() ?
ts('Record Refund') : ts('Record Payment');
249 'name' => $buttonName,
255 'name' => ts('Cancel'),
258 $mailingInfo = Civi
::settings()->get('mailing_backend');
259 $this->assign('outBound_option', $mailingInfo['outBound_option']);
261 $this->addFormRule(['CRM_Contribute_Form_AdditionalPayment', 'formRule'], $this);
271 public static function formRule($fields, $files, $self) {
273 if ($self->_paymentProcessor
['id'] === 0 && empty($fields['payment_instrument_id'])) {
274 $errors['payment_instrument_id'] = ts('Payment method is a required field');
281 * Process the form submission.
283 * @throws \CiviCRM_API3_Exception
285 public function postProcess() {
286 $submittedValues = $this->controller
->exportValues($this->_name
);
287 $this->submit($submittedValues);
288 $childTab = 'contribute';
289 if ($this->_component
=== 'event') {
290 $childTab = 'participant';
292 $session = CRM_Core_Session
::singleton();
293 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
294 "reset=1&cid={$this->_contactId}&selectedChild={$childTab}"
301 * @param array $submittedValues
303 * @throws \CiviCRM_API3_Exception
304 * @throws \CRM_Core_Exception
306 public function submit($submittedValues) {
307 $this->_params
= $submittedValues;
308 $this->beginPostProcess();
309 $this->_contributorContactID
= $this->_contactID
;
310 $this->processBillingAddress();
311 $participantId = NULL;
312 if ($this->_component
=== 'event') {
313 $participantId = $this->_id
;
317 // process credit card
318 $this->assign('contributeMode', 'direct');
319 $this->processCreditCard();
322 // @todo we should clean $ on the form & pass in skipCleanMoney
323 $trxnsData = $this->_params
;
324 if ($this->isARefund()) {
325 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
327 $trxnsData['participant_id'] = $participantId;
328 $trxnsData['contribution_id'] = $this->_contributionId
;
330 $trxnsData['is_send_contribution_notification'] = FALSE;
331 $paymentID = civicrm_api3('Payment', 'create', $trxnsData)['id'];
333 if ($this->_contributionId
&& CRM_Core_Permission
::access('CiviMember')) {
334 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', ['contribution_id' => $this->_contributionId
]);
335 if ($membershipPaymentCount) {
336 $this->ajaxResponse
['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactID
);
339 if ($this->_contributionId
&& CRM_Core_Permission
::access('CiviEvent')) {
340 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', ['contribution_id' => $this->_contributionId
]);
341 if ($participantPaymentCount) {
342 $this->ajaxResponse
['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact
::getCountComponent('participant', $this->_contactID
);
346 $statusMsg = ts('The payment record has been processed.');
348 if (!empty($paymentID) && !empty($this->_params
['is_email_receipt'])) {
349 $sendResult = civicrm_api3('Payment', 'sendconfirmation', ['id' => $paymentID, 'from' => $submittedValues['from_email_address']])['values'][$paymentID];
350 if ($sendResult['is_sent']) {
351 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
355 CRM_Core_Session
::setStatus($statusMsg, ts('Saved'), 'success');
358 public function processCreditCard() {
359 $config = CRM_Core_Config
::singleton();
360 $session = CRM_Core_Session
::singleton();
362 // we need to retrieve email address
363 if ($this->_context
== 'standalone' && !empty($this->_params
['is_email_receipt'])) {
364 list($this->userDisplayName
,
366 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactId
);
367 $this->assign('displayName', $this->userDisplayName
);
370 $this->_params
['amount'] = $this->_params
['total_amount'];
371 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
372 // function to get correct amount level consistently. Remove setting of the amount level in
373 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
374 // to cover all variants.
375 $this->_params
['amount_level'] = 0;
376 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
378 $config->defaultCurrency
381 if (empty($this->_params
['invoice_id'])) {
382 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
385 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
388 $this->assign('address', CRM_Utils_Address
::getFormattedBillingAddressFieldsFromParameters(
393 //Add common data to formatted params
394 $params = $this->_params
;
395 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
396 // at this point we've created a contact and stored its address etc
397 // all the payment processors expect the name and address to be in the
398 // so we copy stuff over to first_name etc.
399 $paymentParams = $this->_params
;
400 $paymentParams['contactID'] = $this->_contactId
;
401 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
403 $paymentParams['contributionPageID'] = NULL;
404 if (!empty($this->_params
['is_email_receipt'])) {
405 $paymentParams['email'] = $this->_contributorEmail
;
406 $paymentParams['is_email_receipt'] = TRUE;
409 $paymentParams['is_email_receipt'] = $this->_params
['is_email_receipt'] = FALSE;
414 if ($paymentParams['amount'] > 0.0) {
416 // force a reget of the payment processor in case the form changed it, CRM-7179
417 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
418 $result = $payment->doPayment($paymentParams);
420 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
421 Civi
::log()->error('Payment processor exception: ' . $e->getMessage());
422 $urlParams = "action=add&cid={$this->_contactId}&id={$this->_contributionId}&component={$this->_component}&mode={$this->_mode}";
423 CRM_Core_Error
::statusBounce($e->getMessage(), CRM_Utils_System
::url('civicrm/payment/add', $urlParams));
427 if (!empty($result)) {
428 $this->_params
= array_merge($this->_params
, $result);
431 $this->set('params', $this->_params
);
433 // set source if not set
434 if (empty($this->_params
['source'])) {
435 $userID = $session->get('userID');
436 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
439 $this->_params
['source'] = ts('Submit Credit Card Payment by: %1', [1 => $userSortName]);
444 * Wrapper for unit testing the post process submit function.
446 * @param array $params
447 * @param string|null $creditCardMode
448 * @param string $entityType
450 * @throws \CiviCRM_API3_Exception
451 * @throws \CRM_Core_Exception
453 public function testSubmit($params, $creditCardMode = NULL, $entityType = 'contribute') {
455 // Required because processCreditCard calls set method on this.
456 $_SERVER['REQUEST_METHOD'] = 'GET';
457 $this->controller
= new CRM_Core_Controller();
459 $this->assignPaymentRelatedVariables();
461 if (!empty($params['contribution_id'])) {
462 $this->_contributionId
= $params['contribution_id'];
464 $paymentDetails = CRM_Contribute_BAO_Contribution
::getPaymentInfo($this->_contributionId
, $entityType, FALSE, TRUE);
466 $paymentAmount = $this->getAmountDue();
467 $this->_amtPaid
= $paymentDetails['paid'];
468 $this->_amtTotal
= $paymentDetails['total'];
470 if ($paymentAmount > 0) {
471 $this->_owed
= $paymentAmount;
473 $this->_paymentType
= $this->getPaymentType();
476 if (!empty($params['contact_id'])) {
477 $this->_contactId
= $params['contact_id'];
480 if ($creditCardMode) {
481 $this->_mode
= $creditCardMode;
485 $this->set('cid', $this->_contactId
);
486 parent
::preProcess();
487 $this->submit($params);
491 * Get the 'payment type' - ie is it a payment or a refund.
493 * We prefer the url action param but fall back on a guess from the balance.
495 * The refund|owed is not great - perhaps move to positive & negative.
498 * @throws \CRM_Core_Exception
500 protected function getPaymentType():string {
501 $urlParam = CRM_Utils_Request
::retrieve('is_refund', 'Int', $this);
502 if ($urlParam === 0) {
505 if ($urlParam === 1) {
509 return $this->getAmountDue() < 0 ?
'refund' : 'owed';
513 * Is the form processing a refund.
517 * @throws \CRM_Core_Exception
519 protected function isARefund() {
520 return $this->getPaymentType() === 'refund';
526 protected function getAmountDue(): float {
527 if (!isset($this->amountDue
)) {
528 $this->amountDue
= CRM_Contribute_BAO_Contribution
::getContributionBalance($this->_contributionId
);
530 return $this->amountDue
;