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 $dateLabel = ($this->_refund
) ?
'Refund Date' : 'Received Date';
260 $this->addDateTime('trxn_date', ts('%1', array(1 => $dateLabel)), FALSE, array('formatType' => 'activityDateTime'));
262 if ($this->_contactId
&& $this->_id
) {
263 if ($this->_component
== 'event') {
264 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $this->_id
, 'event_id', 'id');
265 $event = CRM_Event_BAO_Event
::getEvents(0, $eventId);
266 $this->assign('eventName', $event[$eventId]);
270 $this->assign('displayName', $this->_contributorDisplayName
);
271 $this->assign('component', $this->_component
);
272 $this->assign('email', $this->_contributorEmail
);
274 $this->add('text', 'fee_amount', ts('Fee Amount'),
275 $attributes['fee_amount']
277 $this->addRule('fee_amount', ts('Please enter a valid monetary value for Fee Amount.'), 'money');
279 $this->add('text', 'net_amount', ts('Net Amount'),
280 $attributes['net_amount']
282 $this->addRule('net_amount', ts('Please enter a valid monetary value for Net Amount.'), 'money');
286 $js = array('onclick' => "return verify( );");
289 $buttonName = $this->_refund ?
'Record Refund' : 'Record Payment';
290 $this->addButtons(array(
293 'name' => ts('%1', array(1 => $buttonName)),
299 'name' => ts('Cancel')
305 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
308 $this->assign('outBound_option', $mailingInfo['outBound_option']);
310 $this->addFormRule(array('CRM_Contribute_Form_AdditionalPayment', 'formRule'), $this);
313 static function formRule($fields, $files, $self) {
315 if ($self->_paymentType
== 'owed' && $fields['total_amount'] > $self->_owed
) {
316 $errors['total_amount'] = ts('Payment amount cannot be greater than owed amount');
318 if ($self->_paymentType
== 'refund' && $fields['total_amount'] != abs($self->_refund
)) {
319 $errors['total_amount'] = ts('Refund amount must equal refund due amount.');
321 $netAmt = $fields['total_amount'] - $fields['fee_amount'];
322 if (!empty($fields['net_amount']) && $netAmt != $fields['net_amount']) {
323 $errors['net_amount'] = ts('Net amount should be equal to the difference between payment amount and fee amount.');
328 public function postProcess() {
329 $participantId = NULL;
330 if ($this->_component
== 'event') {
331 $participantId = $this->_id
;
333 $submittedValues = $this->controller
->exportValues($this->_name
);
334 $submittedValues['confirm_email_text'] = CRM_Utils_Array
::value('receipt_text', $submittedValues);
336 $submittedValues['trxn_date'] = CRM_Utils_Date
::processDate($submittedValues['trxn_date'], $submittedValues['trxn_date_time']);
338 // process credit card
339 $this->processCreditCard($submittedValues);
342 $result = CRM_Contribute_BAO_Contribution
::recordAdditionPayment($this->_contributionId
, $submittedValues, $this->_paymentType
, $participantId);
345 if (!empty($result) && !empty($submittedValues['is_email_receipt'])) {
346 $submittedValues['contact_id'] = $this->_contactId
;
347 $submittedValues['contribution_id'] = $this->_contributionId
;
349 // to get 'from email id' for send receipt
350 $this->fromEmailId
= $submittedValues['from_email_address'];
351 $sendReceipt = $this->emailReceipt($submittedValues);
354 $statusMsg = ts('The payment record has been processed.');
355 if (!empty($submittedValues['is_email_receipt']) && $sendReceipt) {
356 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
358 if (isset($sendReceipt)) {
359 $statusMsg .= ' ' . ts('Email has been sent successfully');
361 CRM_Core_Session
::setStatus($statusMsg, ts('Saved'), 'success');
363 $session = CRM_Core_Session
::singleton();
364 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
365 "reset=1&cid={$this->_contactId}&selectedChild=participant"
370 public function processCreditCard($submittedValues) {
371 $config = CRM_Core_Config
::singleton();
372 $session = CRM_Core_Session
::singleton();
374 $unsetParams = array(
376 'payment_instrument_id',
377 'contribution_status_id',
379 foreach ($unsetParams as $key) {
380 if (isset($submittedValues[$key])) {
381 unset($submittedValues[$key]);
385 //Get the rquire fields value only.
386 $params = $this->_params
= $submittedValues;
388 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment($this->_params
['payment_processor_id'],
392 //get the payment processor id as per mode.
393 $this->_params
['payment_processor'] = $params['payment_processor_id'] =
394 $this->_params
['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
396 $now = date('YmdHis');
399 // we need to retrieve email address
400 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
401 list($this->userDisplayName
,
403 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactId
);
404 $this->assign('displayName', $this->userDisplayName
);
407 //set email for primary location.
408 $fields['email-Primary'] = 1;
409 $params['email-Primary'] = $this->_contributorEmail
;
411 // now set the values for the billing location.
412 foreach ($this->_fields
as $name => $dontCare) {
416 // also add location name to the array
417 $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);
418 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
419 $fields["address_name-{$this->_bltID}"] = 1;
421 $ctype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
426 $nameFields = array('first_name', 'middle_name', 'last_name');
427 foreach ($nameFields as $name) {
429 if (array_key_exists("billing_$name", $params)) {
430 $params[$name] = $params["billing_{$name}"];
431 $params['preserveDBName'] = TRUE;
435 if (!empty($params['source'])) {
436 unset($params['source']);
438 $contactID = CRM_Contact_BAO_Contact
::createProfileContact($params, $fields,
444 // add all the additioanl payment params we need
445 $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}"]);
446 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
448 if ($this->_paymentProcessor
['payment_type'] & CRM_Core_Payment
::PAYMENT_TYPE_CREDIT_CARD
) {
449 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
450 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
452 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
453 $this->_params
['amount'] = $this->_params
['total_amount'];
454 $this->_params
['amount_level'] = 0;
455 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
457 $config->defaultCurrency
459 $this->_params
['payment_action'] = 'Sale';
460 if (!empty($this->_params
['trxn_date'])) {
461 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['trxn_date'], $this->_params
['receive_date_time']);
464 if (empty($this->_params
['invoice_id'])) {
465 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
468 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
471 //Add common data to formatted params
472 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
473 // at this point we've created a contact and stored its address etc
474 // all the payment processors expect the name and address to be in the
475 // so we copy stuff over to first_name etc.
476 $paymentParams = $this->_params
;
477 $paymentParams['contactID'] = $this->_contactId
;
478 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
480 $contributionType = new CRM_Financial_DAO_FinancialType();
481 $contributionType->id
= $params['financial_type_id'];
482 if (!$contributionType->find(TRUE)) {
483 CRM_Core_Error
::fatal('Could not find a system table');
486 // add some financial type details to the params list
487 // if folks need to use it
488 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $contributionType->name
;
489 $paymentParams['contributionPageID'] = NULL;
490 if (!empty($this->_params
['is_email_receipt'])) {
491 $paymentParams['email'] = $this->_contributorEmail
;
492 $paymentParams['is_email_receipt'] = 1;
495 $paymentParams['is_email_receipt'] = 0;
496 $this->_params
['is_email_receipt'] = 0;
498 if (!empty($this->_params
['receive_date'])) {
499 $paymentParams['receive_date'] = $this->_params
['receive_date'];
501 if (!empty($this->_params
['receive_date'])) {
502 $paymentParams['receive_date'] = $this->_params
['receive_date'];
507 if ($paymentParams['amount'] > 0.0) {
508 // force a reget of the payment processor in case the form changed it, CRM-7179
509 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this, TRUE);
510 $result = $payment->doDirectPayment($paymentParams);
513 if (is_a($result, 'CRM_Core_Error')) {
514 //set the contribution mode.
515 $urlParams = "action=add&cid={$this->_contactId}&id={$this->_id}&component={$this->_component}";
517 $urlParams .= "&mode={$this->_mode}";
519 CRM_Core_Error
::displaySessionError($result);
520 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/payment/add', $urlParams));
524 $this->_params
= array_merge($this->_params
, $result);
527 $this->_params
['receive_date'] = $now;
529 $this->set('params', $this->_params
);
531 // set source if not set
532 if (empty($this->_params
['source'])) {
533 $userID = $session->get('userID');
534 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
537 $this->_params
['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
540 // process the additional payment
541 $trxnRecord = CRM_Contribute_BAO_Contribution
::recordAdditionPayment($this->_contributionId
, $submittedValues, $this->_paymentType
, $participantId);
543 if ($trxnRecord->id
&& !empty($this->_params
['is_email_receipt'])) {
544 $sendReceipt = $this->emailReceipt($this->_params
);
547 if ($trxnRecord->id
) {
548 $statusMsg = ts('The payment record has been processed.');
549 if (!empty($this->_params
['is_email_receipt']) && $sendReceipt) {
550 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
553 $statusMsg .= ' ' . ts('Email has been sent successfully');
556 CRM_Core_Session
::setStatus($statusMsg, ts('Complete'), 'success');
557 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
558 "reset=1&cid={$this->_contactId}&selectedChild=participant"
563 function emailReceipt(&$params) {
564 // email receipt sending
565 // send message template
566 if ($this->_component
== 'event') {
567 $eventId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $this->_id
, 'event_id', 'id');
569 $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
570 CRM_Core_DAO
::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $eventId, $events, $returnProperties);
571 $event = $events[$eventId];
572 unset($event['start_date']);
573 unset($event['end_date']);
575 //$this-assign('component', $this->_component);
576 $this->assign('isShowLocation', $event['is_show_location']);
577 if (CRM_Utils_Array
::value('is_show_location', $event) == 1) {
578 $locationParams = array(
579 'entity_id' => $eventId,
580 'entity_table' => 'civicrm_event',
582 $location = CRM_Core_BAO_Location
::getValues($locationParams, TRUE);
583 $this->assign('location', $location);
587 // assign payment info here
588 $paymentConfig['confirm_email_text'] = CRM_Utils_Array
::value('confirm_email_text', $params);
589 $this->assign('paymentConfig', $paymentConfig);
590 $isRefund = ($this->_paymentType
== 'refund') ?
TRUE : FALSE;
591 $this->assign('isRefund', $isRefund);
593 $this->assign('totalPaid', $this->_amtPaid
);
594 $this->assign('totalAmount', $this->_amtTotal
);
595 $this->assign('refundAmount', $params['total_amount']);
598 $balance = $this->_amtTotal
- ($this->_amtPaid +
$params['total_amount']);
599 $this->assign('amountOwed', $balance);
600 $this->assign('totalAmount', $this->_amtTotal
);
601 $this->assign('paymentAmount', $params['total_amount']);
603 $this->assign('contactDisplayName', $this->_contributorDisplayName
);
605 // assign trxn details
606 $this->assign('trxn_id', CRM_Utils_Array
::value('trxn_id', $params));
607 $this->assign('receive_date', CRM_Utils_Array
::value('receive_date', $params));
608 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
609 if (array_key_exists('payment_instrument_id', $params)) {
610 $this->assign('paidBy',
611 CRM_Utils_Array
::value($params['payment_instrument_id'],
616 $this->assign('checkNumber', CRM_Utils_Array
::value('check_number', $params));
618 $sendTemplateParams = array(
619 'groupName' => 'msg_tpl_workflow_contribution',
620 'valueName' => 'payment_or_refund_notification',
621 'contactId' => $this->_contactId
,
622 'PDFFilename' => ts('notification').'.pdf',
625 // try to send emails only if email id is present
626 // and the do-not-email option is not checked for that contact
627 if ($this->_contributorEmail
&& !$this->_toDoNotEmail
) {
628 if (array_key_exists($params['from_email_address'], $this->_fromEmails
['from_email_id'])) {
629 $receiptFrom = $params['from_email_address'];
632 $sendTemplateParams['from'] = $receiptFrom;
633 $sendTemplateParams['toName'] = $this->_contributorDisplayName
;
634 $sendTemplateParams['toEmail'] = $this->_contributorEmail
;
635 $sendTemplateParams['cc'] = CRM_Utils_Array
::value('cc', $this->_fromEmails
);
636 $sendTemplateParams['bcc'] = CRM_Utils_Array
::value('bcc', $this->_fromEmails
);
638 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);