Merge remote-tracking branch 'upstream/4.3' into 4.3-master-2013-05-01-11-04-54
[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);
cd0a30ac 1022
6a488035
TO
1023 if (CRM_Utils_Array::value('price_set_id', $submittedValues) && $this->_action & CRM_Core_Action::UPDATE ) {
1024 $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
1025 $lineID = key($line);
1026 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
1027 $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $priceSetId, 'is_quick_config');
1028 if ($quickConfig) {
1029 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
1030 }
1031 }
1032
1033 // process price set and get total amount and line items.
1034 $lineItem = array();
1035 $priceSetId = $pId = NULL;
1036 $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
1037 if (empty($priceSetId) && !$this->_id) {
1038 $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', 'default_contribution_amount', 'id', 'name');
1039 $this->_priceSet = current(CRM_Price_BAO_Set::getSetDetail($priceSetId));
1040 $fieldID = key($this->_priceSet['fields']);
1041 $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
1042 $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1043 $submittedValues['price_' . $fieldID] = 1;
1044 }
1045
1046 if ($priceSetId) {
1047 CRM_Price_BAO_Set::processAmount($this->_priceSet['fields'],
5a230af7 1048 $submittedValues, $lineItem[$priceSetId]);
1049
6a488035
TO
1050 $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
1051 }
1052 if ($this->_id) {
1053 //CRM-10964
5a230af7 1054 $pId = ($this->_compId && $this->_context == 'participant') ? $this->_compId : CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
6a488035
TO
1055 }
1056 if (!$priceSetId && CRM_Utils_Array::value('total_amount', $submittedValues) && $this->_id) {
1057 // 10117 update th line items for participants
1058 if ($pId) {
1059 $entityTable = 'participant';
1060 $entityID = $pId;
1061 $participantParams = array(
1062 'fee_amount' => $submittedValues['total_amount'],
1063 'id' => $entityID
1064 );
1065 CRM_Event_BAO_Participant::add($participantParams);
1066 if (empty($this->_lineItems)) {
1067 $this->_lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant',1);
1068 }
1069 } else {
1070 $entityTable = 'contribution';
1071 $entityID = $this->_id;
1072 }
1073
1074 $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable);
1075 $itemId = key($lineItems);
1076 $fieldType = NULL;
1077 if ($itemId && CRM_Utils_Array::value('price_field_id', $lineItems[$itemId])) {
1078 $fieldType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $lineItems[$itemId]['price_field_id'], 'html_type');
1079 }
1080 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
1081 $lineItems[$itemId]['id'] = $itemId;
1082 // 10117 update th line items for participants
1083 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1084 $lineItem[$this->_priceSetId] = $lineItems;
1085 }
1086 $isQuickConfig = 0;
1087 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $this->_priceSetId, 'is_quick_config')) {
1088 $isQuickConfig = 1;
1089 }
5a230af7 1090 //CRM-11529 for quick config backoffice transactions
1091 //when financial_type_id is passed in form, update the
6a488035
TO
1092 //lineitems with the financial type selected in form
1093 if ($isQuickConfig && CRM_Utils_Array::value('financial_type_id', $submittedValues)
1094 && CRM_Utils_Array::value($this->_priceSetId, $lineItem)) {
1095 foreach ($lineItem[$this->_priceSetId] as &$values) {
1096 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1097 }
1098 }
5a230af7 1099
6a488035
TO
1100 if (!CRM_Utils_Array::value('total_amount', $submittedValues)) {
1101 $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
1102 }
1103 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1104
cd0a30ac 1105 if (CRM_Utils_Array::value('pcp_made_through_id', $submittedValues)) {
ce8be7f2 1106 $fields = array(
1107 'pcp_made_through_id', 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note',
1108 );
1109 foreach ($fields as $f) {
1110 $pcp[$f] = CRM_Utils_Array::value($f, $submittedValues);
1111 }
cd0a30ac 1112 }
1113 else {
1114 //build soft credit params
1115 if (!empty($submittedValues['soft_credit_contact_select_id']))
1116 $softParams = array();
1117 foreach( $submittedValues['soft_credit_contact_select_id'] as $key => $val) {
1118 if ($val && $submittedValues['soft_credit_amount'][$key]) {
1119 $softParams[$key]['contact_id'] = $val;
1120 $softParams[$key]['amount'] = $submittedValues['soft_credit_amount'][$key];
1121 $softCredit = TRUE;
1122 }
1123 }
6a488035 1124 }
cd0a30ac 1125 if (!empty($softParams)) {
1126 $params['soft_credit'] = $softParams;
1127 }
1128
1129 /* if (CRM_Utils_Array::value('soft_credit_to', $submittedValues)) {
1130 $submittedValues['soft_credit_to'] = $submittedValues['soft_contact_id'];
1131 }*/
6a488035
TO
1132
1133 // set the contact, when contact is selected
1134 if (CRM_Utils_Array::value('contact_select_id', $submittedValues)) {
1135 $this->_contactID = $submittedValues['contact_select_id'][1];
1136 }
1137
1138 $config = CRM_Core_Config::singleton();
1139
1140 //Credit Card Contribution.
1141 if ($this->_mode) {
1142 $this->processCreditCard($submittedValues, $config, $session, $pId, $lineItem);
1143 }
1144 else {
1145 //Offline Contribution.
1146 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1147
1148 // get the required field value only.
1149 $formValues = $submittedValues;
1150 $params = $ids = array();
1151
1152 $params['contact_id'] = $this->_contactID;
1153
1154 $params['currency'] = $this->getCurrency($submittedValues);
1155
1156 $fields = array(
1157 'financial_type_id',
1158 'contribution_status_id',
1159 'payment_instrument_id',
1160 'cancel_reason',
1161 'source',
1162 'check_number',
cd0a30ac 1163 /*'soft_credit_to',
6a488035
TO
1164 'pcp_made_through_id',
1165 'pcp_display_in_roll',
1166 'pcp_roll_nickname',
cd0a30ac 1167 'pcp_personal_note',*/
6a488035
TO
1168 );
1169 foreach ($fields as $f) {
1170 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1171 }
ce8be7f2 1172
1173 if (!empty($pcp)) {
1174 $params['pcp'] = $pcp;
1175 }
cd0a30ac 1176 if (!empty($softParams)) {
1177 $params['soft_credit'] = $softParams;
6a488035 1178 }
cd0a30ac 1179 /*if ($softID = CRM_Utils_Array::value('softID', $this->_values)) {
1180 $params['softID'] = $softID;
1181 }*/
6a488035
TO
1182 //if priceset is used, no need to cleanup money
1183 //CRM-5740
1184 if ($priceSetId) {
1185 $params['skipCleanMoney'] = 1;
1186 }
1187
1188 $dates = array(
1189 'receive_date',
1190 'receipt_date',
1191 'cancel_date',
1192 );
1193
1194 foreach ($dates as $d) {
1195 $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1196 }
1197
1198 if (CRM_Utils_Array::value('is_email_receipt', $formValues)) {
1199 $params['receipt_date'] = date("Y-m-d");
1200 }
1201
1202 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name')
1203 || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')) {
1204 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
1205 $params['cancel_date'] = date("Y-m-d");
1206 }
1207 }
1208 else {
cd0a30ac 1209 $params['cancel_date'] = $params['cancel_reason'] = 'null';
6a488035
TO
1210 }
1211
1212 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1213 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
1214 $params['is_pay_later'] = 1;
1215 }
1216
1217 $ids['contribution'] = $params['id'] = $this->_id;
1218
1219 //Add Additional common information to formatted params
1220 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
1221 if ($pId) {
1222 $params['contribution_mode'] = 'participant';
1223 $params['participant_id'] = $pId;
464bb009 1224 $params['skipLineItem'] = 1;
6a488035
TO
1225 }
1226 $params['line_item'] = $lineItem;
1227 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
1228 //create contribution.
1229 if ($isQuickConfig) {
1230 $params['is_quick_config'] = 1;
1231 }
1232
1233 // CRM-11956
1234 // if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep it.
1235 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
1236 $params['non_deductible_amount'] = $params['non_deductible_amount'];
1237 }
1238 // if non_deductible_amount does NOT exist - then calculate it depending on:
1239 // $ContributionType->is_deductible and whether there is a product (premium).
1240 else {
1241 $contributionType = new CRM_Financial_DAO_FinancialType();
1242 $contributionType->id = $params['financial_type_id'];
1243 if (!$contributionType->find(TRUE)) {
1244 CRM_Core_Error::fatal('Could not find a system table');
1245 }
1246 if ($contributionType->is_deductible) {
1247
1248 if (isset($formValues['product_name'][0])) {
1249 $selectProduct = $formValues['product_name'][0];
1250 }
1251 // if there is a product - compare the value to the contribution amount
1252 if (isset($selectProduct))
1253 {
1254 $productDAO = new CRM_Contribute_DAO_Product();
1255 $productDAO->id = $selectProduct;
1256 $productDAO->find(TRUE);
1257 // product value exceeds contribution amount
1258 if ($params['total_amount'] < $productDAO->price) {
1259 $params['non_deductible_amount'] = $params['total_amount'];
1260 }
1261 // product value does NOT exceed contribution amount
1262 else {
1263 $params['non_deductible_amount'] = $productDAO->price;
1264 }
1265 }
1266 // contribution is deductible - but there is no product
1267 else {
1268 $params['non_deductible_amount'] = '0.00';
1269 }
1270 }
1271 // contribution is NOT deductible
1272 else {
1273 $params['non_deductible_amount'] = $params['total_amount'];
1274 }
1275 }
1276
1277 $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
1278
1279 // process associated membership / participant, CRM-4395
1280 $relatedComponentStatusMsg = NULL;
1281 if ($contribution->id && $this->_action & CRM_Core_Action::UPDATE) {
1282 $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id,
1283 $contribution->contribution_status_id,
1284 CRM_Utils_Array::value('contribution_status_id',
1285 $this->_values
1286 )
1287 );
1288 }
1289
1290 //process note
1291 if ($contribution->id && isset($formValues['note'])) {
1292 CRM_Contribute_Form_AdditionalInfo::processNote($formValues, $this->_contactID, $contribution->id, $this->_noteID);
1293 }
1294
1295 //process premium
5a230af7 1296 if ($contribution->id && isset($formValues['product_name'][0])) {
6a488035
TO
1297 CRM_Contribute_Form_AdditionalInfo::processPremium($formValues, $contribution->id,
1298 $this->_premiumID, $this->_options
1299 );
1300 }
1301
1302 //send receipt mail.
1303 if ($contribution->id && CRM_Utils_Array::value('is_email_receipt', $formValues)) {
1304 $formValues['contact_id'] = $this->_contactID;
1305 $formValues['contribution_id'] = $contribution->id;
1306
1307 // to get 'from email id' for send receipt
1308 $this->fromEmailId = $formValues['from_email_address'];
1309 $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues);
1310 }
1311
1312 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1313 $contribution->id,
1314 'id',
1315 'contribution_id'
1316 );
1317
1318 //update pledge payment status.
1319 if ((($this->_ppID && $contribution->id) && $this->_action & CRM_Core_Action::ADD) ||
1320 (($pledgePaymentId) && $this->_action & CRM_Core_Action::UPDATE)
1321 ) {
1322
1323 if ($this->_ppID) {
1324 //store contribution id in payment record.
1325 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
1326 }
1327 else {
1328 $this->_ppID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1329 $contribution->id,
1330 'id',
1331 'contribution_id'
1332 );
1333 $this->_pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1334 $contribution->id,
1335 'pledge_id',
1336 'contribution_id'
1337 );
1338 }
1339
1340 $adjustTotalAmount = FALSE;
1341 if (CRM_Utils_Array::value('option_type', $formValues) == 2) {
1342 $adjustTotalAmount = TRUE;
1343 }
1344
1345 $updatePledgePaymentStatus = FALSE;
1346 //do only if either the status or the amount has changed
1347 if ($this->_action & CRM_Core_Action::ADD) {
1348 $updatePledgePaymentStatus = TRUE;
1349 }
1350 elseif ($this->_action & CRM_Core_Action::UPDATE && (($this->_defaults['contribution_status_id'] != $formValues['contribution_status_id']) ||
1351 ($this->_defaults['total_amount'] != $formValues['total_amount']))
1352 ) {
1353 $updatePledgePaymentStatus = TRUE;
1354 }
1355
1356 if ($updatePledgePaymentStatus) {
1357 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID,
1358 array($this->_ppID),
1359 $contribution->contribution_status_id,
1360 NULL,
1361 $contribution->total_amount,
1362 $adjustTotalAmount
1363 );
1364 }
1365 }
5a230af7 1366
6a488035
TO
1367 $statusMsg = ts('The contribution record has been saved.');
1368 if (CRM_Utils_Array::value('is_email_receipt', $formValues) && $sendReceipt) {
1369 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1370 }
5a230af7 1371
6a488035
TO
1372 if ($relatedComponentStatusMsg) {
1373 $statusMsg .= ' ' . $relatedComponentStatusMsg;
1374 }
5a230af7 1375
6a488035
TO
1376 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
1377 //Offline Contribution ends.
5a230af7 1378 }
6a488035
TO
1379 $buttonName = $this->controller->getButtonName();
1380 if ($this->_context == 'standalone') {
1381 if ($buttonName == $this->getButtonName('upload', 'new')) {
1382 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add',
1383 'reset=1&action=add&context=standalone'
1384 ));
1385 }
1386 else {
1387 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1388 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1389 ));
1390 }
1391 }
1392 elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) {
1393 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1394 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1395 ));
1396 }
1397 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1398 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1399 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1400 ));
1401 }
1402 }
5a230af7 1403
6a488035
TO
1404 public function processCreditCard($submittedValues, $config, $session, $pId, $lineItem) {
1405 $unsetParams = array(
1406 'trxn_id',
1407 'payment_instrument_id',
1408 'contribution_status_id',
1409 'cancel_date',
1410 'cancel_reason',
1411 );
1412 foreach ($unsetParams as $key) {
1413 if (isset($submittedValues[$key])) {
1414 unset($submittedValues[$key]);
1415 }
1416 }
1417
1418 //Get the rquire fields value only.
1419 $params = $this->_params = $submittedValues;
1420
1421 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
1422 $this->_mode
1423 );
1424
1425 //get the payment processor id as per mode.
1426 $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
1427
1428 $now = date('YmdHis');
1429 $fields = array();
1430
1431 // we need to retrieve email address
1432 if ($this->_context == 'standalone' && CRM_Utils_Array::value('is_email_receipt', $submittedValues)) {
1433 list($this->userDisplayName,
1434 $this->userEmail
1435 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
1436 $this->assign('displayName', $this->userDisplayName);
1437 }
1438
1439 //set email for primary location.
1440 $fields['email-Primary'] = 1;
1441 $params['email-Primary'] = $this->userEmail;
1442
1443 // now set the values for the billing location.
1444 foreach ($this->_fields as $name => $dontCare) {
1445 $fields[$name] = 1;
1446 }
1447
1448 // also add location name to the array
1449 $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);
1450 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1451 $fields["address_name-{$this->_bltID}"] = 1;
1452
1453 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
1454 $this->_contactID,
1455 'contact_type'
1456 );
1457
1458 $nameFields = array('first_name', 'middle_name', 'last_name');
1459 foreach ($nameFields as $name) {
1460 $fields[$name] = 1;
1461 if (array_key_exists("billing_$name", $params)) {
1462 $params[$name] = $params["billing_{$name}"];
1463 $params['preserveDBName'] = TRUE;
1464 }
1465 }
1466
1467 if (CRM_Utils_Array::value('source', $params)) {
1468 unset($params['source']);
1469 }
1470 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields,
1471 $this->_contactID,
1472 NULL, NULL,
1473 $ctype
1474 );
1475
1476 // add all the additioanl payment params we need
1477 $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}"]);
1478 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
1479
1480 if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD) {
1481 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
1482 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
1483 }
1484 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
1485 $this->_params['amount'] = $this->_params['total_amount'];
1486 $this->_params['amount_level'] = 0;
1487 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
1488 $this->_params,
1489 $config->defaultCurrency
1490 );
1491 $this->_params['payment_action'] = 'Sale';
1492 if (CRM_Utils_Array::value('receive_date', $this->_params)) {
1493 $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']);
1494 }
1495
1496 if (CRM_Utils_Array::value('soft_credit_to', $params)) {
1497 $this->_params['soft_credit_to'] = $params['soft_credit_to'];
1498 $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id'];
1499 }
1500
1501 $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
1502 $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
1503 $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
1504
1505 //Add common data to formatted params
1506 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
1507
1508 if (empty($this->_params['invoice_id'])) {
1509 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1510 }
1511 else {
1512 $this->_params['invoiceID'] = $this->_params['invoice_id'];
1513 }
1514
1515 // at this point we've created a contact and stored its address etc
1516 // all the payment processors expect the name and address to be in the
1517 // so we copy stuff over to first_name etc.
1518 $paymentParams = $this->_params;
1519 $paymentParams['contactID'] = $this->_contactID;
1520 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
1521
1522 $contributionType = new CRM_Financial_DAO_FinancialType();
1523 $contributionType->id = $params['financial_type_id'];
1524 if (!$contributionType->find(TRUE)) {
1525 CRM_Core_Error::fatal('Could not find a system table');
1526 }
1527
1528 // add some financial type details to the params list
1529 // if folks need to use it
1530 $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
1531 $paymentParams['contributionPageID'] = NULL;
1532 if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
1533 $paymentParams['email'] = $this->userEmail;
1534 $paymentParams['is_email_receipt'] = 1;
1535 }
1536 else {
1537 $paymentParams['is_email_receipt'] = 0;
1538 $this->_params['is_email_receipt'] = 0;
1539 }
1540 if (CRM_Utils_Array::value('receive_date', $this->_params)) {
1541 $paymentParams['receive_date'] = $this->_params['receive_date'];
1542 }
1543 if (CRM_Utils_Array::value('receive_date', $this->_params)) {
1544 $paymentParams['receive_date'] = $this->_params['receive_date'];
1545 }
1546
1547 $result = NULL;
1548
1549 // For recurring contribution, create Contribution Record first.
1550 // Contribution ID, Recurring ID and Contact ID needed
1551 // When we get a callback from the payment processor, CRM-7115
1552 if (CRM_Utils_Array::value('is_recur', $paymentParams)) {
1553 $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this,
1554 $this->_params,
1555 $result,
1556 $this->_contactID,
1557 $contributionType,
1558 FALSE,
1559 TRUE,
1560 FALSE
1561 );
1562 $paymentParams['contributionID'] = $contribution->id;
1563 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
1564 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1565 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
1566 }
1567
1568 if ($paymentParams['amount'] > 0.0) {
1569 // force a reget of the payment processor in case the form changed it, CRM-7179
1570 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE);
1571 $result = $payment->doDirectPayment($paymentParams);
1572 }
1573
1574 if (is_a($result, 'CRM_Core_Error')) {
1575 //make sure to cleanup db for recurring case.
1576 if (CRM_Utils_Array::value('contributionID', $paymentParams)) {
1577 CRM_Core_Error::debug_log_message(CRM_Core_Error::getMessages($result) . "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}");
1578 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
1579 }
1580 if (CRM_Utils_Array::value('contributionRecurID', $paymentParams)) {
1581 CRM_Core_Error::debug_log_message(CRM_Core_Error::getMessages($result) . "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}");
1582 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
1583 }
1584
1585 //set the contribution mode.
1586 $urlParams = "action=add&cid={$this->_contactID}";
1587 if ($this->_mode) {
1588 $urlParams .= "&mode={$this->_mode}";
1589 }
1590 if (!empty($this->_ppID)) {
1591 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1592 }
1593 CRM_Core_Error::displaySessionError($result);
1594 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams));
1595 }
1596
1597 if ($result) {
1598 $this->_params = array_merge($this->_params, $result);
1599 }
1600
1601 $this->_params['receive_date'] = $now;
1602
1603 if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
1604 $this->_params['receipt_date'] = $now;
1605 }
1606 else {
1607 $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'],
1608 $params['receipt_date_time'], TRUE
1609 );
1610 }
1611
1612 $this->set('params', $this->_params);
1613 $this->assign('trxn_id', $result['trxn_id']);
1614 $this->assign('receive_date', $this->_params['receive_date']);
1615
1616 // result has all the stuff we need
1617 // lets archive it to a financial transaction
1618 if ($contributionType->is_deductible) {
1619 $this->assign('is_deductible', TRUE);
1620 $this->set('is_deductible', TRUE);
1621 }
1622
1623 // set source if not set
1624 if (empty($this->_params['source'])) {
1625 $userID = $session->get('userID');
1626 $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1627 'sort_name'
1628 );
1629 $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1630 }
1631
1632 // build custom data getFields array
1633 $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE,
1634 CRM_Utils_Array::value('financial_type_id', $params)
1635 );
1636 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType,
1637 CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE)
1638 );
1639 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
1640 $customFields,
1641 $this->_id,
1642 'Contribution'
1643 );
1644
1645
1646 if (!CRM_Utils_Array::value('is_recur', $paymentParams)) {
1647 $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this,
1648 $this->_params,
1649 $result,
1650 $this->_contactID,
1651 $contributionType,
1652 FALSE, FALSE, FALSE
1653 );
1654 }
1655
1656 //send receipt mail.
1657 if ($contribution->id &&
1658 CRM_Utils_Array::value('is_email_receipt', $this->_params)
1659 ) {
1660 $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
1661 $this->_params['contact_id'] = $this->_contactID;
1662 $this->_params['contribution_id'] = $contribution->id;
1663 $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE);
1664 }
1665
1666 //process the note
1667 if ($contribution->id && isset($params['note'])) {
1668 CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, NULL);
1669 }
1670 //process premium
1671 if ($contribution->id && isset($params['product_name'][0])) {
1672 CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, NULL, $this->_options);
1673 }
1674
1675 //update pledge payment status.
1676 if ($this->_ppID && $contribution->id) {
1677 //store contribution id in payment record.
1678 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
1679
1680 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID,
1681 array($this->_ppID),
1682 $contribution->contribution_status_id,
1683 NULL,
1684 $contribution->total_amount
1685 );
1686 }
1687
1688 if ($contribution->id) {
1689 $statusMsg = ts('The contribution record has been processed.');
1690 if (CRM_Utils_Array::value('is_email_receipt', $this->_params) && $sendReceipt) {
1691 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1692 }
1693 CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
1694 }
1695 }
1696}
1697