3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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 usefusul, 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-2013
37 * This form records additional payments needed when
38 * event/contribution is partially paid
41 class CRM_Contribute_Form_AdditionalPayment
extends CRM_Contribute_Form_AbstractEditPayment
{
42 public $_contributeMode = 'direct';
45 * related component whose financial payment is being processed
50 protected $_component = NULL;
53 * id of the component entity
57 protected $_owed = NULL;
59 protected $_refund = NULL;
61 protected $_contactId = NULL;
63 protected $_contributorDisplayName = NULL;
65 protected $_contributorEmail = NULL;
67 protected $_toDoNotEmail = NULL;
69 protected $_paymentType = NULL;
71 protected $_contributionId = NULL;
73 protected $fromEmailId = NULL;
75 protected $_fromEmails = NULL;
77 public function preProcess() {
78 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this, TRUE);
79 $this->_contactId
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this, TRUE);
80 $this->_component
= CRM_Utils_Request
::retrieve('component', 'String', $this, TRUE);
82 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
83 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
86 if ($this->_component
== 'event') {
87 $enitityType = 'participant';
88 $this->_contributionId
= CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'contribution_id', 'participant_id');
90 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $this->_id
, 'event_id', 'id');
91 $this->_fromEmails
= CRM_Event_BAO_Event
::getFromEmailIds($eventId);
93 $paymentInfo = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($this->_id
, $enitityType);
94 $paymentDetails = CRM_Contribute_BAO_Contribution
::getPaymentInfo($this->_id
, $this->_component
);
96 $this->_amtPaid
= $paymentDetails['paid'];
97 $this->_amtTotal
= $paymentDetails['total'];
99 if (!empty($paymentInfo['refund_due'])) {
100 $paymentAmt = $this->_refund
= $paymentInfo['refund_due'];
101 $this->_paymentType
= 'refund';
103 elseif (!empty($paymentInfo['amount_owed'])) {
104 $paymentAmt = $this->_owed
= $paymentInfo['amount_owed'];
105 $this->_paymentType
= 'owed';
108 CRM_Core_Error
::fatal(ts('No payment information found for this record'));
111 //set the payment mode - _mode property is defined in parent class
112 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'String', $this);
114 if (!empty($this->_mode
) && $this->_paymentType
== 'refund') {
115 CRM_Core_Error
::fatal(ts('Credit card payment is not for Refund payments use'));
118 list($this->_contributorDisplayName
, $this->_contributorEmail
) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactId
);
120 if (!$this->_refund
) {
121 $this->assignProcessors();
122 // also check for billing information
123 // get the billing location type
124 $this->assignBillingType();
127 $this->assign('contributionMode', $this->_mode
);
128 $this->assign('contactId', $this->_contactId
);
129 $this->assign('component', $this->_component
);
130 $this->assign('id', $this->_id
);
131 $this->assign('paymentType', $this->_paymentType
);
132 $this->assign('paymentAmt', abs($paymentAmt));
134 $this->_paymentProcessor
= array('billing_mode' => 1);
136 $title = ($this->_refund
) ?
"Refund for {$this->_contributorDisplayName}" : "Payment from {$this->_contributorDisplayName}";
138 CRM_Utils_System
::setTitle(ts('%1', array(1 => $title)));
142 public function setDefaultValues() {
144 $defaults = $this->_values
;
146 $config = CRM_Core_Config
::singleton();
147 // set default country from config if no country set
148 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
149 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
152 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
153 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
156 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactId
);
157 $defaults = array_merge($defaults, $billingDefaults);
159 // now fix all state country selectors, set correct state based on country
160 CRM_Core_BAO_Address
::fixAllStateSelects($this, $defaults);
163 // Set $newCredit variable in template to control whether link to credit card mode is included
164 CRM_Core_Payment
::allowBackofficeCreditCard($this);
167 public function buildQuickForm() {
170 if (CRM_Utils_Array
::value('payment_type', $this->_processors
) & CRM_Core_Payment
::PAYMENT_TYPE_DIRECT_DEBIT
172 $ccPane = array(ts('Direct Debit Information') => 'DirectDebit');
175 $ccPane = array(ts('Credit Card Information') => 'CreditCard');
177 $defaults = $this->_values
;
178 $showAdditionalInfo = FALSE;
180 foreach ($ccPane as $name => $type) {
181 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
182 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
184 $showAdditionalInfo = TRUE;
185 $allPanes[$name]['open'] = 'true';
188 $urlParams = "snippet=4&formType={$type}";
190 $urlParams .= "&mode={$this->_mode}";
193 if ($type == 'CreditCard' ||
194 $type == 'DirectDebit'
199 $allPanes[$name] = array(
200 'url' => CRM_Utils_System
::url('civicrm/payment/add', $urlParams),
205 if ($type == 'CreditCard') {
206 $this->add('hidden', 'hidden_CreditCard', 1);
207 CRM_Core_Payment_Form
::buildCreditCard($this, TRUE);
209 elseif ($type == 'DirectDebit') {
210 $this->add('hidden', 'hidden_DirectDebit', 1);
211 CRM_Core_Payment_Form
::buildDirectDebit($this, TRUE);
213 $qfKey = $this->controller
->_key
;
214 $this->assign('qfKey', $qfKey);
215 $this->assign('allPanes', $allPanes);
216 $this->assign('showAdditionalInfo', $showAdditionalInfo);
218 if ($this->_formType
) {
219 $this->assign('formType', $this->_formType
);
224 $attributes = CRM_Core_DAO
::getAttribute('CRM_Financial_DAO_FinancialTrxn');
226 $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors
, NULL);
227 $this->add('select', 'financial_type_id',
228 ts('Financial Type'),
229 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::financialType(),
232 $label = ($this->_refund
) ?
'Refund Amount' : 'Payment Amount';
233 $this->addMoney('total_amount',
234 ts('%1', array(1 => $label)),
236 $attributes['total_amount'],
237 TRUE, 'currency', NULL
241 $this->add('select', 'payment_instrument_id',
243 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
244 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
248 $this->add('text', 'check_number', ts('Check Number'), $attributes['financial_trxn_check_number']);
249 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), $attributes['trxn_id']);
251 //add receipt for offline contribution
252 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
254 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
['from_email_id']);
256 $this->add('textarea', 'receipt_text', ts('Confirmation Message'));
259 $this->addDateTime('trxn_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
261 if ($this->_contactId
&& $this->_id
) {
262 if ($this->_component
== 'event') {
263 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $this->_id
, 'event_id', 'id');
264 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
265 $this->assign('eventName', $event[$eventId]);
269 $this->assign('displayName', $this->_contributorDisplayName
);
270 $this->assign('component', $this->_component
);
271 $this->assign('email', $this->_contributorEmail
);
273 $this->add('text', 'fee_amount', ts('Fee Amount'),
274 $attributes['fee_amount']
276 $this->addRule('fee_amount', ts('Please enter a valid monetary value for Fee Amount.'), 'money');
278 $this->add('text', 'net_amount', ts('Net Amount'),
279 $attributes['net_amount']
281 $this->addRule('net_amount', ts('Please enter a valid monetary value for Net Amount.'), 'money');
285 $js = array('onclick' => "return verify( );");
288 $buttonName = $this->_refund ?
'Record Refund' : 'Record Payment';
289 $this->addButtons(array(
292 'name' => ts('%1', array(1 => $buttonName)),
298 'name' => ts('Cancel')
304 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
307 $this->assign('outBound_option', $mailingInfo['outBound_option']);
309 $this->addFormRule(array('CRM_Contribute_Form_AdditionalPayment', 'formRule'), $this);
312 static function formRule($fields, $files, $self) {
314 if ($self->_paymentType
== 'owed' && $fields['total_amount'] > $self->_owed
) {
315 $errors['total_amount'] = ts('Payment amount cannot be greater than owed amount');
317 if ($self->_paymentType
== 'refund' && $fields['total_amount'] != abs($self->_refund
)) {
318 $errors['total_amount'] = ts('Refund amount should not differ');
320 $netAmt = $fields['total_amount'] - $fields['fee_amount'];
321 if (!empty($fields['net_amount']) && $netAmt != $fields['net_amount']) {
322 $errors['net_amount'] = ts('Net amount should be difference of payment amount and fee amount');
327 public function postProcess() {
328 $participantId = NULL;
329 if ($this->_component
== 'event') {
330 $participantId = $this->_id
;
332 $submittedValues = $this->controller
->exportValues($this->_name
);
333 $submittedValues['confirm_email_text'] = CRM_Utils_Array
::value('receipt_text', $submittedValues);
335 $submittedValues['trxn_date'] = CRM_Utils_Date
::processDate($submittedValues['trxn_date'], $submittedValues['trxn_date_time']);
337 // process credit card
338 $this->processCreditCard($submittedValues);
341 $result = CRM_Contribute_BAO_Contribution
::recordAdditionPayment($this->_contributionId
, $submittedValues, $this->_paymentType
, $participantId);
344 if (!empty($result) && !empty($submittedValues['is_email_receipt'])) {
345 $submittedValues['contact_id'] = $this->_contactId
;
346 $submittedValues['contribution_id'] = $this->_contributionId
;
348 // to get 'from email id' for send receipt
349 $this->fromEmailId
= $submittedValues['from_email_address'];
350 $sendReceipt = $this->emailReceipt($submittedValues);
353 $statusMsg = ts('The payment record has been processed.');
354 if (!empty($submittedValues['is_email_receipt']) && $sendReceipt) {
355 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
357 if (isset($sendReceipt)) {
358 $statusMsg .= ' ' . ts('Email has been sent successfully');
360 CRM_Core_Session
::setStatus($statusMsg, ts('Saved'), 'success');
362 $session = CRM_Core_Session
::singleton();
363 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
364 "reset=1&cid={$this->_contactId}&selectedChild=participant"
369 public function processCreditCard($submittedValues) {
370 $config = CRM_Core_Config
::singleton();
371 $session = CRM_Core_Session
::singleton();
373 $unsetParams = array(
375 'payment_instrument_id',
376 'contribution_status_id',
378 foreach ($unsetParams as $key) {
379 if (isset($submittedValues[$key])) {
380 unset($submittedValues[$key]);
384 //Get the rquire fields value only.
385 $params = $this->_params
= $submittedValues;
387 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment($this->_params
['payment_processor_id'],
391 //get the payment processor id as per mode.
392 $this->_params
['payment_processor'] = $params['payment_processor_id'] =
393 $this->_params
['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
395 $now = date('YmdHis');
398 // we need to retrieve email address
399 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
400 list($this->userDisplayName
,
402 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactId
);
403 $this->assign('displayName', $this->userDisplayName
);
406 //set email for primary location.
407 $fields['email-Primary'] = 1;
408 $params['email-Primary'] = $this->_contributorEmail
;
410 // now set the values for the billing location.
411 foreach ($this->_fields
as $name => $dontCare) {
415 // also add location name to the array
416 $params["address_name-{$this->_bltID}"] = CRM_Utils_Array
::value('billing_first_name', $params) . ' ' . CRM_Utils_Array
::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array
::value('billing_last_name', $params);
417 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
418 $fields["address_name-{$this->_bltID}"] = 1;
420 $ctype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
425 $nameFields = array('first_name', 'middle_name', 'last_name');
426 foreach ($nameFields as $name) {
428 if (array_key_exists("billing_$name", $params)) {
429 $params[$name] = $params["billing_{$name}"];
430 $params['preserveDBName'] = TRUE;
434 if (!empty($params['source'])) {
435 unset($params['source']);
437 $contactID = CRM_Contact_BAO_Contact
::createProfileContact($params, $fields,
443 // add all the additioanl payment params we need
444 $this->_params
["state_province-{$this->_bltID}"] = $this->_params
["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($this->_params
["billing_state_province_id-{$this->_bltID}"]);
445 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
447 if ($this->_paymentProcessor
['payment_type'] & CRM_Core_Payment
::PAYMENT_TYPE_CREDIT_CARD
) {
448 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
449 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
451 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
452 $this->_params
['amount'] = $this->_params
['total_amount'];
453 $this->_params
['amount_level'] = 0;
454 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
456 $config->defaultCurrency
458 $this->_params
['payment_action'] = 'Sale';
459 if (!empty($this->_params
['trxn_date'])) {
460 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['trxn_date'], $this->_params
['receive_date_time']);
463 if (empty($this->_params
['invoice_id'])) {
464 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
467 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
470 //Add common data to formatted params
471 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
472 // at this point we've created a contact and stored its address etc
473 // all the payment processors expect the name and address to be in the
474 // so we copy stuff over to first_name etc.
475 $paymentParams = $this->_params
;
476 $paymentParams['contactID'] = $this->_contactId
;
477 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
479 $contributionType = new CRM_Financial_DAO_FinancialType();
480 $contributionType->id
= $params['financial_type_id'];
481 if (!$contributionType->find(TRUE)) {
482 CRM_Core_Error
::fatal('Could not find a system table');
485 // add some financial type details to the params list
486 // if folks need to use it
487 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $contributionType->name
;
488 $paymentParams['contributionPageID'] = NULL;
489 if (!empty($this->_params
['is_email_receipt'])) {
490 $paymentParams['email'] = $this->_contributorEmail
;
491 $paymentParams['is_email_receipt'] = 1;
494 $paymentParams['is_email_receipt'] = 0;
495 $this->_params
['is_email_receipt'] = 0;
497 if (!empty($this->_params
['receive_date'])) {
498 $paymentParams['receive_date'] = $this->_params
['receive_date'];
500 if (!empty($this->_params
['receive_date'])) {
501 $paymentParams['receive_date'] = $this->_params
['receive_date'];
506 if ($paymentParams['amount'] > 0.0) {
507 // force a reget of the payment processor in case the form changed it, CRM-7179
508 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this, TRUE);
509 $result = $payment->doDirectPayment($paymentParams);
512 if (is_a($result, 'CRM_Core_Error')) {
513 //set the contribution mode.
514 $urlParams = "action=add&cid={$this->_contactId}&id={$this->_id}&component={$this->_component}";
516 $urlParams .= "&mode={$this->_mode}";
518 CRM_Core_Error
::displaySessionError($result);
519 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/payment/add', $urlParams));
523 $this->_params
= array_merge($this->_params
, $result);
526 $this->_params
['receive_date'] = $now;
528 $this->set('params', $this->_params
);
530 // set source if not set
531 if (empty($this->_params
['source'])) {
532 $userID = $session->get('userID');
533 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
536 $this->_params
['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
539 // process the additional payment
540 $trxnRecord = CRM_Contribute_BAO_Contribution
::recordAdditionPayment($this->_contributionId
, $submittedValues, $this->_paymentType
, $participantId);
542 if ($trxnRecord->id
&& !empty($this->_params
['is_email_receipt'])) {
543 $sendReceipt = $this->emailReceipt($this->_params
);
546 if ($trxnRecord->id
) {
547 $statusMsg = ts('The payment record has been processed.');
548 if (!empty($this->_params
['is_email_receipt']) && $sendReceipt) {
549 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
552 $statusMsg .= ' ' . ts('Email has been sent successfully');
555 CRM_Core_Session
::setStatus($statusMsg, ts('Complete'), 'success');
556 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
557 "reset=1&cid={$this->_contactId}&selectedChild=participant"
562 function emailReceipt(&$params) {
563 // email receipt sending
564 // send message template
565 if ($this->_component
== 'event') {
566 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $this->_id
, 'event_id', 'id');
568 $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
569 CRM_Core_DAO
::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $eventId, $events, $returnProperties);
570 $event = $events[$eventId];
571 unset($event['start_date']);
572 unset($event['end_date']);
574 //$this-assign('component', $this->_component);
575 $this->assign('isShowLocation', $event['is_show_location']);
576 if (CRM_Utils_Array
::value('is_show_location', $event) == 1) {
577 $locationParams = array(
578 'entity_id' => $eventId,
579 'entity_table' => 'civicrm_event',
581 $location = CRM_Core_BAO_Location
::getValues($locationParams, TRUE);
582 $this->assign('location', $location);
586 // assign payment info here
587 $paymentConfig['confirm_email_text'] = CRM_Utils_Array
::value('confirm_email_text', $params);
588 $this->assign('paymentConfig', $paymentConfig);
589 $isRefund = ($this->_paymentType
== 'refund') ?
TRUE : FALSE;
590 $this->assign('isRefund', $isRefund);
592 $this->assign('totalPaid', $this->_amtPaid
);
593 $this->assign('totalAmount', $this->_amtTotal
);
594 $this->assign('refundAmount', $params['total_amount']);
597 $balance = $this->_amtTotal
- ($this->_amtPaid +
$params['total_amount']);
598 $this->assign('amountOwed', $balance);
599 $this->assign('totalAmount', $this->_amtTotal
);
600 $this->assign('paymentAmount', $params['total_amount']);
602 $this->assign('contactDisplayName', $this->_contributorDisplayName
);
604 // assign trxn details
605 $this->assign('trxn_id', CRM_Utils_Array
::value('trxn_id', $params));
606 $this->assign('receive_date', CRM_Utils_Array
::value('receive_date', $params));
607 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
608 if (array_key_exists('payment_instrument_id', $params)) {
609 $this->assign('paidBy',
610 CRM_Utils_Array
::value($params['payment_instrument_id'],
615 $this->assign('checkNumber', CRM_Utils_Array
::value('check_number', $params));
617 $sendTemplateParams = array(
618 'groupName' => 'msg_tpl_workflow_contribution',
619 'valueName' => 'payment_or_refund_notification',
620 'contactId' => $this->_contactId
,
621 'PDFFilename' => ts('notification').'.pdf',
624 // try to send emails only if email id is present
625 // and the do-not-email option is not checked for that contact
626 if ($this->_contributorEmail
&& !$this->_toDoNotEmail
) {
627 if (array_key_exists($params['from_email_address'], $this->_fromEmails
['from_email_id'])) {
628 $receiptFrom = $params['from_email_address'];
631 $sendTemplateParams['from'] = $receiptFrom;
632 $sendTemplateParams['toName'] = $this->_contributorDisplayName
;
633 $sendTemplateParams['toEmail'] = $this->_contributorEmail
;
634 $sendTemplateParams['cc'] = CRM_Utils_Array
::value('cc', $this->_fromEmails
);
635 $sendTemplateParams['bcc'] = CRM_Utils_Array
::value('bcc', $this->_fromEmails
);
637 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);