Merge pull request #2288 from eileenmcnaughton/CRM-14043
[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) {
d37ade2e 682 foreach (array(
683 'Overdue',
684 'In Progress'
685 ) as $suppress) {
6a488035
TO
686 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
687 }
688 }
689 if ($this->_id) {
690 $contributionStatus = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id, 'contribution_status_id');
691 $name = CRM_Utils_Array::value($contributionStatus, $statusName);
d37ade2e 692 switch ($name) {
6a488035
TO
693 case 'Completed':
694 case 'Cancelled':
695 case 'Refunded':
696 unset($status[CRM_Utils_Array::key('Pending', $statusName)]);
697 unset($status[CRM_Utils_Array::key('Failed', $statusName)]);
698 break;
699 case 'Pending':
700 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
701 break;
702 case 'Failed':
d37ade2e 703 foreach (array(
704 'Pending',
705 'Refunded',
706 'Completed',
707 'Cancelled'
708 ) as $suppress) {
6a488035
TO
709 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
710 }
711 break;
712 }
d37ade2e 713 }
714 else {
6a488035
TO
715 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
716 }
717
718 $this->add('select', 'contribution_status_id',
719 ts('Contribution Status'),
720 $status,
721 FALSE
722 );
723
724 // add various dates
725 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
726
727 if ($this->_online) {
728 $this->assign('hideCalender', TRUE);
729 }
730 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
731
732 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
733 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
734
735 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
736
737 $recurJs = NULL;
738 if ($buildRecurBlock) {
739 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
740 }
741 $element = $this->add('select',
742 'payment_processor_id',
743 ts('Payment Processor'),
744 $this->_processors,
745 NULL,
746 $recurJs
747 );
748
749 if ($this->_online) {
750 $element->freeze();
751 }
752 $totalAmount = NULL;
753 if (empty($this->_lineItems)) {
754 $buildPriceSet = FALSE;
9da8dc8c 755 $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute');
6a488035
TO
756 if (!empty($priceSets) && !$this->_ppID) {
757 $buildPriceSet = TRUE;
758 }
759
760 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
761 // and if we already have line items for that participant. CRM-5095
762 if ($buildPriceSet && $this->_id) {
763 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
764 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
765 $this->_id,
766 'id',
767 'contribution_id'
768 );
769 if ($pledgePaymentId) {
770 $buildPriceSet = FALSE;
771 }
772 if ($participantID = CRM_Utils_Array::value('participant', $componentDetails)) {
773 $participantLI = CRM_Price_BAO_LineItem::getLineItems($participantID);
774 if (!CRM_Utils_System::isNull($participantLI)) {
775 $buildPriceSet = FALSE;
776 }
777 }
778 }
779
780 $hasPriceSets = FALSE;
781 if ($buildPriceSet) {
782 $hasPriceSets = TRUE;
783 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
784 array(
785 '' => ts('Choose price set')
786 ) + $priceSets,
787 NULL, array('onchange' => "buildAmount( this.value );")
5a230af7 788 );
6a488035
TO
789 if ($this->_online && !($this->_action & CRM_Core_Action::UPDATE)) {
790 $element->freeze();
791 }
792 }
793 $this->assign('hasPriceSets', $hasPriceSets);
794 $currencyFreeze = FALSE;
795 if (!($this->_action & CRM_Core_Action::UPDATE)) {
d37ade2e 796 if ($this->_online || $this->_ppID) {
797 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
798 'READONLY' => TRUE,
799 'style' => "background-color:#EBECE4"
800 ));
801 $optionTypes = array(
802 '1' => ts('Adjust Pledge Payment Schedule?'),
803 '2' => ts('Adjust Total Pledge Amount?'),
804 );
805 $this->addRadio('option_type',
806 NULL,
807 $optionTypes,
808 array(), '<br/>'
809 );
810
811 $currencyFreeze = TRUE;
812 }
6a488035
TO
813 }
814
815 $totalAmount = $this->addMoney('total_amount',
816 ts('Total Amount'),
817 ($hasPriceSets) ? FALSE : TRUE,
818 $attributes['total_amount'],
819 TRUE, 'currency', NULL, $currencyFreeze
820 );
821 }
822
823 $this->add('text', 'source', ts('Source'), CRM_Utils_Array::value('source', $attributes));
824
825 //CRM-7362 --add campaigns.
826 CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
827
0baed70b 828 CRM_Contribute_Form_SoftCredit::buildQuickForm($this);
0baed70b 829
6a488035
TO
830 $js = NULL;
831 if (!$this->_mode) {
832 $js = array('onclick' => "return verify( );");
833 }
834
835 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
836 'mailing_backend'
837 );
838 $this->assign('outBound_option', $mailingInfo['outBound_option']);
839
840 $this->addButtons(array(
841 array(
842 'type' => 'upload',
843 'name' => ts('Save'),
844 'js' => $js,
845 'isDefault' => TRUE
846 ),
847 array(
848 'type' => 'upload',
849 'name' => ts('Save and New'),
850 'js' => $js,
851 'subName' => 'new'
852 ),
853 array(
854 'type' => 'cancel',
855 'name' => ts('Cancel')
856 ),
857 )
858 );
859
860 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
861 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
862 if ($this->_id && $this->_values['contribution_status_id'] == array_search('Cancelled', $statusName)) {
5a230af7 863 if ($totalAmount) {
6a488035
TO
864 $totalAmount->freeze();
865 }
866 $checkNumber->freeze();
867 $paymentInstrument->freeze();
868 $trxnId->freeze();
869 $financialType->freeze();
870 }
871
872 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
873
874 if ($this->_action & CRM_Core_Action::VIEW) {
875 $this->freeze();
876 }
877 }
878
879 /**
880 * global form rule
881 *
882 * @param array $fields the input form values
883 * @param array $files the uploaded files if any
884 * @param array $options additional user data
885 *
886 * @return true if no errors, else array of errors
887 * @access public
888 * @static
889 */
890 static function formRule($fields, $files, $self) {
891 $errors = array();
892
893 //check if contact is selected in standalone mode
894 if (isset($fields['contact_select_id'][1]) && !$fields['contact_select_id'][1]) {
895 $errors['contact[1]'] = ts('Please select a contact or create new contact');
896 }
897
898 if (isset($fields['honor_type_id'])) {
899 if (!((CRM_Utils_Array::value('honor_first_name', $fields) &&
900 CRM_Utils_Array::value('honor_last_name', $fields)
901 ) ||
902 CRM_Utils_Array::value('honor_email', $fields)
903 )
904 ) {
905 $errors['honor_first_name'] = ts('Honor First Name and Last Name OR an email should be set.');
906 }
907 }
908
909 //check for Credit Card Contribution.
910 if ($self->_mode) {
911 if (empty($fields['payment_processor_id'])) {
912 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
913 }
914 }
915
916 // do the amount validations.
917 if (!CRM_Utils_Array::value('total_amount', $fields) && empty($self->_lineItems)) {
918 if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) {
9da8dc8c 919 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $fields, $errors);
6a488035
TO
920 }
921 }
922
b326919b 923 $softErrors = CRM_Contribute_Form_SoftCredit::formRule($fields, $errors, $self);
d37ade2e 924
925 if (CRM_Utils_Array::value('total_amount', $fields) && (CRM_Utils_Array::value('net_amount', $fields) || CRM_Utils_Array::value('fee_amount', $fields))) {
6a488035
TO
926 $sum = CRM_Utils_Rule::cleanMoney($fields['net_amount']) + CRM_Utils_Rule::cleanMoney($fields['fee_amount']);
927 if (CRM_Utils_Rule::cleanMoney($fields['total_amount']) != $sum) {
928 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
929 }
930 }
931 //form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
932 if ($self->_id && $self->_values['contribution_status_id'] != $fields['contribution_status_id']) {
933 CRM_Contribute_BAO_Contribution::checkStatusValidation($self->_values, $fields, $errors);
934 }
935
936 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
3b67ab13
PN
937 if (CRM_Utils_Array::value('fee_amount', $fields)
938 && $financialType = CRM_Contribute_BAO_Contribution::validateFinancialType($fields['financial_type_id'])) {
939 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
6a488035 940 }
7272e4fa
DG
941
942 // $trxn_id must be unique CRM-13919
943 if (!empty($fields['trxn_id'])) {
944 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
945 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
946 if ($self->_id) {
947 $queryParams[2] = array((int)$self->_id, 'Integer');
948 $query .= ' and id !=%2';
949 }
950 $tCnt = CRM_Core_DAO::singleValueQuery($query, $queryParams);
951 if ($tCnt) {
952 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
953 }
954 }
d37ade2e 955
ac0c89ed 956 $errors = array_merge($errors, $softErrors);
6a488035
TO
957 return $errors;
958 }
959
960 /**
961 * Function to process the form
962 *
963 * @access public
964 *
965 * @return void
966 */
967 public function postProcess() {
968 $session = CRM_Core_Session::singleton();
969 if ($this->_action & CRM_Core_Action::DELETE) {
970 CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
971 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
972 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
973 ));
974 return;
975 }
976
977 // get the submitted form values.
978 $submittedValues = $this->controller->exportValues($this->_name);
d37ade2e 979 if (CRM_Utils_Array::value('price_set_id', $submittedValues) && $this->_action & CRM_Core_Action::UPDATE) {
980 $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
6a488035 981 $lineID = key($line);
9da8dc8c 982 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
983 $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
6a488035
TO
984 if ($quickConfig) {
985 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
986 }
987 }
988
989 // process price set and get total amount and line items.
990 $lineItem = array();
991 $priceSetId = $pId = NULL;
992 $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
993 if (empty($priceSetId) && !$this->_id) {
9da8dc8c 994 $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
995 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
6a488035
TO
996 $fieldID = key($this->_priceSet['fields']);
997 $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
998 $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
999 $submittedValues['price_' . $fieldID] = 1;
1000 }
1001
1002 if ($priceSetId) {
9da8dc8c 1003 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
5a230af7 1004 $submittedValues, $lineItem[$priceSetId]);
1005
6a488035
TO
1006 $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
1007 }
1008 if ($this->_id) {
1009 //CRM-10964
5a230af7 1010 $pId = ($this->_compId && $this->_context == 'participant') ? $this->_compId : CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
6a488035
TO
1011 }
1012 if (!$priceSetId && CRM_Utils_Array::value('total_amount', $submittedValues) && $this->_id) {
1013 // 10117 update th line items for participants
1014 if ($pId) {
1015 $entityTable = 'participant';
1016 $entityID = $pId;
1017 $participantParams = array(
1018 'fee_amount' => $submittedValues['total_amount'],
1019 'id' => $entityID
1020 );
1021 CRM_Event_BAO_Participant::add($participantParams);
1022 if (empty($this->_lineItems)) {
d37ade2e 1023 $this->_lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
6a488035 1024 }
d37ade2e 1025 }
1026 else {
6a488035
TO
1027 $entityTable = 'contribution';
1028 $entityID = $this->_id;
1029 }
1030
1031 $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable);
5af5956c
CB
1032 foreach (array_keys($lineItems) as $id) {
1033 $lineItems[$id]['id'] = $id;
1034 }
6a488035
TO
1035 $itemId = key($lineItems);
1036 $fieldType = NULL;
1037 if ($itemId && CRM_Utils_Array::value('price_field_id', $lineItems[$itemId])) {
9da8dc8c 1038 $fieldType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'html_type');
6a488035
TO
1039 }
1040 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
6a488035 1041 // 10117 update th line items for participants
32cb2feb
CW
1042 if (!empty($lineItems[$itemId]['price_field_id'])) {
1043 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1044 $lineItem[$this->_priceSetId] = $lineItems;
1045 }
6a488035
TO
1046 }
1047 $isQuickConfig = 0;
9da8dc8c 1048 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
6a488035
TO
1049 $isQuickConfig = 1;
1050 }
5a230af7 1051 //CRM-11529 for quick config backoffice transactions
1052 //when financial_type_id is passed in form, update the
6a488035
TO
1053 //lineitems with the financial type selected in form
1054 if ($isQuickConfig && CRM_Utils_Array::value('financial_type_id', $submittedValues)
d37ade2e 1055 && CRM_Utils_Array::value($this->_priceSetId, $lineItem)
1056 ) {
6a488035
TO
1057 foreach ($lineItem[$this->_priceSetId] as &$values) {
1058 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1059 }
1060 }
5a230af7 1061
3b557cc8 1062 if (!isset($submittedValues['total_amount'])) {
6a488035
TO
1063 $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
1064 }
1065 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1066
cd0a30ac 1067 if (CRM_Utils_Array::value('pcp_made_through_id', $submittedValues)) {
912e7aaa 1068 $pcp = array();
d37ade2e 1069 $fields = array(
1070 'pcp_made_through_id',
1071 'pcp_display_in_roll',
1072 'pcp_roll_nickname',
1073 'pcp_personal_note',
1074 );
ce8be7f2 1075 foreach ($fields as $f) {
1076 $pcp[$f] = CRM_Utils_Array::value($f, $submittedValues);
1077 }
cd0a30ac 1078 }
1079 else {
3f662d9d 1080 //build soft credit params
d37ade2e 1081 if (!empty($submittedValues['soft_credit_contact_select_id'])) {
e8b75b35 1082 $softParams = $softIDs =array();
d37ade2e 1083 foreach ($submittedValues['soft_credit_contact_select_id'] as $key => $val) {
cd0a30ac 1084 if ($val && $submittedValues['soft_credit_amount'][$key]) {
d37ade2e 1085 $softParams[$key]['contact_id'] = $val;
0689c15c 1086 $softParams[$key]['amount'] = CRM_Utils_Rule::cleanMoney($submittedValues['soft_credit_amount'][$key]);
80673b70 1087 if (!empty($submittedValues['soft_credit_id'][$key])) {
2cfc0f58 1088 $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
912e7aaa 1089 }
cd0a30ac 1090 }
1091 }
d37ade2e 1092 }
cd0a30ac 1093 }
1094
6a488035
TO
1095 // set the contact, when contact is selected
1096 if (CRM_Utils_Array::value('contact_select_id', $submittedValues)) {
1097 $this->_contactID = $submittedValues['contact_select_id'][1];
1098 }
1099
1100 $config = CRM_Core_Config::singleton();
1101
1102 //Credit Card Contribution.
1103 if ($this->_mode) {
1104 $this->processCreditCard($submittedValues, $config, $session, $pId, $lineItem);
1105 }
1106 else {
1107 //Offline Contribution.
1108 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1109
1110 // get the required field value only.
1111 $formValues = $submittedValues;
1112 $params = $ids = array();
1113
1114 $params['contact_id'] = $this->_contactID;
1115
1116 $params['currency'] = $this->getCurrency($submittedValues);
1117
1118 $fields = array(
1119 'financial_type_id',
1120 'contribution_status_id',
1121 'payment_instrument_id',
1122 'cancel_reason',
1123 'source',
1124 'check_number',
6a488035
TO
1125 );
1126 foreach ($fields as $f) {
1127 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1128 }
ce8be7f2 1129
1130 if (!empty($pcp)) {
3f662d9d 1131 $params['pcp'] = $pcp;
ce8be7f2 1132 }
cd0a30ac 1133 if (!empty($softParams)) {
3f662d9d 1134 $params['soft_credit'] = $softParams;
2cfc0f58 1135 $params['soft_credit_ids'] = $softIDs;
6a488035 1136 }
3f662d9d 1137
6a488035
TO
1138 //if priceset is used, no need to cleanup money
1139 //CRM-5740
1140 if ($priceSetId) {
1141 $params['skipCleanMoney'] = 1;
1142 }
1143
1144 $dates = array(
1145 'receive_date',
1146 'receipt_date',
1147 'cancel_date',
1148 );
1149
1150 foreach ($dates as $d) {
1151 $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1152 }
1153
1154 if (CRM_Utils_Array::value('is_email_receipt', $formValues)) {
1155 $params['receipt_date'] = date("Y-m-d");
1156 }
1157
1158 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name')
d37ade2e 1159 || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')
1160 ) {
6a488035 1161 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
d37ade2e 1162 $params['cancel_date'] = date('Y-m-d');
6a488035
TO
1163 }
1164 }
1165 else {
d37ade2e 1166 $params['cancel_date'] = $params['cancel_reason'] = 'null';
6a488035
TO
1167 }
1168
1169 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1170 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
1171 $params['is_pay_later'] = 1;
1172 }
1173
1174 $ids['contribution'] = $params['id'] = $this->_id;
1175
1176 //Add Additional common information to formatted params
1177 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
1178 if ($pId) {
1179 $params['contribution_mode'] = 'participant';
1180 $params['participant_id'] = $pId;
464bb009 1181 $params['skipLineItem'] = 1;
6a488035
TO
1182 }
1183 $params['line_item'] = $lineItem;
1184 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
1185 //create contribution.
1186 if ($isQuickConfig) {
1187 $params['is_quick_config'] = 1;
1188 }
1189
1190 // CRM-11956
1191 // if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep it.
1192 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
1193 $params['non_deductible_amount'] = $params['non_deductible_amount'];
1194 }
1195 // if non_deductible_amount does NOT exist - then calculate it depending on:
1196 // $ContributionType->is_deductible and whether there is a product (premium).
1197 else {
1198 $contributionType = new CRM_Financial_DAO_FinancialType();
1199 $contributionType->id = $params['financial_type_id'];
1200 if (!$contributionType->find(TRUE)) {
1201 CRM_Core_Error::fatal('Could not find a system table');
1202 }
1203 if ($contributionType->is_deductible) {
1204
1205 if (isset($formValues['product_name'][0])) {
1206 $selectProduct = $formValues['product_name'][0];
1207 }
1208 // if there is a product - compare the value to the contribution amount
d37ade2e 1209 if (isset($selectProduct)) {
6a488035
TO
1210 $productDAO = new CRM_Contribute_DAO_Product();
1211 $productDAO->id = $selectProduct;
1212 $productDAO->find(TRUE);
1213 // product value exceeds contribution amount
1214 if ($params['total_amount'] < $productDAO->price) {
1215 $params['non_deductible_amount'] = $params['total_amount'];
1216 }
1217 // product value does NOT exceed contribution amount
1218 else {
1219 $params['non_deductible_amount'] = $productDAO->price;
1220 }
1221 }
1222 // contribution is deductible - but there is no product
1223 else {
1224 $params['non_deductible_amount'] = '0.00';
1225 }
1226 }
1227 // contribution is NOT deductible
1228 else {
1229 $params['non_deductible_amount'] = $params['total_amount'];
1230 }
1231 }
1232
1233 $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
1234
1235 // process associated membership / participant, CRM-4395
1236 $relatedComponentStatusMsg = NULL;
1237 if ($contribution->id && $this->_action & CRM_Core_Action::UPDATE) {
1238 $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id,
1239 $contribution->contribution_status_id,
1240 CRM_Utils_Array::value('contribution_status_id',
1241 $this->_values
1242 )
1243 );
1244 }
1245
1246 //process note
1247 if ($contribution->id && isset($formValues['note'])) {
1248 CRM_Contribute_Form_AdditionalInfo::processNote($formValues, $this->_contactID, $contribution->id, $this->_noteID);
1249 }
1250
1251 //process premium
5a230af7 1252 if ($contribution->id && isset($formValues['product_name'][0])) {
6a488035
TO
1253 CRM_Contribute_Form_AdditionalInfo::processPremium($formValues, $contribution->id,
1254 $this->_premiumID, $this->_options
1255 );
1256 }
1257
1258 //send receipt mail.
1259 if ($contribution->id && CRM_Utils_Array::value('is_email_receipt', $formValues)) {
1260 $formValues['contact_id'] = $this->_contactID;
1261 $formValues['contribution_id'] = $contribution->id;
1262
1263 // to get 'from email id' for send receipt
1264 $this->fromEmailId = $formValues['from_email_address'];
1265 $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues);
1266 }
1267
1268 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1269 $contribution->id,
1270 'id',
1271 'contribution_id'
1272 );
1273
1274 //update pledge payment status.
1275 if ((($this->_ppID && $contribution->id) && $this->_action & CRM_Core_Action::ADD) ||
1276 (($pledgePaymentId) && $this->_action & CRM_Core_Action::UPDATE)
1277 ) {
1278
1279 if ($this->_ppID) {
1280 //store contribution id in payment record.
1281 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
1282 }
1283 else {
1284 $this->_ppID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1285 $contribution->id,
1286 'id',
1287 'contribution_id'
1288 );
1289 $this->_pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1290 $contribution->id,
1291 'pledge_id',
1292 'contribution_id'
1293 );
1294 }
1295
1296 $adjustTotalAmount = FALSE;
1297 if (CRM_Utils_Array::value('option_type', $formValues) == 2) {
1298 $adjustTotalAmount = TRUE;
1299 }
1300
1301 $updatePledgePaymentStatus = FALSE;
1302 //do only if either the status or the amount has changed
1303 if ($this->_action & CRM_Core_Action::ADD) {
1304 $updatePledgePaymentStatus = TRUE;
1305 }
1306 elseif ($this->_action & CRM_Core_Action::UPDATE && (($this->_defaults['contribution_status_id'] != $formValues['contribution_status_id']) ||
1307 ($this->_defaults['total_amount'] != $formValues['total_amount']))
1308 ) {
1309 $updatePledgePaymentStatus = TRUE;
1310 }
1311
1312 if ($updatePledgePaymentStatus) {
1313 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID,
1314 array($this->_ppID),
1315 $contribution->contribution_status_id,
1316 NULL,
1317 $contribution->total_amount,
1318 $adjustTotalAmount
1319 );
1320 }
1321 }
5a230af7 1322
6a488035
TO
1323 $statusMsg = ts('The contribution record has been saved.');
1324 if (CRM_Utils_Array::value('is_email_receipt', $formValues) && $sendReceipt) {
1325 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1326 }
5a230af7 1327
6a488035
TO
1328 if ($relatedComponentStatusMsg) {
1329 $statusMsg .= ' ' . $relatedComponentStatusMsg;
1330 }
5a230af7 1331
6a488035
TO
1332 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
1333 //Offline Contribution ends.
5a230af7 1334 }
6a488035
TO
1335 $buttonName = $this->controller->getButtonName();
1336 if ($this->_context == 'standalone') {
1337 if ($buttonName == $this->getButtonName('upload', 'new')) {
1338 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add',
1339 'reset=1&action=add&context=standalone'
1340 ));
1341 }
1342 else {
1343 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1344 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1345 ));
1346 }
1347 }
1348 elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) {
1349 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1350 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1351 ));
1352 }
1353 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1354 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1355 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1356 ));
1357 }
1358 }
5a230af7 1359
6a488035
TO
1360 public function processCreditCard($submittedValues, $config, $session, $pId, $lineItem) {
1361 $unsetParams = array(
1362 'trxn_id',
1363 'payment_instrument_id',
1364 'contribution_status_id',
1365 'cancel_date',
1366 'cancel_reason',
1367 );
1368 foreach ($unsetParams as $key) {
1369 if (isset($submittedValues[$key])) {
1370 unset($submittedValues[$key]);
1371 }
1372 }
eea16664 1373
25e92485
PN
1374 // CRM-12680 set $_lineItem if its not set
1375 if (empty($this->_lineItem) && !empty($lineItem)) {
1376 $this->_lineItem = $lineItem;
1377 }
eea16664 1378
6a488035
TO
1379 //Get the rquire fields value only.
1380 $params = $this->_params = $submittedValues;
1381
1382 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
1383 $this->_mode
1384 );
1385
1386 //get the payment processor id as per mode.
8ef12e64 1387 $this->_params['payment_processor'] = $params['payment_processor_id'] =
78b79549 1388 $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
6a488035
TO
1389
1390 $now = date('YmdHis');
1391 $fields = array();
1392
1393 // we need to retrieve email address
1394 if ($this->_context == 'standalone' && CRM_Utils_Array::value('is_email_receipt', $submittedValues)) {
1395 list($this->userDisplayName,
1396 $this->userEmail
1397 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
1398 $this->assign('displayName', $this->userDisplayName);
1399 }
1400
1401 //set email for primary location.
1402 $fields['email-Primary'] = 1;
1403 $params['email-Primary'] = $this->userEmail;
1404
1405 // now set the values for the billing location.
1406 foreach ($this->_fields as $name => $dontCare) {
1407 $fields[$name] = 1;
1408 }
1409
1410 // also add location name to the array
1411 $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);
1412 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1413 $fields["address_name-{$this->_bltID}"] = 1;
1414
1415 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
1416 $this->_contactID,
1417 'contact_type'
1418 );
1419
1420 $nameFields = array('first_name', 'middle_name', 'last_name');
1421 foreach ($nameFields as $name) {
1422 $fields[$name] = 1;
1423 if (array_key_exists("billing_$name", $params)) {
1424 $params[$name] = $params["billing_{$name}"];
1425 $params['preserveDBName'] = TRUE;
1426 }
1427 }
1428
1429 if (CRM_Utils_Array::value('source', $params)) {
1430 unset($params['source']);
1431 }
1432 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields,
1433 $this->_contactID,
1434 NULL, NULL,
1435 $ctype
1436 );
1437
1438 // add all the additioanl payment params we need
1439 $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}"]);
1440 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
1441
1442 if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD) {
1443 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
1444 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
1445 }
1446 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
1447 $this->_params['amount'] = $this->_params['total_amount'];
1448 $this->_params['amount_level'] = 0;
1449 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
1450 $this->_params,
1451 $config->defaultCurrency
1452 );
1453 $this->_params['payment_action'] = 'Sale';
1454 if (CRM_Utils_Array::value('receive_date', $this->_params)) {
1455 $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']);
1456 }
1457
1458 if (CRM_Utils_Array::value('soft_credit_to', $params)) {
1459 $this->_params['soft_credit_to'] = $params['soft_credit_to'];
1460 $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id'];
1461 }
1462
1463 $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
1464 $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
1465 $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
1466
1467 //Add common data to formatted params
1468 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
1469
1470 if (empty($this->_params['invoice_id'])) {
1471 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1472 }
1473 else {
1474 $this->_params['invoiceID'] = $this->_params['invoice_id'];
1475 }
1476
1477 // at this point we've created a contact and stored its address etc
1478 // all the payment processors expect the name and address to be in the
1479 // so we copy stuff over to first_name etc.
1480 $paymentParams = $this->_params;
1481 $paymentParams['contactID'] = $this->_contactID;
1482 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
1483
1484 $contributionType = new CRM_Financial_DAO_FinancialType();
1485 $contributionType->id = $params['financial_type_id'];
1486 if (!$contributionType->find(TRUE)) {
1487 CRM_Core_Error::fatal('Could not find a system table');
1488 }
1489
1490 // add some financial type details to the params list
1491 // if folks need to use it
1492 $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
1493 $paymentParams['contributionPageID'] = NULL;
1494 if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
1495 $paymentParams['email'] = $this->userEmail;
1496 $paymentParams['is_email_receipt'] = 1;
1497 }
1498 else {
1499 $paymentParams['is_email_receipt'] = 0;
1500 $this->_params['is_email_receipt'] = 0;
1501 }
1502 if (CRM_Utils_Array::value('receive_date', $this->_params)) {
1503 $paymentParams['receive_date'] = $this->_params['receive_date'];
1504 }
1505 if (CRM_Utils_Array::value('receive_date', $this->_params)) {
1506 $paymentParams['receive_date'] = $this->_params['receive_date'];
1507 }
1508
1509 $result = NULL;
1510
1511 // For recurring contribution, create Contribution Record first.
1512 // Contribution ID, Recurring ID and Contact ID needed
1513 // When we get a callback from the payment processor, CRM-7115
1514 if (CRM_Utils_Array::value('is_recur', $paymentParams)) {
1515 $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this,
1516 $this->_params,
1517 $result,
1518 $this->_contactID,
1519 $contributionType,
1520 FALSE,
1521 TRUE,
1522 FALSE
1523 );
1524 $paymentParams['contributionID'] = $contribution->id;
1525 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
1526 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1527 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
1528 }
1529
1530 if ($paymentParams['amount'] > 0.0) {
1531 // force a reget of the payment processor in case the form changed it, CRM-7179
1532 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE);
1533 $result = $payment->doDirectPayment($paymentParams);
1534 }
1535
1536 if (is_a($result, 'CRM_Core_Error')) {
1537 //make sure to cleanup db for recurring case.
1538 if (CRM_Utils_Array::value('contributionID', $paymentParams)) {
1539 CRM_Core_Error::debug_log_message(CRM_Core_Error::getMessages($result) . "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}");
1540 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
1541 }
1542 if (CRM_Utils_Array::value('contributionRecurID', $paymentParams)) {
1543 CRM_Core_Error::debug_log_message(CRM_Core_Error::getMessages($result) . "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}");
1544 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
1545 }
1546
1547 //set the contribution mode.
1548 $urlParams = "action=add&cid={$this->_contactID}";
1549 if ($this->_mode) {
1550 $urlParams .= "&mode={$this->_mode}";
1551 }
1552 if (!empty($this->_ppID)) {
1553 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1554 }
1555 CRM_Core_Error::displaySessionError($result);
1556 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams));
1557 }
1558
1559 if ($result) {
1560 $this->_params = array_merge($this->_params, $result);
1561 }
1562
1563 $this->_params['receive_date'] = $now;
1564
1565 if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
1566 $this->_params['receipt_date'] = $now;
1567 }
1568 else {
1569 $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'],
1570 $params['receipt_date_time'], TRUE
1571 );
1572 }
1573
1574 $this->set('params', $this->_params);
1575 $this->assign('trxn_id', $result['trxn_id']);
1576 $this->assign('receive_date', $this->_params['receive_date']);
1577
1578 // result has all the stuff we need
1579 // lets archive it to a financial transaction
1580 if ($contributionType->is_deductible) {
1581 $this->assign('is_deductible', TRUE);
1582 $this->set('is_deductible', TRUE);
1583 }
1584
1585 // set source if not set
1586 if (empty($this->_params['source'])) {
1587 $userID = $session->get('userID');
1588 $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1589 'sort_name'
1590 );
1591 $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1592 }
1593
1594 // build custom data getFields array
1595 $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE,
1596 CRM_Utils_Array::value('financial_type_id', $params)
1597 );
1598 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType,
1599 CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE)
1600 );
1601 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
1602 $customFields,
1603 $this->_id,
1604 'Contribution'
1605 );
1606
1607
1608 if (!CRM_Utils_Array::value('is_recur', $paymentParams)) {
1609 $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this,
1610 $this->_params,
1611 $result,
1612 $this->_contactID,
1613 $contributionType,
1614 FALSE, FALSE, FALSE
1615 );
1616 }
1617
1618 //send receipt mail.
1619 if ($contribution->id &&
1620 CRM_Utils_Array::value('is_email_receipt', $this->_params)
1621 ) {
1622 $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
1623 $this->_params['contact_id'] = $this->_contactID;
1624 $this->_params['contribution_id'] = $contribution->id;
1625 $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE);
1626 }
1627
1628 //process the note
1629 if ($contribution->id && isset($params['note'])) {
1630 CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, NULL);
1631 }
1632 //process premium
1633 if ($contribution->id && isset($params['product_name'][0])) {
1634 CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, NULL, $this->_options);
1635 }
1636
1637 //update pledge payment status.
1638 if ($this->_ppID && $contribution->id) {
1639 //store contribution id in payment record.
1640 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
1641
1642 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID,
1643 array($this->_ppID),
1644 $contribution->contribution_status_id,
1645 NULL,
1646 $contribution->total_amount
1647 );
1648 }
1649
1650 if ($contribution->id) {
1651 $statusMsg = ts('The contribution record has been processed.');
1652 if (CRM_Utils_Array::value('is_email_receipt', $this->_params) && $sendReceipt) {
1653 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1654 }
1655 CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
1656 }
1657 }
1658}
1659