Merge remote-tracking branch 'upstream/4.4' into 4.4-master-2014-08-25-10-57-01
[civicrm-core.git] / CRM / Contribute / Form / AdditionalPayment.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * This form records additional payments needed when
38 * event/contribution is partially paid
39 *
40 */
41 class CRM_Contribute_Form_AdditionalPayment extends CRM_Contribute_Form_AbstractEditPayment {
42 public $_contributeMode = 'direct';
43
44 /**
45 * related component whose financial payment is being processed
46 *
47 * @var string
48 * @public
49 */
50 protected $_component = NULL;
51
52 /**
53 * id of the component entity
54 */
55 public $_id = NULL;
56
57 protected $_owed = NULL;
58
59 protected $_refund = NULL;
60
61 protected $_contactId = NULL;
62
63 protected $_contributorDisplayName = NULL;
64
65 protected $_contributorEmail = NULL;
66
67 protected $_toDoNotEmail = NULL;
68
69 protected $_paymentType = NULL;
70
71 protected $_contributionId = NULL;
72
73 protected $fromEmailId = NULL;
74
75 protected $_fromEmails = NULL;
76
77 protected $_view = NULL;
78
79 public $_action = NULL;
80
81 public function preProcess() {
82 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
83 $this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
84 $this->_component = CRM_Utils_Request::retrieve('component', 'String', $this, TRUE);
85 $this->_view = CRM_Utils_Request::retrieve('view', 'String', $this, FALSE);
86 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE);
87 $this->assign('component', $this->_component);
88 $this->assign('id', $this->_id);
89
90 if ($this->_view == 'transaction' && ($this->_action & CRM_Core_Action::BROWSE)) {
91 $paymentInfo = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_id, $this->_component, TRUE);
92 $transactionRows = $paymentInfo['transaction'];
93 $title = ts('View Payment');
94 if ($this->_component == 'event') {
95 $info = CRM_Event_BAO_Participant::participantDetails($this->_id);
96 $title .= " - {$info['title']}";
97 }
98 CRM_Utils_System::setTitle($title);
99 $this->assign('transaction', TRUE);
100 $this->assign('rows', $transactionRows);
101 return;
102 }
103 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
104 $this->_formType = CRM_Utils_Array::value('formType', $_GET);
105
106 $enitityType = NULL;
107 if ($this->_component == 'event') {
108 $enitityType = 'participant';
109 $this->_contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id');
110 }
111 $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id');
112 $this->_fromEmails = CRM_Event_BAO_Event::getFromEmailIds($eventId);
113
114 $paymentInfo = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($this->_id, $enitityType);
115 $paymentDetails = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_id, $this->_component, FALSE, TRUE);
116
117 $this->_amtPaid = $paymentDetails['paid'];
118 $this->_amtTotal = $paymentDetails['total'];
119
120 if (!empty($paymentInfo['refund_due'])) {
121 $paymentAmt = $this->_refund = $paymentInfo['refund_due'];
122 $this->_paymentType = 'refund';
123 }
124 elseif (!empty($paymentInfo['amount_owed'])) {
125 $paymentAmt = $this->_owed = $paymentInfo['amount_owed'];
126 $this->_paymentType = 'owed';
127 }
128 else {
129 CRM_Core_Error::fatal(ts('No payment information found for this record'));
130 }
131
132 //set the payment mode - _mode property is defined in parent class
133 $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
134
135 if (!empty($this->_mode) && $this->_paymentType == 'refund') {
136 CRM_Core_Error::fatal(ts('Credit card payment is not for Refund payments use'));
137 }
138
139 list($this->_contributorDisplayName, $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactId);
140
141 if (!$this->_refund) {
142 $this->assignProcessors();
143 // also check for billing information
144 // get the billing location type
145 $this->assignBillingType();
146 }
147
148 $this->assign('contributionMode', $this->_mode);
149 $this->assign('contactId', $this->_contactId);
150 $this->assign('paymentType', $this->_paymentType);
151 $this->assign('paymentAmt', abs($paymentAmt));
152
153 $this->setPageTitle($this->_refund ? ts('Refund') : ts('Payment'));
154
155 $this->_paymentProcessor = array('billing_mode' => 1);
156 }
157
158 /**
159 * This virtual function is used to set the default values of
160 * various form elements
161 *
162 * access public
163 *
164 * @return array reference to the array of default values
165 *
166 */
167 /**
168 * @return array
169 */
170 public function setDefaultValues() {
171 if ($this->_view == 'transaction' && ($this->_action & CRM_Core_Action::BROWSE)) {
172 return;
173 }
174 $defaults = array( );
175 if ($this->_mode) {
176 $defaults = $this->_values;
177
178 $config = CRM_Core_Config::singleton();
179 // set default country from config if no country set
180 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
181 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
182 }
183
184 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
185 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
186 }
187
188 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactId);
189 $defaults = array_merge($defaults, $billingDefaults);
190
191 // now fix all state country selectors, set correct state based on country
192 CRM_Core_BAO_Address::fixAllStateSelects($this, $defaults);
193 }
194
195 if (empty($defaults['trxn_date']) && empty($defaults['trxn_date_time'])) {
196 list($defaults['trxn_date'],
197 $defaults['trxn_date_time']
198 ) = CRM_Utils_Date::setDateDefaults(
199 CRM_Utils_Array::value('register_date', $defaults), 'activityDateTime'
200 );
201 }
202
203 if ($this->_refund) {
204 $defaults['total_amount'] = abs($this->_refund);
205 }
206
207 // Set $newCredit variable in template to control whether link to credit card mode is included
208 $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
209 return $defaults;
210 }
211
212 public function buildQuickForm() {
213 if ($this->_view == 'transaction' && ($this->_action & CRM_Core_Action::BROWSE)) {
214 $this->addButtons(array(
215 array(
216 'type' => 'cancel',
217 'name' => ts('Done'),
218 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
219 'isDefault' => TRUE,
220 ),
221 )
222 );
223 return;
224 }
225 $ccPane = NULL;
226 if ($this->_mode) {
227 if (CRM_Utils_Array::value('payment_type', $this->_processors) & CRM_Core_Payment::PAYMENT_TYPE_DIRECT_DEBIT
228 ) {
229 $ccPane = array(ts('Direct Debit Information') => 'DirectDebit');
230 }
231 else {
232 $ccPane = array(ts('Credit Card Information') => 'CreditCard');
233 }
234 $defaults = $this->_values;
235 $showAdditionalInfo = FALSE;
236
237 foreach ($ccPane as $name => $type) {
238 if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) ||
239 CRM_Utils_Array::value("hidden_{$type}", $defaults)
240 ) {
241 $showAdditionalInfo = TRUE;
242 $allPanes[$name]['open'] = 'true';
243 }
244
245 $urlParams = "snippet=4&formType={$type}";
246 if ($this->_mode) {
247 $urlParams .= "&mode={$this->_mode}";
248 }
249 $open = 'false';
250 if ($type == 'CreditCard' ||
251 $type == 'DirectDebit'
252 ) {
253 $open = 'true';
254 }
255
256 $allPanes[$name] = array(
257 'url' => CRM_Utils_System::url('civicrm/payment/add', $urlParams),
258 'open' => $open,
259 'id' => $type
260 );
261
262 if ($type == 'CreditCard') {
263 $this->add('hidden', 'hidden_CreditCard', 1);
264 CRM_Core_Payment_Form::buildCreditCard($this, TRUE);
265 }
266 elseif ($type == 'DirectDebit') {
267 $this->add('hidden', 'hidden_DirectDebit', 1);
268 CRM_Core_Payment_Form::buildDirectDebit($this, TRUE);
269 }
270 $qfKey = $this->controller->_key;
271 $this->assign('qfKey', $qfKey);
272 $this->assign('allPanes', $allPanes);
273 $this->assign('showAdditionalInfo', $showAdditionalInfo);
274
275 if ($this->_formType) {
276 $this->assign('formType', $this->_formType);
277 return;
278 }
279 }
280 }
281 $attributes = CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialTrxn');
282
283 $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors, NULL);
284 $label = ($this->_refund) ? 'Refund Amount' : 'Payment Amount';
285 $this->addMoney('total_amount',
286 ts('%1', array(1 => $label)),
287 FALSE,
288 $attributes['total_amount'],
289 TRUE, 'currency', NULL
290 );
291
292 $this->add('select', 'payment_instrument_id',
293 ts('Paid By'),
294 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
295 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
296 );
297
298 $this->add('text', 'check_number', ts('Check Number'), $attributes['financial_trxn_check_number']);
299 $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') + $attributes['trxn_id']);
300
301 //add receipt for offline contribution
302 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
303
304 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails['from_email_id']);
305
306 $this->add('textarea', 'receipt_text', ts('Confirmation Message'));
307
308 // add various dates
309 $dateLabel = ($this->_refund) ? 'Refund Date' : 'Received Date';
310 $this->addDateTime('trxn_date', ts('%1', array(1 => $dateLabel)), FALSE, array('formatType' => 'activityDateTime'));
311
312 if ($this->_contactId && $this->_id) {
313 if ($this->_component == 'event') {
314 $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id');
315 $event = CRM_Event_BAO_Event::getEvents(0, $eventId);
316 $this->assign('eventName', $event[$eventId]);
317 }
318 }
319
320 $this->assign('displayName', $this->_contributorDisplayName);
321 $this->assign('component', $this->_component);
322 $this->assign('email', $this->_contributorEmail);
323
324 $this->add('text', 'fee_amount', ts('Fee Amount'),
325 $attributes['fee_amount']
326 );
327 $this->addRule('fee_amount', ts('Please enter a valid monetary value for Fee Amount.'), 'money');
328
329 $this->add('text', 'net_amount', ts('Net Amount'),
330 $attributes['net_amount']
331 );
332 $this->addRule('net_amount', ts('Please enter a valid monetary value for Net Amount.'), 'money');
333
334 $js = NULL;
335 if (!$this->_mode) {
336 $js = array('onclick' => "return verify( );");
337 }
338
339 $buttonName = $this->_refund ? 'Record Refund' : 'Record Payment';
340 $this->addButtons(array(
341 array(
342 'type' => 'upload',
343 'name' => ts('%1', array(1 => $buttonName)),
344 'js' => $js,
345 'isDefault' => TRUE
346 ),
347 array(
348 'type' => 'cancel',
349 'name' => ts('Cancel')
350 ),
351 )
352 );
353
354
355 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
356 'mailing_backend'
357 );
358 $this->assign('outBound_option', $mailingInfo['outBound_option']);
359
360 $this->addFormRule(array('CRM_Contribute_Form_AdditionalPayment', 'formRule'), $this);
361 }
362
363 /**
364 * @param $fields
365 * @param $files
366 * @param $self
367 *
368 * @return array
369 */
370 static function formRule($fields, $files, $self) {
371 $errors = array();
372 if ($self->_paymentType == 'owed' && $fields['total_amount'] > $self->_owed) {
373 $errors['total_amount'] = ts('Payment amount cannot be greater than owed amount');
374 }
375 if ($self->_paymentType == 'refund' && $fields['total_amount'] != abs($self->_refund)) {
376 $errors['total_amount'] = ts('Refund amount must equal refund due amount.');
377 }
378 $netAmt = $fields['total_amount'] - $fields['fee_amount'];
379 if (!empty($fields['net_amount']) && $netAmt != $fields['net_amount']) {
380 $errors['net_amount'] = ts('Net amount should be equal to the difference between payment amount and fee amount.');
381 }
382 return $errors;
383 }
384
385 public function postProcess() {
386 $participantId = NULL;
387 if ($this->_component == 'event') {
388 $participantId = $this->_id;
389 }
390 $submittedValues = $this->controller->exportValues($this->_name);
391 $submittedValues['confirm_email_text'] = CRM_Utils_Array::value('receipt_text', $submittedValues);
392
393 $submittedValues['trxn_date'] = CRM_Utils_Date::processDate($submittedValues['trxn_date'], $submittedValues['trxn_date_time']);
394 if ($this->_mode) {
395 // process credit card
396 $this->assign('contributeMode', 'direct');
397 $this->processCreditCard($submittedValues);
398 }
399 else {
400 $result = CRM_Contribute_BAO_Contribution::recordAdditionalPayment($this->_contributionId, $submittedValues, $this->_paymentType, $participantId);
401
402 // email sending
403 if (!empty($result) && !empty($submittedValues['is_email_receipt'])) {
404 $submittedValues['contact_id'] = $this->_contactId;
405 $submittedValues['contribution_id'] = $this->_contributionId;
406
407 // to get 'from email id' for send receipt
408 $this->fromEmailId = $submittedValues['from_email_address'];
409 $sendReceipt = $this->emailReceipt($submittedValues);
410 }
411
412 $statusMsg = ts('The payment record has been processed.');
413 if (!empty($submittedValues['is_email_receipt']) && $sendReceipt) {
414 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
415 }
416
417 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
418
419 $session = CRM_Core_Session::singleton();
420 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
421 "reset=1&cid={$this->_contactId}&selectedChild=participant"
422 ));
423 }
424 }
425
426 /**
427 * @param $submittedValues
428 */
429 public function processCreditCard($submittedValues) {
430 $config = CRM_Core_Config::singleton();
431 $session = CRM_Core_Session::singleton();
432
433 $unsetParams = array(
434 'trxn_id',
435 'payment_instrument_id',
436 'contribution_status_id',
437 );
438 foreach ($unsetParams as $key) {
439 if (isset($submittedValues[$key])) {
440 unset($submittedValues[$key]);
441 }
442 }
443
444 //Get the rquire fields value only.
445 $params = $this->_params = $submittedValues;
446
447 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
448 $this->_mode
449 );
450
451 //get the payment processor id as per mode.
452 $this->_params['payment_processor'] = $params['payment_processor_id'] =
453 $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
454
455 $now = date('YmdHis');
456 $fields = array();
457
458 // we need to retrieve email address
459 if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
460 list($this->userDisplayName,
461 $this->userEmail
462 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactId);
463 $this->assign('displayName', $this->userDisplayName);
464 }
465
466 //set email for primary location.
467 $fields['email-Primary'] = 1;
468 $params['email-Primary'] = $this->_contributorEmail;
469
470 // now set the values for the billing location.
471 foreach ($this->_fields as $name => $dontCare) {
472 $fields[$name] = 1;
473 }
474
475 // also add location name to the array
476 $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);
477 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
478 $fields["address_name-{$this->_bltID}"] = 1;
479
480 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
481 $this->_contactId,
482 'contact_type'
483 );
484
485 $nameFields = array('first_name', 'middle_name', 'last_name');
486 foreach ($nameFields as $name) {
487 $fields[$name] = 1;
488 if (array_key_exists("billing_$name", $params)) {
489 $params[$name] = $params["billing_{$name}"];
490 $params['preserveDBName'] = TRUE;
491 }
492 }
493
494 if (!empty($params['source'])) {
495 unset($params['source']);
496 }
497 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields,
498 $this->_contactId,
499 NULL, NULL,
500 $ctype
501 );
502
503 // add all the additioanl payment params we need
504 $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}"]);
505 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
506
507 if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD) {
508 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
509 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
510 }
511 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
512 $this->_params['amount'] = $this->_params['total_amount'];
513 $this->_params['amount_level'] = 0;
514 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
515 $this->_params,
516 $config->defaultCurrency
517 );
518 $this->_params['payment_action'] = 'Sale';
519 if (!empty($this->_params['trxn_date'])) {
520 $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['trxn_date'], $this->_params['trxn_date_time']);
521 }
522
523 if (empty($this->_params['invoice_id'])) {
524 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
525 }
526 else {
527 $this->_params['invoiceID'] = $this->_params['invoice_id'];
528 }
529
530 // billing name and Address
531 $name = CRM_Utils_Array::value('billing_first_name', $params);
532 if (!empty($params['billing_middle_name'])) {
533 $name .= " {$params['billing_middle_name']}";
534 }
535 $name .= ' ' . CRM_Utils_Array::value('billing_last_name', $params);
536 $name = trim($name);
537 $this->assign('billingName', $name);
538
539 //assign the address formatted up for display
540 $addressParts = array(
541 "street_address" => "billing_street_address-{$this->_bltID}",
542 "city" => "billing_city-{$this->_bltID}",
543 "postal_code" => "billing_postal_code-{$this->_bltID}",
544 "state_province" => "state_province-{$this->_bltID}",
545 "country" => "country-{$this->_bltID}",
546 );
547 $addressFields = array();
548 foreach ($addressParts as $name => $field) {
549 $addressFields[$name] = CRM_Utils_Array::value($field, $params);
550 }
551 $this->assign('address', CRM_Utils_Address::format($addressFields));
552 $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
553 $date = CRM_Utils_Date::mysqlToIso($date);
554 $this->assign('credit_card_type', CRM_Utils_Array::value('credit_card_type', $params));
555 $this->assign('credit_card_exp_date', $date);
556 $this->assign('credit_card_number',
557 CRM_Utils_System::mungeCreditCard($params['credit_card_number'])
558 );
559
560 //Add common data to formatted params
561 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
562 // at this point we've created a contact and stored its address etc
563 // all the payment processors expect the name and address to be in the
564 // so we copy stuff over to first_name etc.
565 $paymentParams = $this->_params;
566 $paymentParams['contactID'] = $this->_contactId;
567 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
568
569 // add some financial type details to the params list
570 // if folks need to use it
571 $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
572 $paymentParams['contributionPageID'] = NULL;
573 if (!empty($this->_params['is_email_receipt'])) {
574 $paymentParams['email'] = $this->_contributorEmail;
575 $paymentParams['is_email_receipt'] = 1;
576 }
577 else {
578 $paymentParams['is_email_receipt'] = 0;
579 $this->_params['is_email_receipt'] = 0;
580 }
581 if (!empty($this->_params['receive_date'])) {
582 $paymentParams['receive_date'] = $this->_params['receive_date'];
583 }
584 if (!empty($this->_params['receive_date'])) {
585 $paymentParams['receive_date'] = $this->_params['receive_date'];
586 }
587
588 $result = NULL;
589
590 if ($paymentParams['amount'] > 0.0) {
591 // force a reget of the payment processor in case the form changed it, CRM-7179
592 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE);
593 $result = $payment->doDirectPayment($paymentParams);
594 }
595
596 if (is_a($result, 'CRM_Core_Error')) {
597 //set the contribution mode.
598 $urlParams = "action=add&cid={$this->_contactId}&id={$this->_id}&component={$this->_component}";
599 if ($this->_mode) {
600 $urlParams .= "&mode={$this->_mode}";
601 }
602 CRM_Core_Error::displaySessionError($result);
603 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/payment/add', $urlParams));
604 }
605
606 if ($result) {
607 $this->_params = array_merge($this->_params, $result);
608 }
609
610 if (empty($this->_params['receive_date'])) {
611 $this->_params['receive_date'] = $now;
612 }
613
614 $this->set('params', $this->_params);
615
616 // set source if not set
617 if (empty($this->_params['source'])) {
618 $userID = $session->get('userID');
619 $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
620 'sort_name'
621 );
622 $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
623 }
624
625 // process the additional payment
626 $participantId = NULL;
627 if ($this->_component == 'event') {
628 $participantId = $this->_id;
629 }
630 $trxnRecord = CRM_Contribute_BAO_Contribution::recordAdditionalPayment($this->_contributionId, $submittedValues, $this->_paymentType, $participantId);
631
632 if ($trxnRecord->id && !empty($this->_params['is_email_receipt'])) {
633 $sendReceipt = $this->emailReceipt($this->_params);
634 }
635
636 if ($trxnRecord->id) {
637 $statusMsg = ts('The payment record has been processed.');
638 if (!empty($this->_params['is_email_receipt']) && $sendReceipt) {
639 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
640 }
641
642 CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
643 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
644 "reset=1&cid={$this->_contactId}&selectedChild=participant"
645 ));
646 }
647 }
648
649 /**
650 * @param $params
651 *
652 * @return mixed
653 */
654 function emailReceipt(&$params) {
655 // email receipt sending
656 // send message template
657 if ($this->_component == 'event') {
658 $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id');
659
660 $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
661 CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $eventId, $events, $returnProperties);
662 $event = $events[$eventId];
663 unset($event['start_date']);
664 unset($event['end_date']);
665
666 $this->assign('event', $event);
667 $this->assign('isShowLocation', $event['is_show_location']);
668 if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
669 $locationParams = array(
670 'entity_id' => $eventId,
671 'entity_table' => 'civicrm_event',
672 );
673 $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
674 $this->assign('location', $location);
675 }
676 }
677
678 // assign payment info here
679 $paymentConfig['confirm_email_text'] = CRM_Utils_Array::value('confirm_email_text', $params);
680 $this->assign('paymentConfig', $paymentConfig);
681 $isRefund = ($this->_paymentType == 'refund') ? TRUE : FALSE;
682 $this->assign('isRefund', $isRefund);
683 if ($isRefund) {
684 $this->assign('totalPaid', $this->_amtPaid);
685 $this->assign('totalAmount', $this->_amtTotal);
686 $this->assign('refundAmount', $params['total_amount']);
687 }
688 else {
689 $balance = $this->_amtTotal - ($this->_amtPaid + $params['total_amount']);
690 $paymentsComplete = ($balance == 0) ? 1 : 0;
691 $this->assign('amountOwed', $balance);
692 $this->assign('totalAmount', $this->_amtTotal);
693 $this->assign('paymentAmount', $params['total_amount']);
694 $this->assign('paymentsComplete', $paymentsComplete);
695 }
696 $this->assign('contactDisplayName', $this->_contributorDisplayName);
697
698 // assign trxn details
699 $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $params));
700 $this->assign('receive_date', CRM_Utils_Array::value('trxn_date', $params));
701 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
702 if (array_key_exists('payment_instrument_id', $params)) {
703 $this->assign('paidBy',
704 CRM_Utils_Array::value($params['payment_instrument_id'],
705 $paymentInstrument
706 )
707 );
708 }
709 $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
710
711 $sendTemplateParams = array(
712 'groupName' => 'msg_tpl_workflow_contribution',
713 'valueName' => 'payment_or_refund_notification',
714 'contactId' => $this->_contactId,
715 'PDFFilename' => ts('notification').'.pdf',
716 );
717
718 // try to send emails only if email id is present
719 // and the do-not-email option is not checked for that contact
720 if ($this->_contributorEmail && !$this->_toDoNotEmail) {
721 if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
722 $receiptFrom = $params['from_email_address'];
723 }
724
725 $sendTemplateParams['from'] = $receiptFrom;
726 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
727 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
728 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
729 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
730 }
731 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
732 return $mailSent;
733 }
734 }