Merge pull request #1646 from monishdeb/CRM-13383
[civicrm-core.git] / CRM / Contribute / Form / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
32 * $Id$
33 *
34 */
35
36 /**
37 * This class generates form components for processing a contribution
38 *
39 */
40 class CRM_Contribute_Form_Contribution extends CRM_Contribute_Form_AbstractEditPayment {
41 /**
42 * the id of the contribution that we are proceessing
43 *
44 * @var int
45 * @public
46 */
47 public $_id;
48
49 /**
50 * the id of the premium that we are proceessing
51 *
52 * @var int
53 * @public
54 */
55 public $_premiumID = NULL;
56 public $_productDAO = NULL;
57
58 /**
59 * the id of the note
60 *
61 * @var int
62 * @public
63 */
64 public $_noteID;
65
66 /**
67 * the id of the contact associated with this contribution
68 *
69 * @var int
70 * @public
71 */
72 public $_contactID;
73
74 /**
75 * the id of the pledge payment that we are processing
76 *
77 * @var int
78 * @public
79 */
80 public $_ppID;
81
82 /**
83 * the id of the pledge that we are processing
84 *
85 * @var int
86 * @public
87 */
88 public $_pledgeID;
89
90 /**
91 * is this contribution associated with an online
92 * financial transaction
93 *
94 * @var boolean
95 * @public
96 */
97 public $_online = FALSE;
98
99 /**
100 * Stores all product option
101 *
102 * @var array
103 * @public
104 */
105 public $_options;
106
107 /**
108 * stores the honor id
109 *
110 * @var int
111 * @public
112 */
113 public $_honorID = NULL;
114
115 /**
116 * Store the contribution Type ID
117 *
118 * @var array
119 */
120 public $_contributionType;
121
122 /**
123 * The contribution values if an existing contribution
124 */
125 public $_values;
126
127 /**
128 * The pledge values if this contribution is associated with pledge
129 */
130 public $_pledgeValues;
131
132 public $_contributeMode = 'direct';
133
134 public $_context;
135
136 public $_compId;
137
138 /*
139 * Store the line items if price set used.
140 */
141 public $_lineItems;
142
143 /**
144 * @var soft credit info
145 */
146 public $_softCreditInfo;
147
148 protected $_formType;
149 protected $_cdType;
150
151 /**
152 * Function to set variables up before form is built
153 *
154 * @return void
155 * @access public
156 */
157 public function preProcess() {
158
159 //check permission for action.
160 if (!CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
161 CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
162 }
163
164 $this->_cdType = CRM_Utils_Array::value('type', $_GET);
165
166 $this->assign('cdType', FALSE);
167 if ($this->_cdType) {
168 $this->assign('cdType', TRUE);
169 CRM_Custom_Form_CustomData::preProcess($this);
170 return;
171 }
172
173 $config = CRM_Core_Config::singleton();
174 $resources = CRM_Core_Resources::singleton();
175 $resources->addScriptFile('civicrm', 'templates/CRM/Contribute/Form/SoftCredit.js');
176 $resources->addSetting(array('monetaryThousandSeparator' => $config->monetaryThousandSeparator));
177
178 $this->_formType = CRM_Utils_Array::value('formType', $_GET);
179
180 // get price set id.
181 $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
182 $this->set('priceSetId', $this->_priceSetId);
183 $this->assign('priceSetId', $this->_priceSetId);
184
185 //get the pledge payment id
186 $this->_ppID = CRM_Utils_Request::retrieve('ppid', 'Positive', $this);
187
188 //get the contact id
189 $this->_contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
190
191 //get the action.
192 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
193 $this->assign('action', $this->_action);
194
195 //get the contribution id if update
196 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
197 if (!empty($this->_id)) {
198 $this->assign('contribID', $this->_id);
199 }
200
201 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
202 $this->assign('context', $this->_context);
203
204 $this->_compId = CRM_Utils_Request::retrieve('compId', 'Positive', $this);
205
206 $this->_compContext = CRM_Utils_Request::retrieve('compContext', 'String', $this);
207
208 //set the contribution mode.
209 $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
210
211 $this->assign('contributionMode', $this->_mode);
212
213 $this->_paymentProcessor = array('billing_mode' => 1);
214
215 $this->assign('showCheckNumber', TRUE);
216
217 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
218 $this->assignProcessors();
219
220 if ($this->_contactID) {
221 list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
222 $this->assign('displayName', $this->userDisplayName);
223 }
224
225 // also check for billing information
226 // get the billing location type
227 $this->assignBillingType();
228
229 $this->_fields = array();
230
231 CRM_Core_Payment_Form::setPaymentFieldsByType(CRM_Utils_Array::value('payment_type', $this->_processors), $this);
232
233 if ($this->_action & CRM_Core_Action::DELETE) {
234 return;
235 }
236
237 if (in_array('CiviPledge', $config->enableComponents) && !$this->_formType) {
238 $this->preProcessPledge();
239 }
240
241 $this->_values = array();
242
243 // current contribution id
244 if ($this->_id) {
245 $this->assignPremiumProduct($this->_id);
246 $this->buildValuesAndAssignOnline_Note_Type($this->_id, $this->_values);
247 }
248
249 // when custom data is included in this page
250 if (CRM_Utils_Array::value('hidden_custom', $_POST)) {
251 $this->applyCustomData('Contribution', CRM_Utils_Array::value('financial_type_id', $_POST), $this->_id);
252 }
253
254 $this->_lineItems = array();
255 if ($this->_id) {
256 if (!empty($this->_compId) && $this->_compContext == 'participant') {
257 $this->assign('compId', $this->_compId);
258 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_compId);
259 }
260 else {
261 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution', 1);
262 }
263 empty($lineItem) ? NULL : $this->_lineItems[] = $lineItem;
264 }
265
266 $this->assign('lineItem', empty($this->_lineItems) ? FALSE : $this->_lineItems);
267
268 // Set title
269 if ($this->_contactID) {
270 $displayName = CRM_Contact_BAO_Contact::displayName($this->_contactID);
271
272 // Check if this is default domain contact CRM-10482
273 if (CRM_Contact_BAO_Contact::checkDomainContact($this->_contactID)) {
274 $displayName .= ' (' . ts('default organization') . ')';
275 }
276
277 // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
278 CRM_Utils_System::setTitle(ts('Contribution from') . ' ' . $displayName);
279 }
280 }
281
282 function setDefaultValues() {
283 if ($this->_cdType) {
284 return CRM_Custom_Form_CustomData::setDefaultValues($this);
285 }
286
287 $defaults = $this->_values;
288
289 //set defaults for pledge payment.
290 if ($this->_ppID) {
291 $defaults['total_amount'] = CRM_Utils_Array::value('scheduled_amount', $this->_pledgeValues['pledgePayment']);
292 $defaults['honor_type_id'] = CRM_Utils_Array::value('honor_type_id', $this->_pledgeValues);
293 $defaults['honor_contact_id'] = CRM_Utils_Array::value('honor_contact_id', $this->_pledgeValues);
294 $defaults['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $this->_pledgeValues);
295 $defaults['currency'] = CRM_Utils_Array::value('currency', $this->_pledgeValues);
296 $defaults['option_type'] = 1;
297 }
298
299 $fields = array();
300 if ($this->_action & CRM_Core_Action::DELETE) {
301 return $defaults;
302 }
303
304 // set soft credit defaults
305 CRM_Contribute_Form_SoftCredit::setDefaultValues($defaults, $this);
306
307 if ($this->_mode) {
308 $config = CRM_Core_Config::singleton();
309 // set default country from config if no country set
310 if (!CRM_Utils_Array::value("billing_country_id-{$this->_bltID}", $defaults)) {
311 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
312 }
313
314 if (!CRM_Utils_Array::value("billing_state_province_id-{$this->_bltID}", $defaults)) {
315 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
316 }
317
318 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
319 $defaults = array_merge($defaults, $billingDefaults);
320
321 // now fix all state country selectors, set correct state based on country
322 CRM_Core_BAO_Address::fixAllStateSelects($this, $defaults);
323 }
324
325 if ($this->_id) {
326 $this->_contactID = $defaults['contact_id'];
327 }
328
329 // Set $newCredit variable in template to control whether link to credit card mode is included
330 CRM_Core_Payment::allowBackofficeCreditCard($this);
331
332 // fix the display of the monetary value, CRM-4038
333 if (isset($defaults['total_amount'])) {
334 $defaults['total_amount'] = CRM_Utils_Money::format($defaults['total_amount'], NULL, '%a');
335 }
336
337 if (isset($defaults['non_deductible_amount'])) {
338 $defaults['non_deductible_amount'] = CRM_Utils_Money::format($defaults['non_deductible_amount'], NULL, '%a');
339 }
340
341 if (isset($defaults['fee_amount'])) {
342 $defaults['fee_amount'] = CRM_Utils_Money::format($defaults['fee_amount'], NULL, '%a');
343 }
344
345 if (isset($defaults['net_amount'])) {
346 $defaults['net_amount'] = CRM_Utils_Money::format($defaults['net_amount'], NULL, '%a');
347 }
348
349 if ($this->_contributionType) {
350 $defaults['financial_type_id'] = $this->_contributionType;
351 }
352
353 if (CRM_Utils_Array::value('is_test', $defaults)) {
354 $this->assign('is_test', TRUE);
355 }
356
357 if (isset($defaults['honor_contact_id'])) {
358 $honorDefault = $ids = array();
359 $this->_honorID = $defaults['honor_contact_id'];
360 $honorType = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'honor_type_id');
361 $idParams = array(
362 'id' => $defaults['honor_contact_id'],
363 'contact_id' => $defaults['honor_contact_id'],
364 );
365 CRM_Contact_BAO_Contact::retrieve($idParams, $honorDefault, $ids);
366
367 $defaults['honor_prefix_id'] = CRM_Utils_Array::value('prefix_id', $honorDefault);
368 $defaults['honor_first_name'] = CRM_Utils_Array::value('first_name', $honorDefault);
369 $defaults['honor_last_name'] = CRM_Utils_Array::value('last_name', $honorDefault);
370 $defaults['honor_email'] = CRM_Utils_Array::value('email', $honorDefault['email'][1]);
371 $defaults['honor_type'] = $honorType[$defaults['honor_type_id']];
372 }
373
374 $this->assign('showOption', TRUE);
375 // for Premium section
376 if ($this->_premiumID) {
377 $this->assign('showOption', FALSE);
378 $options = isset($this->_options[$this->_productDAO->product_id]) ? $this->_options[$this->_productDAO->product_id] : "";
379 if (!$options) {
380 $this->assign('showOption', TRUE);
381 }
382 $options_key = CRM_Utils_Array::key($this->_productDAO->product_option, $options);
383 if ($options_key) {
384 $defaults['product_name'] = array($this->_productDAO->product_id, trim($options_key));
385 }
386 else {
387 $defaults['product_name'] = array($this->_productDAO->product_id);
388 }
389 if ($this->_productDAO->fulfilled_date) {
390 list($defaults['fulfilled_date']) = CRM_Utils_Date::setDateDefaults($this->_productDAO->fulfilled_date);
391 }
392 }
393
394 if (isset($this->userEmail)) {
395 $this->assign('email', $this->userEmail);
396 }
397
398 if (CRM_Utils_Array::value('is_pay_later', $defaults)) {
399 $this->assign('is_pay_later', TRUE);
400 }
401 $this->assign('contribution_status_id', CRM_Utils_Array::value('contribution_status_id', $defaults));
402
403 $dates = array('receive_date', 'receipt_date', 'cancel_date', 'thankyou_date');
404 foreach ($dates as $key) {
405 if (CRM_Utils_Array::value($key, $defaults)) {
406 list($defaults[$key],
407 $defaults[$key . '_time']
408 ) = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value($key, $defaults),
409 'activityDateTime'
410 );
411 }
412 }
413
414 if (!$this->_id && !CRM_Utils_Array::value('receive_date', $defaults)) {
415 list($defaults['receive_date'],
416 $defaults['receive_date_time']
417 ) = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
418 }
419
420 $this->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $defaults),
421 CRM_Utils_Array::value('receive_date_time', $defaults)
422 ));
423 $currency = CRM_Utils_Array::value('currency', $defaults);
424 $this->assign('currency', $currency);
425 // Hack to get currency info to the js layer. CRM-11440
426 CRM_Utils_Money::format(1);
427 $this->assign('currencySymbol', CRM_Utils_Array::value($currency, CRM_Utils_Money::$_currencySymbols));
428 $this->assign('totalAmount', CRM_Utils_Array::value('total_amount', $defaults));
429
430 //inherit campaign from pledge.
431 if ($this->_ppID && CRM_Utils_Array::value('campaign_id', $this->_pledgeValues)) {
432 $defaults['campaign_id'] = $this->_pledgeValues['campaign_id'];
433 }
434
435 $this->_defaults = $defaults;
436 return $defaults;
437 }
438
439 /**
440 * Function to build the form
441 *
442 * @return void
443 * @access public
444 */
445 public function buildQuickForm() {
446 if ($this->_cdType) {
447 CRM_Custom_Form_CustomData::buildQuickForm($this);
448 return;
449 }
450
451 // build price set form.
452 $buildPriceSet = FALSE;
453 if (empty($this->_lineItems) &&
454 ($this->_priceSetId || CRM_Utils_Array::value('price_set_id', $_POST))
455 ) {
456 $buildPriceSet = TRUE;
457 $getOnlyPriceSetElements = TRUE;
458 if (!$this->_priceSetId) {
459 $this->_priceSetId = $_POST['price_set_id'];
460 $getOnlyPriceSetElements = FALSE;
461 }
462
463 $this->set('priceSetId', $this->_priceSetId);
464 CRM_Price_BAO_PriceSet::buildPriceSet($this);
465
466 // get only price set form elements.
467 if ($getOnlyPriceSetElements) {
468 return;
469 }
470 }
471 // use to build form during form rule.
472 $this->assign('buildPriceSet', $buildPriceSet);
473
474 $showAdditionalInfo = FALSE;
475
476 $defaults = $this->_values;
477 $additionalDetailFields = array(
478 'note',
479 'thankyou_date',
480 'invoice_id',
481 'non_deductible_amount',
482 'fee_amount',
483 'net_amount',
484 );
485 foreach ($additionalDetailFields as $key) {
486 if (!empty($defaults[$key])) {
487 $defaults['hidden_AdditionalDetail'] = 1;
488 break;
489 }
490 }
491
492 $honorFields = array(
493 'honor_type_id',
494 'honor_prefix_id',
495 'honor_first_name',
496 'honor_lastname',
497 'honor_email',
498 );
499 foreach ($honorFields as $key) {
500 if (!empty($defaults[$key])) {
501 $defaults['hidden_Honoree'] = 1;
502 break;
503 }
504 }
505
506 //check for honoree pane.
507 if ($this->_ppID && CRM_Utils_Array::value('honor_contact_id', $this->_pledgeValues)) {
508 $defaults['hidden_Honoree'] = 1;
509 }
510
511 if ($this->_productDAO) {
512 if ($this->_productDAO->product_id) {
513 $defaults['hidden_Premium'] = 1;
514 }
515 }
516
517 if ($this->_noteID &&
518 isset($this->_values['note'])
519 ) {
520 $defaults['hidden_AdditionalDetail'] = 1;
521 }
522
523 $paneNames = array(
524 ts('Additional Details') => 'AdditionalDetail',
525 ts('Honoree Information') => 'Honoree'
526 );
527
528 //Add Premium pane only if Premium is exists.
529 $dao = new CRM_Contribute_DAO_Product();
530 $dao->is_active = 1;
531
532 if ($dao->find(TRUE)) {
533 $paneNames[ts('Premium Information')] = 'Premium';
534 }
535
536 $ccPane = NULL;
537 if ($this->_mode) {
538 if (CRM_Utils_Array::value('payment_type', $this->_processors) & CRM_Core_Payment::PAYMENT_TYPE_DIRECT_DEBIT
539 ) {
540 $ccPane = array(ts('Direct Debit Information') => 'DirectDebit');
541 }
542 else {
543 $ccPane = array(ts('Credit Card Information') => 'CreditCard');
544 }
545 }
546 if (is_array($ccPane)) {
547 $paneNames = array_merge($ccPane, $paneNames);
548 }
549
550 $buildRecurBlock = FALSE;
551 foreach ($paneNames as $name => $type) {
552 $urlParams = "snippet=4&formType={$type}";
553 if ($this->_mode) {
554 $urlParams .= "&mode={$this->_mode}";
555 }
556
557 $open = 'false';
558 if ($type == 'CreditCard' ||
559 $type == 'DirectDebit'
560 ) {
561 $open = 'true';
562 }
563
564 $allPanes[$name] = array(
565 'url' => CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams),
566 'open' => $open,
567 'id' => $type
568 );
569
570 // see if we need to include this paneName in the current form
571 if ($this->_formType == $type ||
572 CRM_Utils_Array::value("hidden_{$type}", $_POST) ||
573 CRM_Utils_Array::value("hidden_{$type}", $defaults)
574 ) {
575 $showAdditionalInfo = TRUE;
576 $allPanes[$name]['open'] = 'true';
577 }
578
579 if ($type == 'CreditCard') {
580 $buildRecurBlock = TRUE;
581 $this->add('hidden', 'hidden_CreditCard', 1);
582 CRM_Core_Payment_Form::buildCreditCard($this, TRUE);
583 }
584 elseif ($type == 'DirectDebit') {
585 $buildRecurBlock = TRUE;
586 $this->add('hidden', 'hidden_DirectDebit', 1);
587 CRM_Core_Payment_Form::buildDirectDebit($this, TRUE);
588 }
589 else {
590 $additionalInfoFormFunction = 'build' . $type;
591 CRM_Contribute_Form_AdditionalInfo::$additionalInfoFormFunction($this);
592 }
593 }
594 if (empty($this->_recurPaymentProcessors)) {
595 $buildRecurBlock = FALSE;
596 }
597 if ($buildRecurBlock) {
598 CRM_Contribute_Form_Contribution_Main::buildRecur($this);
599 $this->setDefaults(array('is_recur' => 0));
600 }
601 $this->assign('buildRecurBlock', $buildRecurBlock);
602 $qfKey = $this->controller->_key;
603 $this->assign('qfKey', $qfKey);
604 $this->assign('allPanes', $allPanes);
605 $this->assign('showAdditionalInfo', $showAdditionalInfo);
606
607 if ($this->_formType) {
608 $this->assign('formType', $this->_formType);
609 return;
610 }
611
612 $this->applyFilter('__ALL__', 'trim');
613
614 if ($this->_action & CRM_Core_Action::DELETE) {
615 $this->addButtons(array(
616 array(
617 'type' => 'next',
618 'name' => ts('Delete'),
619 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
620 'isDefault' => TRUE,
621 ),
622 array(
623 'type' => 'cancel',
624 'name' => ts('Cancel')
625 )
626 )
627 );
628 return;
629 }
630
631 //need to assign custom data type and subtype to the template
632 $this->assign('customDataType', 'Contribution');
633 $this->assign('customDataSubType', $this->_contributionType);
634 $this->assign('entityID', $this->_id);
635
636 if ($this->_context == 'standalone') {
637 CRM_Contact_Form_NewContact::buildQuickForm($this);
638 }
639
640 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
641
642 $financialType = $this->add('select', 'financial_type_id',
643 ts('Financial Type'),
644 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(),
645 TRUE,
646 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
647 );
648
649 if (!$this->_mode) {
650 $paymentInstrument = $this->add('select', 'payment_instrument_id',
651 ts('Paid By'),
652 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
653 FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
654 );
655 }
656
657 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), $attributes['trxn_id']);
658
659 //add receipt for offline contribution
660 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
661
662 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
663
664 $status = CRM_Contribute_PseudoConstant::contributionStatus();
665
666 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
667 $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
668 if ($this->_ppID) {
669 foreach (array(
670 'Cancelled',
671 'Failed',
672 'In Progress'
673 ) as $suppress) {
674 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
675 }
676 }
677 elseif ((!$this->_ppID && $this->_id) || !$this->_id) {
678 foreach (array(
679 'Overdue',
680 'In Progress'
681 ) as $suppress) {
682 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
683 }
684 }
685 if ($this->_id) {
686 $contributionStatus = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id, 'contribution_status_id');
687 $name = CRM_Utils_Array::value($contributionStatus, $statusName);
688 switch ($name) {
689 case 'Completed':
690 case 'Cancelled':
691 case 'Refunded':
692 unset($status[CRM_Utils_Array::key('Pending', $statusName)]);
693 unset($status[CRM_Utils_Array::key('Failed', $statusName)]);
694 break;
695 case 'Pending':
696 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
697 break;
698 case 'Failed':
699 foreach (array(
700 'Pending',
701 'Refunded',
702 'Completed',
703 'Cancelled'
704 ) as $suppress) {
705 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
706 }
707 break;
708 }
709 }
710 else {
711 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
712 }
713
714 $this->add('select', 'contribution_status_id',
715 ts('Contribution Status'),
716 $status,
717 FALSE
718 );
719
720 // add various dates
721 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
722
723 if ($this->_online) {
724 $this->assign('hideCalender', TRUE);
725 }
726 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
727
728 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
729 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
730
731 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
732
733 $recurJs = NULL;
734 if ($buildRecurBlock) {
735 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
736 }
737 $element = $this->add('select',
738 'payment_processor_id',
739 ts('Payment Processor'),
740 $this->_processors,
741 NULL,
742 $recurJs
743 );
744
745 if ($this->_online) {
746 $element->freeze();
747 }
748 $totalAmount = NULL;
749 if (empty($this->_lineItems)) {
750 $buildPriceSet = FALSE;
751 $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute');
752 if (!empty($priceSets) && !$this->_ppID) {
753 $buildPriceSet = TRUE;
754 }
755
756 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
757 // and if we already have line items for that participant. CRM-5095
758 if ($buildPriceSet && $this->_id) {
759 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
760 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
761 $this->_id,
762 'id',
763 'contribution_id'
764 );
765 if ($pledgePaymentId) {
766 $buildPriceSet = FALSE;
767 }
768 if ($participantID = CRM_Utils_Array::value('participant', $componentDetails)) {
769 $participantLI = CRM_Price_BAO_LineItem::getLineItems($participantID);
770 if (!CRM_Utils_System::isNull($participantLI)) {
771 $buildPriceSet = FALSE;
772 }
773 }
774 }
775
776 $hasPriceSets = FALSE;
777 if ($buildPriceSet) {
778 $hasPriceSets = TRUE;
779 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
780 array(
781 '' => ts('Choose price set')
782 ) + $priceSets,
783 NULL, array('onchange' => "buildAmount( this.value );")
784 );
785 if ($this->_online && !($this->_action & CRM_Core_Action::UPDATE)) {
786 $element->freeze();
787 }
788 }
789 $this->assign('hasPriceSets', $hasPriceSets);
790 $currencyFreeze = FALSE;
791 if (!($this->_action & CRM_Core_Action::UPDATE)) {
792 if ($this->_online || $this->_ppID) {
793 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
794 'READONLY' => TRUE,
795 'style' => "background-color:#EBECE4"
796 ));
797 $optionTypes = array(
798 '1' => ts('Adjust Pledge Payment Schedule?'),
799 '2' => ts('Adjust Total Pledge Amount?'),
800 );
801 $this->addRadio('option_type',
802 NULL,
803 $optionTypes,
804 array(), '<br/>'
805 );
806
807 $currencyFreeze = TRUE;
808 }
809 }
810
811 $totalAmount = $this->addMoney('total_amount',
812 ts('Total Amount'),
813 ($hasPriceSets) ? FALSE : TRUE,
814 $attributes['total_amount'],
815 TRUE, 'currency', NULL, $currencyFreeze
816 );
817 }
818
819 $this->add('text', 'source', ts('Source'), CRM_Utils_Array::value('source', $attributes));
820
821 //CRM-7362 --add campaigns.
822 CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
823
824 CRM_Contribute_Form_SoftCredit::buildQuickForm($this);
825
826 $js = NULL;
827 if (!$this->_mode) {
828 $js = array('onclick' => "return verify( );");
829 }
830
831 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
832 'mailing_backend'
833 );
834 $this->assign('outBound_option', $mailingInfo['outBound_option']);
835
836 $this->addButtons(array(
837 array(
838 'type' => 'upload',
839 'name' => ts('Save'),
840 'js' => $js,
841 'isDefault' => TRUE
842 ),
843 array(
844 'type' => 'upload',
845 'name' => ts('Save and New'),
846 'js' => $js,
847 'subName' => 'new'
848 ),
849 array(
850 'type' => 'cancel',
851 'name' => ts('Cancel')
852 ),
853 )
854 );
855
856 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
857 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
858 if ($this->_id && $this->_values['contribution_status_id'] == array_search('Cancelled', $statusName)) {
859 if ($totalAmount) {
860 $totalAmount->freeze();
861 }
862 $checkNumber->freeze();
863 $paymentInstrument->freeze();
864 $trxnId->freeze();
865 $financialType->freeze();
866 }
867
868 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
869
870 if ($this->_action & CRM_Core_Action::VIEW) {
871 $this->freeze();
872 }
873 }
874
875 /**
876 * global form rule
877 *
878 * @param array $fields the input form values
879 * @param array $files the uploaded files if any
880 * @param array $options additional user data
881 *
882 * @return true if no errors, else array of errors
883 * @access public
884 * @static
885 */
886 static function formRule($fields, $files, $self) {
887 $errors = array();
888
889 //check if contact is selected in standalone mode
890 if (isset($fields['contact_select_id'][1]) && !$fields['contact_select_id'][1]) {
891 $errors['contact[1]'] = ts('Please select a contact or create new contact');
892 }
893
894 if (isset($fields['honor_type_id'])) {
895 if (!((CRM_Utils_Array::value('honor_first_name', $fields) &&
896 CRM_Utils_Array::value('honor_last_name', $fields)
897 ) ||
898 CRM_Utils_Array::value('honor_email', $fields)
899 )
900 ) {
901 $errors['honor_first_name'] = ts('Honor First Name and Last Name OR an email should be set.');
902 }
903 }
904
905 //check for Credit Card Contribution.
906 if ($self->_mode) {
907 if (empty($fields['payment_processor_id'])) {
908 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
909 }
910 }
911
912 // do the amount validations.
913 if (!CRM_Utils_Array::value('total_amount', $fields) && empty($self->_lineItems)) {
914 if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) {
915 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $fields, $errors);
916 }
917 }
918
919 $softErrors = CRM_Contribute_Form_SoftCredit::formRule($fields);
920
921 if (CRM_Utils_Array::value('total_amount', $fields) && (CRM_Utils_Array::value('net_amount', $fields) || CRM_Utils_Array::value('fee_amount', $fields))) {
922 $sum = CRM_Utils_Rule::cleanMoney($fields['net_amount']) + CRM_Utils_Rule::cleanMoney($fields['fee_amount']);
923 if (CRM_Utils_Rule::cleanMoney($fields['total_amount']) != $sum) {
924 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
925 }
926 }
927 //form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
928 if ($self->_id && $self->_values['contribution_status_id'] != $fields['contribution_status_id']) {
929 CRM_Contribute_BAO_Contribution::checkStatusValidation($self->_values, $fields, $errors);
930 }
931
932 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
933 if (CRM_Utils_Array::value('fee_amount', $fields)) {
934 $financialAccount = array();
935 CRM_Core_PseudoConstant::populate($financialAccount,
936 'CRM_Financial_DAO_EntityFinancialAccount',
937 $all = TRUE,
938 $retrieve = 'financial_account_id',
939 $filter = NULL,
940 " account_relationship = 5 AND entity_id = {$fields['financial_type_id']} ");
941 if (!current($financialAccount)) {
942 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for this Financial Type");
943 }
944 }
945
946 $errors = array_merge($errors, $softErrors);
947 return $errors;
948 }
949
950 /**
951 * Function to process the form
952 *
953 * @access public
954 *
955 * @return void
956 */
957 public function postProcess() {
958 $session = CRM_Core_Session::singleton();
959 if ($this->_action & CRM_Core_Action::DELETE) {
960 CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
961 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
962 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
963 ));
964 return;
965 }
966
967 // get the submitted form values.
968 $submittedValues = $this->controller->exportValues($this->_name);
969 if (CRM_Utils_Array::value('price_set_id', $submittedValues) && $this->_action & CRM_Core_Action::UPDATE) {
970 $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
971 $lineID = key($line);
972 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
973 $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
974 if ($quickConfig) {
975 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
976 }
977 }
978
979 // process price set and get total amount and line items.
980 $lineItem = array();
981 $priceSetId = $pId = NULL;
982 $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
983 if (empty($priceSetId) && !$this->_id) {
984 $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
985 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
986 $fieldID = key($this->_priceSet['fields']);
987 $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
988 $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
989 $submittedValues['price_' . $fieldID] = 1;
990 }
991
992 if ($priceSetId) {
993 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
994 $submittedValues, $lineItem[$priceSetId]);
995
996 $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
997 }
998 if ($this->_id) {
999 //CRM-10964
1000 $pId = ($this->_compId && $this->_context == 'participant') ? $this->_compId : CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
1001 }
1002 if (!$priceSetId && CRM_Utils_Array::value('total_amount', $submittedValues) && $this->_id) {
1003 // 10117 update th line items for participants
1004 if ($pId) {
1005 $entityTable = 'participant';
1006 $entityID = $pId;
1007 $participantParams = array(
1008 'fee_amount' => $submittedValues['total_amount'],
1009 'id' => $entityID
1010 );
1011 CRM_Event_BAO_Participant::add($participantParams);
1012 if (empty($this->_lineItems)) {
1013 $this->_lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
1014 }
1015 }
1016 else {
1017 $entityTable = 'contribution';
1018 $entityID = $this->_id;
1019 }
1020
1021 $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable);
1022 foreach (array_keys($lineItems) as $id) {
1023 $lineItems[$id]['id'] = $id;
1024 }
1025 $itemId = key($lineItems);
1026 $fieldType = NULL;
1027 if ($itemId && CRM_Utils_Array::value('price_field_id', $lineItems[$itemId])) {
1028 $fieldType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'html_type');
1029 }
1030 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
1031 // 10117 update th line items for participants
1032 if (!empty($lineItems[$itemId]['price_field_id'])) {
1033 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1034 $lineItem[$this->_priceSetId] = $lineItems;
1035 }
1036 }
1037 $isQuickConfig = 0;
1038 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1039 $isQuickConfig = 1;
1040 }
1041 //CRM-11529 for quick config backoffice transactions
1042 //when financial_type_id is passed in form, update the
1043 //lineitems with the financial type selected in form
1044 if ($isQuickConfig && CRM_Utils_Array::value('financial_type_id', $submittedValues)
1045 && CRM_Utils_Array::value($this->_priceSetId, $lineItem)
1046 ) {
1047 foreach ($lineItem[$this->_priceSetId] as &$values) {
1048 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1049 }
1050 }
1051
1052 if (!isset($submittedValues['total_amount'])) {
1053 $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
1054 }
1055 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1056
1057 if (CRM_Utils_Array::value('pcp_made_through_id', $submittedValues)) {
1058 $pcp = array();
1059 $fields = array(
1060 'pcp_made_through_id',
1061 'pcp_display_in_roll',
1062 'pcp_roll_nickname',
1063 'pcp_personal_note',
1064 );
1065 foreach ($fields as $f) {
1066 $pcp[$f] = CRM_Utils_Array::value($f, $submittedValues);
1067 }
1068 }
1069 else {
1070 //build soft credit params
1071 if (!empty($submittedValues['soft_credit_contact_select_id'])) {
1072 $softParams = $softIDs =array();
1073 foreach ($submittedValues['soft_credit_contact_select_id'] as $key => $val) {
1074 if ($val && $submittedValues['soft_credit_amount'][$key]) {
1075 $softParams[$key]['contact_id'] = $val;
1076 $softParams[$key]['amount'] = CRM_Utils_Rule::cleanMoney($submittedValues['soft_credit_amount'][$key]);
1077 if (!empty($submittedValues['soft_credit_id'][$key])) {
1078 $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
1079 }
1080 }
1081 }
1082 }
1083 }
1084
1085 // set the contact, when contact is selected
1086 if (CRM_Utils_Array::value('contact_select_id', $submittedValues)) {
1087 $this->_contactID = $submittedValues['contact_select_id'][1];
1088 }
1089
1090 $config = CRM_Core_Config::singleton();
1091
1092 //Credit Card Contribution.
1093 if ($this->_mode) {
1094 $this->processCreditCard($submittedValues, $config, $session, $pId, $lineItem);
1095 }
1096 else {
1097 //Offline Contribution.
1098 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1099
1100 // get the required field value only.
1101 $formValues = $submittedValues;
1102 $params = $ids = array();
1103
1104 $params['contact_id'] = $this->_contactID;
1105
1106 $params['currency'] = $this->getCurrency($submittedValues);
1107
1108 $fields = array(
1109 'financial_type_id',
1110 'contribution_status_id',
1111 'payment_instrument_id',
1112 'cancel_reason',
1113 'source',
1114 'check_number',
1115 );
1116 foreach ($fields as $f) {
1117 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1118 }
1119
1120 if (!empty($pcp)) {
1121 $params['pcp'] = $pcp;
1122 }
1123 if (!empty($softParams)) {
1124 $params['soft_credit'] = $softParams;
1125 $params['soft_credit_ids'] = $softIDs;
1126 }
1127
1128 //if priceset is used, no need to cleanup money
1129 //CRM-5740
1130 if ($priceSetId) {
1131 $params['skipCleanMoney'] = 1;
1132 }
1133
1134 $dates = array(
1135 'receive_date',
1136 'receipt_date',
1137 'cancel_date',
1138 );
1139
1140 foreach ($dates as $d) {
1141 $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1142 }
1143
1144 if (CRM_Utils_Array::value('is_email_receipt', $formValues)) {
1145 $params['receipt_date'] = date("Y-m-d");
1146 }
1147
1148 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name')
1149 || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')
1150 ) {
1151 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
1152 $params['cancel_date'] = date('Y-m-d');
1153 }
1154 }
1155 else {
1156 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1157 }
1158
1159 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1160 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
1161 $params['is_pay_later'] = 1;
1162 }
1163
1164 $ids['contribution'] = $params['id'] = $this->_id;
1165
1166 //Add Additional common information to formatted params
1167 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
1168 if ($pId) {
1169 $params['contribution_mode'] = 'participant';
1170 $params['participant_id'] = $pId;
1171 $params['skipLineItem'] = 1;
1172 }
1173 $params['line_item'] = $lineItem;
1174 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
1175 //create contribution.
1176 if ($isQuickConfig) {
1177 $params['is_quick_config'] = 1;
1178 }
1179
1180 // CRM-11956
1181 // if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep it.
1182 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
1183 $params['non_deductible_amount'] = $params['non_deductible_amount'];
1184 }
1185 // if non_deductible_amount does NOT exist - then calculate it depending on:
1186 // $ContributionType->is_deductible and whether there is a product (premium).
1187 else {
1188 $contributionType = new CRM_Financial_DAO_FinancialType();
1189 $contributionType->id = $params['financial_type_id'];
1190 if (!$contributionType->find(TRUE)) {
1191 CRM_Core_Error::fatal('Could not find a system table');
1192 }
1193 if ($contributionType->is_deductible) {
1194
1195 if (isset($formValues['product_name'][0])) {
1196 $selectProduct = $formValues['product_name'][0];
1197 }
1198 // if there is a product - compare the value to the contribution amount
1199 if (isset($selectProduct)) {
1200 $productDAO = new CRM_Contribute_DAO_Product();
1201 $productDAO->id = $selectProduct;
1202 $productDAO->find(TRUE);
1203 // product value exceeds contribution amount
1204 if ($params['total_amount'] < $productDAO->price) {
1205 $params['non_deductible_amount'] = $params['total_amount'];
1206 }
1207 // product value does NOT exceed contribution amount
1208 else {
1209 $params['non_deductible_amount'] = $productDAO->price;
1210 }
1211 }
1212 // contribution is deductible - but there is no product
1213 else {
1214 $params['non_deductible_amount'] = '0.00';
1215 }
1216 }
1217 // contribution is NOT deductible
1218 else {
1219 $params['non_deductible_amount'] = $params['total_amount'];
1220 }
1221 }
1222
1223 $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
1224
1225 // process associated membership / participant, CRM-4395
1226 $relatedComponentStatusMsg = NULL;
1227 if ($contribution->id && $this->_action & CRM_Core_Action::UPDATE) {
1228 $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id,
1229 $contribution->contribution_status_id,
1230 CRM_Utils_Array::value('contribution_status_id',
1231 $this->_values
1232 )
1233 );
1234 }
1235
1236 //process note
1237 if ($contribution->id && isset($formValues['note'])) {
1238 CRM_Contribute_Form_AdditionalInfo::processNote($formValues, $this->_contactID, $contribution->id, $this->_noteID);
1239 }
1240
1241 //process premium
1242 if ($contribution->id && isset($formValues['product_name'][0])) {
1243 CRM_Contribute_Form_AdditionalInfo::processPremium($formValues, $contribution->id,
1244 $this->_premiumID, $this->_options
1245 );
1246 }
1247
1248 //send receipt mail.
1249 if ($contribution->id && CRM_Utils_Array::value('is_email_receipt', $formValues)) {
1250 $formValues['contact_id'] = $this->_contactID;
1251 $formValues['contribution_id'] = $contribution->id;
1252
1253 // to get 'from email id' for send receipt
1254 $this->fromEmailId = $formValues['from_email_address'];
1255 $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues);
1256 }
1257
1258 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1259 $contribution->id,
1260 'id',
1261 'contribution_id'
1262 );
1263
1264 //update pledge payment status.
1265 if ((($this->_ppID && $contribution->id) && $this->_action & CRM_Core_Action::ADD) ||
1266 (($pledgePaymentId) && $this->_action & CRM_Core_Action::UPDATE)
1267 ) {
1268
1269 if ($this->_ppID) {
1270 //store contribution id in payment record.
1271 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
1272 }
1273 else {
1274 $this->_ppID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1275 $contribution->id,
1276 'id',
1277 'contribution_id'
1278 );
1279 $this->_pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1280 $contribution->id,
1281 'pledge_id',
1282 'contribution_id'
1283 );
1284 }
1285
1286 $adjustTotalAmount = FALSE;
1287 if (CRM_Utils_Array::value('option_type', $formValues) == 2) {
1288 $adjustTotalAmount = TRUE;
1289 }
1290
1291 $updatePledgePaymentStatus = FALSE;
1292 //do only if either the status or the amount has changed
1293 if ($this->_action & CRM_Core_Action::ADD) {
1294 $updatePledgePaymentStatus = TRUE;
1295 }
1296 elseif ($this->_action & CRM_Core_Action::UPDATE && (($this->_defaults['contribution_status_id'] != $formValues['contribution_status_id']) ||
1297 ($this->_defaults['total_amount'] != $formValues['total_amount']))
1298 ) {
1299 $updatePledgePaymentStatus = TRUE;
1300 }
1301
1302 if ($updatePledgePaymentStatus) {
1303 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID,
1304 array($this->_ppID),
1305 $contribution->contribution_status_id,
1306 NULL,
1307 $contribution->total_amount,
1308 $adjustTotalAmount
1309 );
1310 }
1311 }
1312
1313 $statusMsg = ts('The contribution record has been saved.');
1314 if (CRM_Utils_Array::value('is_email_receipt', $formValues) && $sendReceipt) {
1315 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1316 }
1317
1318 if ($relatedComponentStatusMsg) {
1319 $statusMsg .= ' ' . $relatedComponentStatusMsg;
1320 }
1321
1322 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
1323 //Offline Contribution ends.
1324 }
1325 $buttonName = $this->controller->getButtonName();
1326 if ($this->_context == 'standalone') {
1327 if ($buttonName == $this->getButtonName('upload', 'new')) {
1328 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add',
1329 'reset=1&action=add&context=standalone'
1330 ));
1331 }
1332 else {
1333 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1334 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1335 ));
1336 }
1337 }
1338 elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) {
1339 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1340 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1341 ));
1342 }
1343 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1344 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1345 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1346 ));
1347 }
1348 }
1349
1350 public function processCreditCard($submittedValues, $config, $session, $pId, $lineItem) {
1351 $unsetParams = array(
1352 'trxn_id',
1353 'payment_instrument_id',
1354 'contribution_status_id',
1355 'cancel_date',
1356 'cancel_reason',
1357 );
1358 foreach ($unsetParams as $key) {
1359 if (isset($submittedValues[$key])) {
1360 unset($submittedValues[$key]);
1361 }
1362 }
1363
1364 // CRM-12680 set $_lineItem if its not set
1365 if (empty($this->_lineItem) && !empty($lineItem)) {
1366 $this->_lineItem = $lineItem;
1367 }
1368
1369 //Get the rquire fields value only.
1370 $params = $this->_params = $submittedValues;
1371
1372 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
1373 $this->_mode
1374 );
1375
1376 //get the payment processor id as per mode.
1377 $this->_params['payment_processor'] = $params['payment_processor_id'] =
1378 $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
1379
1380 $now = date('YmdHis');
1381 $fields = array();
1382
1383 // we need to retrieve email address
1384 if ($this->_context == 'standalone' && CRM_Utils_Array::value('is_email_receipt', $submittedValues)) {
1385 list($this->userDisplayName,
1386 $this->userEmail
1387 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
1388 $this->assign('displayName', $this->userDisplayName);
1389 }
1390
1391 //set email for primary location.
1392 $fields['email-Primary'] = 1;
1393 $params['email-Primary'] = $this->userEmail;
1394
1395 // now set the values for the billing location.
1396 foreach ($this->_fields as $name => $dontCare) {
1397 $fields[$name] = 1;
1398 }
1399
1400 // also add location name to the array
1401 $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);
1402 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1403 $fields["address_name-{$this->_bltID}"] = 1;
1404
1405 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
1406 $this->_contactID,
1407 'contact_type'
1408 );
1409
1410 $nameFields = array('first_name', 'middle_name', 'last_name');
1411 foreach ($nameFields as $name) {
1412 $fields[$name] = 1;
1413 if (array_key_exists("billing_$name", $params)) {
1414 $params[$name] = $params["billing_{$name}"];
1415 $params['preserveDBName'] = TRUE;
1416 }
1417 }
1418
1419 if (CRM_Utils_Array::value('source', $params)) {
1420 unset($params['source']);
1421 }
1422 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields,
1423 $this->_contactID,
1424 NULL, NULL,
1425 $ctype
1426 );
1427
1428 // add all the additioanl payment params we need
1429 $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}"]);
1430 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
1431
1432 if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD) {
1433 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
1434 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
1435 }
1436 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
1437 $this->_params['amount'] = $this->_params['total_amount'];
1438 $this->_params['amount_level'] = 0;
1439 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
1440 $this->_params,
1441 $config->defaultCurrency
1442 );
1443 $this->_params['payment_action'] = 'Sale';
1444 if (CRM_Utils_Array::value('receive_date', $this->_params)) {
1445 $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']);
1446 }
1447
1448 if (CRM_Utils_Array::value('soft_credit_to', $params)) {
1449 $this->_params['soft_credit_to'] = $params['soft_credit_to'];
1450 $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id'];
1451 }
1452
1453 $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
1454 $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
1455 $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
1456
1457 //Add common data to formatted params
1458 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
1459
1460 if (empty($this->_params['invoice_id'])) {
1461 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1462 }
1463 else {
1464 $this->_params['invoiceID'] = $this->_params['invoice_id'];
1465 }
1466
1467 // at this point we've created a contact and stored its address etc
1468 // all the payment processors expect the name and address to be in the
1469 // so we copy stuff over to first_name etc.
1470 $paymentParams = $this->_params;
1471 $paymentParams['contactID'] = $this->_contactID;
1472 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
1473
1474 $contributionType = new CRM_Financial_DAO_FinancialType();
1475 $contributionType->id = $params['financial_type_id'];
1476 if (!$contributionType->find(TRUE)) {
1477 CRM_Core_Error::fatal('Could not find a system table');
1478 }
1479
1480 // add some financial type details to the params list
1481 // if folks need to use it
1482 $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
1483 $paymentParams['contributionPageID'] = NULL;
1484 if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
1485 $paymentParams['email'] = $this->userEmail;
1486 $paymentParams['is_email_receipt'] = 1;
1487 }
1488 else {
1489 $paymentParams['is_email_receipt'] = 0;
1490 $this->_params['is_email_receipt'] = 0;
1491 }
1492 if (CRM_Utils_Array::value('receive_date', $this->_params)) {
1493 $paymentParams['receive_date'] = $this->_params['receive_date'];
1494 }
1495 if (CRM_Utils_Array::value('receive_date', $this->_params)) {
1496 $paymentParams['receive_date'] = $this->_params['receive_date'];
1497 }
1498
1499 $result = NULL;
1500
1501 // For recurring contribution, create Contribution Record first.
1502 // Contribution ID, Recurring ID and Contact ID needed
1503 // When we get a callback from the payment processor, CRM-7115
1504 if (CRM_Utils_Array::value('is_recur', $paymentParams)) {
1505 $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this,
1506 $this->_params,
1507 $result,
1508 $this->_contactID,
1509 $contributionType,
1510 FALSE,
1511 TRUE,
1512 FALSE
1513 );
1514 $paymentParams['contributionID'] = $contribution->id;
1515 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
1516 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1517 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
1518 }
1519
1520 if ($paymentParams['amount'] > 0.0) {
1521 // force a reget of the payment processor in case the form changed it, CRM-7179
1522 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE);
1523 $result = $payment->doDirectPayment($paymentParams);
1524 }
1525
1526 if (is_a($result, 'CRM_Core_Error')) {
1527 //make sure to cleanup db for recurring case.
1528 if (CRM_Utils_Array::value('contributionID', $paymentParams)) {
1529 CRM_Core_Error::debug_log_message(CRM_Core_Error::getMessages($result) . "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}");
1530 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
1531 }
1532 if (CRM_Utils_Array::value('contributionRecurID', $paymentParams)) {
1533 CRM_Core_Error::debug_log_message(CRM_Core_Error::getMessages($result) . "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}");
1534 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
1535 }
1536
1537 //set the contribution mode.
1538 $urlParams = "action=add&cid={$this->_contactID}";
1539 if ($this->_mode) {
1540 $urlParams .= "&mode={$this->_mode}";
1541 }
1542 if (!empty($this->_ppID)) {
1543 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1544 }
1545 CRM_Core_Error::displaySessionError($result);
1546 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams));
1547 }
1548
1549 if ($result) {
1550 $this->_params = array_merge($this->_params, $result);
1551 }
1552
1553 $this->_params['receive_date'] = $now;
1554
1555 if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
1556 $this->_params['receipt_date'] = $now;
1557 }
1558 else {
1559 $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'],
1560 $params['receipt_date_time'], TRUE
1561 );
1562 }
1563
1564 $this->set('params', $this->_params);
1565 $this->assign('trxn_id', $result['trxn_id']);
1566 $this->assign('receive_date', $this->_params['receive_date']);
1567
1568 // result has all the stuff we need
1569 // lets archive it to a financial transaction
1570 if ($contributionType->is_deductible) {
1571 $this->assign('is_deductible', TRUE);
1572 $this->set('is_deductible', TRUE);
1573 }
1574
1575 // set source if not set
1576 if (empty($this->_params['source'])) {
1577 $userID = $session->get('userID');
1578 $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1579 'sort_name'
1580 );
1581 $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1582 }
1583
1584 // build custom data getFields array
1585 $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE,
1586 CRM_Utils_Array::value('financial_type_id', $params)
1587 );
1588 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType,
1589 CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE)
1590 );
1591 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
1592 $customFields,
1593 $this->_id,
1594 'Contribution'
1595 );
1596
1597
1598 if (!CRM_Utils_Array::value('is_recur', $paymentParams)) {
1599 $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this,
1600 $this->_params,
1601 $result,
1602 $this->_contactID,
1603 $contributionType,
1604 FALSE, FALSE, FALSE
1605 );
1606 }
1607
1608 //send receipt mail.
1609 if ($contribution->id &&
1610 CRM_Utils_Array::value('is_email_receipt', $this->_params)
1611 ) {
1612 $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
1613 $this->_params['contact_id'] = $this->_contactID;
1614 $this->_params['contribution_id'] = $contribution->id;
1615 $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE);
1616 }
1617
1618 //process the note
1619 if ($contribution->id && isset($params['note'])) {
1620 CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, NULL);
1621 }
1622 //process premium
1623 if ($contribution->id && isset($params['product_name'][0])) {
1624 CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, NULL, $this->_options);
1625 }
1626
1627 //update pledge payment status.
1628 if ($this->_ppID && $contribution->id) {
1629 //store contribution id in payment record.
1630 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
1631
1632 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID,
1633 array($this->_ppID),
1634 $contribution->contribution_status_id,
1635 NULL,
1636 $contribution->total_amount
1637 );
1638 }
1639
1640 if ($contribution->id) {
1641 $statusMsg = ts('The contribution record has been processed.');
1642 if (CRM_Utils_Array::value('is_email_receipt', $this->_params) && $sendReceipt) {
1643 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1644 }
1645 CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
1646 }
1647 }
1648 }
1649