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