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