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