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