--ICM-17, added condition to check if FT-ACL is turned off or on
[civicrm-core.git] / CRM / Contribute / Form / Contribution.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 | |
74ab7ba8 14 | CiviCRM is distributed in the hope that it will be useful, but |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035 27
7758bd2b
EM
28use Civi\Payment\Exception\PaymentProcessorException;
29
6a488035 30/**
22ab45ae 31 * This class generates form components for processing a contribution.
6a488035
TO
32 */
33class CRM_Contribute_Form_Contribution extends CRM_Contribute_Form_AbstractEditPayment {
6a488035 34 /**
fe482240 35 * The id of the contribution that we are processing.
6a488035
TO
36 *
37 * @var int
6a488035
TO
38 */
39 public $_id;
40
41 /**
fe482240 42 * The id of the premium that we are processing.
6a488035
TO
43 *
44 * @var int
6a488035
TO
45 */
46 public $_premiumID = NULL;
4691b077
EM
47
48 /**
49 * @var CRM_Contribute_DAO_ContributionProduct
50 */
6a488035
TO
51 public $_productDAO = NULL;
52
53 /**
fe482240 54 * The id of the note.
6a488035
TO
55 *
56 * @var int
6a488035
TO
57 */
58 public $_noteID;
59
60 /**
fe482240 61 * The id of the contact associated with this contribution.
6a488035
TO
62 *
63 * @var int
6a488035
TO
64 */
65 public $_contactID;
66
67 /**
fe482240 68 * The id of the pledge payment that we are processing.
6a488035
TO
69 *
70 * @var int
6a488035
TO
71 */
72 public $_ppID;
73
6a488035 74 /**
fe482240 75 * Is this contribution associated with an online.
6a488035
TO
76 * financial transaction
77 *
78 * @var boolean
6a488035
TO
79 */
80 public $_online = FALSE;
81
82 /**
bf56a083 83 * Stores all product options.
6a488035
TO
84 *
85 * @var array
6a488035
TO
86 */
87 public $_options;
88
4691b077
EM
89 /**
90 * Storage of parameters from form
91 *
92 * @var array
4691b077
EM
93 */
94 public $_params;
95
6a488035
TO
96 /**
97 * Store the contribution Type ID
98 *
99 * @var array
100 */
101 public $_contributionType;
102
103 /**
104 * The contribution values if an existing contribution
105 */
106 public $_values;
107
108 /**
109 * The pledge values if this contribution is associated with pledge
110 */
111 public $_pledgeValues;
112
113 public $_contributeMode = 'direct';
114
115 public $_context;
116
5032bf07 117 /**
fe482240 118 * Parameter with confusing name.
5032bf07
EM
119 * @todo what is it?
120 * @var string
121 */
122 public $_compContext;
123
6a488035
TO
124 public $_compId;
125
5032bf07
EM
126 /**
127 * Possible From email addresses
128 * @var array
129 */
130 public $_fromEmails;
d77a0a58
EM
131
132 /**
133 * ID of from email
134 * @var integer
135 */
136 public $fromEmailId;
d424ffde
CW
137
138 /**
6a488035
TO
139 * Store the line items if price set used.
140 */
141 public $_lineItems;
142
d77a0a58 143 /**
100fef9d 144 * Line item
d77a0a58
EM
145 * @todo explain why we use lineItem & lineItems
146 * @var array
147 */
148 public $_lineItem;
149
17db9f82 150 /**
efe42cdc 151 * @var array soft credit info
17db9f82
KJ
152 */
153 public $_softCreditInfo;
154
6a488035 155 protected $_formType;
efe42cdc 156
1421174e 157 public $_honoreeProfileType;
6a488035 158
459091e1 159 /**
100fef9d 160 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
459091e1
EM
161 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
162 *
163 * @var array
164 */
353ffa53 165 public $_paymentFields = array();
4691b077 166 /**
28a4070b 167 * Logged in user's email.
4691b077
EM
168 * @var string
169 */
170 public $userEmail;
171
172 /**
173 * Price set ID
174 * @var integer
175 */
176 public $_priceSetId;
177
4691b077
EM
178 /**
179 * Price set as an array
180 * @var array
181 */
182 public $_priceSet;
183
d77a0a58
EM
184 /**
185 * User display name
186 *
187 * @var string
188 */
189 public $userDisplayName;
353ffa53 190
7e5961cf
EM
191 /**
192 * Status message to be shown to the user.
193 *
3e6a1f4a 194 * @var array
7e5961cf 195 */
3e6a1f4a 196 protected $statusMessage = array();
7e5961cf
EM
197
198 /**
199 * Status message title to be shown to the user.
200 *
201 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
202 * although this might not be a good fit with the broad range of processors.
203 *
204 * @var string
205 */
206 protected $statusMessageTitle;
207
6a488035 208 /**
22ab45ae 209 * Set variables up before form is built.
6a488035
TO
210 */
211 public function preProcess() {
28a4070b 212 // Check permission for action.
6a488035 213 if (!CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
0499b0ad 214 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
6a488035 215 }
6a488035 216
42e8b05c
EM
217 parent::preProcess();
218
6a488035
TO
219 $this->_formType = CRM_Utils_Array::value('formType', $_GET);
220
28a4070b 221 // Get price set id.
6a488035
TO
222 $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
223 $this->set('priceSetId', $this->_priceSetId);
224 $this->assign('priceSetId', $this->_priceSetId);
225
28a4070b 226 // Get the pledge payment id
6a488035
TO
227 $this->_ppID = CRM_Utils_Request::retrieve('ppid', 'Positive', $this);
228
6a488035
TO
229 $this->assign('action', $this->_action);
230
28a4070b 231 // Get the contribution id if update
6a488035
TO
232 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
233 if (!empty($this->_id)) {
234 $this->assign('contribID', $this->_id);
235 }
236
237 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
238 $this->assign('context', $this->_context);
239
240 $this->_compId = CRM_Utils_Request::retrieve('compId', 'Positive', $this);
241
242 $this->_compContext = CRM_Utils_Request::retrieve('compContext', 'String', $this);
243
244 //set the contribution mode.
245 $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
246
247 $this->assign('contributionMode', $this->_mode);
459091e1
EM
248 if ($this->_action & CRM_Core_Action::DELETE) {
249 return;
250 }
6a488035
TO
251
252 $this->assign('showCheckNumber', TRUE);
253
254 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
cc984198 255 $this->assignPaymentRelatedVariables();
6a488035 256
d77a0a58 257 if (in_array('CiviPledge', CRM_Core_Config::singleton()->enableComponents) && !$this->_formType) {
6a488035
TO
258 $this->preProcessPledge();
259 }
260
d5397f2f
PJ
261 if ($this->_id) {
262 $this->showRecordLinkMesssage($this->_id);
263 }
6a488035
TO
264 $this->_values = array();
265
bf56a083 266 // Current contribution id.
6a488035
TO
267 if ($this->_id) {
268 $this->assignPremiumProduct($this->_id);
269 $this->buildValuesAndAssignOnline_Note_Type($this->_id, $this->_values);
270 }
271
272 // when custom data is included in this page
a7488080 273 if (!empty($_POST['hidden_custom'])) {
6a488035
TO
274 $this->applyCustomData('Contribution', CRM_Utils_Array::value('financial_type_id', $_POST), $this->_id);
275 }
276
277 $this->_lineItems = array();
278 if ($this->_id) {
279 if (!empty($this->_compId) && $this->_compContext == 'participant') {
280 $this->assign('compId', $this->_compId);
281 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_compId);
282 }
283 else {
0b71718c 284 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution', 1, TRUE, TRUE);
6a488035
TO
285 }
286 empty($lineItem) ? NULL : $this->_lineItems[] = $lineItem;
287 }
288
289 $this->assign('lineItem', empty($this->_lineItems) ? FALSE : $this->_lineItems);
290
291 // Set title
e2046b33
CW
292 if ($this->_mode) {
293 $this->setPageTitle($this->_ppID ? ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
294 }
295 else {
296 $this->setPageTitle($this->_ppID ? ts('Pledge Payment') : ts('Contribution'));
6a488035 297 }
1421174e 298
299 if ($this->_id) {
300 CRM_Contribute_Form_SoftCredit::preprocess($this);
301 }
6a488035
TO
302 }
303
28a4070b
EM
304 /**
305 * Set default values.
306 *
307 * @return array
308 */
00be9182 309 public function setDefaultValues() {
6a488035
TO
310
311 $defaults = $this->_values;
312
bf56a083 313 // Set defaults for pledge payment.
6a488035
TO
314 if ($this->_ppID) {
315 $defaults['total_amount'] = CRM_Utils_Array::value('scheduled_amount', $this->_pledgeValues['pledgePayment']);
6a488035
TO
316 $defaults['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $this->_pledgeValues);
317 $defaults['currency'] = CRM_Utils_Array::value('currency', $this->_pledgeValues);
318 $defaults['option_type'] = 1;
319 }
320
6a488035
TO
321 if ($this->_action & CRM_Core_Action::DELETE) {
322 return $defaults;
323 }
324
7fe22c48
EM
325 $defaults['frequency_interval'] = 1;
326 $defaults['frequency_unit'] = 'month';
327
bf56a083 328 // Set soft credit defaults.
17db9f82 329 CRM_Contribute_Form_SoftCredit::setDefaultValues($defaults, $this);
dfbad3f7 330
6a488035
TO
331 if ($this->_mode) {
332 $config = CRM_Core_Config::singleton();
bf56a083 333 // Set default country from config if no country set.
a7488080 334 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
6a488035
TO
335 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
336 }
5a230af7 337
a7488080 338 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
6a488035
TO
339 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
340 }
341
cc8ff73d
DG
342 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
343 $defaults = array_merge($defaults, $billingDefaults);
6a488035
TO
344 }
345
346 if ($this->_id) {
347 $this->_contactID = $defaults['contact_id'];
348 }
5a230af7 349
bf56a083 350 // Set $newCredit variable in template to control whether link to credit card mode is included.
9be1374d 351 $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
5a230af7 352
bf56a083 353 // Fix the display of the monetary value, CRM-4038.
6a488035 354 if (isset($defaults['total_amount'])) {
049db839 355 if (!empty($defaults['tax_amount'])) {
b6f65362 356 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
357 if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
358 $defaults['total_amount'] = CRM_Utils_Money::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
359 }
049db839 360 }
361 else {
362 $defaults['total_amount'] = CRM_Utils_Money::format($defaults['total_amount'], NULL, '%a');
363 }
6a488035
TO
364 }
365
366 if (isset($defaults['non_deductible_amount'])) {
367 $defaults['non_deductible_amount'] = CRM_Utils_Money::format($defaults['non_deductible_amount'], NULL, '%a');
368 }
369
370 if (isset($defaults['fee_amount'])) {
371 $defaults['fee_amount'] = CRM_Utils_Money::format($defaults['fee_amount'], NULL, '%a');
372 }
373
374 if (isset($defaults['net_amount'])) {
375 $defaults['net_amount'] = CRM_Utils_Money::format($defaults['net_amount'], NULL, '%a');
376 }
377
378 if ($this->_contributionType) {
379 $defaults['financial_type_id'] = $this->_contributionType;
380 }
133e2c99 381
a7488080 382 if (empty($defaults['payment_instrument_id'])) {
d96cf288
DG
383 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
384 }
6a488035 385
a7488080 386 if (!empty($defaults['is_test'])) {
6a488035
TO
387 $this->assign('is_test', TRUE);
388 }
389
6a488035 390 $this->assign('showOption', TRUE);
bf56a083 391 // For Premium section.
6a488035
TO
392 if ($this->_premiumID) {
393 $this->assign('showOption', FALSE);
394 $options = isset($this->_options[$this->_productDAO->product_id]) ? $this->_options[$this->_productDAO->product_id] : "";
395 if (!$options) {
396 $this->assign('showOption', TRUE);
397 }
398 $options_key = CRM_Utils_Array::key($this->_productDAO->product_option, $options);
399 if ($options_key) {
400 $defaults['product_name'] = array($this->_productDAO->product_id, trim($options_key));
401 }
402 else {
403 $defaults['product_name'] = array($this->_productDAO->product_id);
404 }
405 if ($this->_productDAO->fulfilled_date) {
406 list($defaults['fulfilled_date']) = CRM_Utils_Date::setDateDefaults($this->_productDAO->fulfilled_date);
407 }
408 }
409
410 if (isset($this->userEmail)) {
411 $this->assign('email', $this->userEmail);
412 }
413
a7488080 414 if (!empty($defaults['is_pay_later'])) {
6a488035
TO
415 $this->assign('is_pay_later', TRUE);
416 }
417 $this->assign('contribution_status_id', CRM_Utils_Array::value('contribution_status_id', $defaults));
418
22ab45ae
EM
419 $dates = array(
420 'receive_date',
421 'receipt_date',
422 'cancel_date',
423 'thankyou_date',
28a4070b 424 );
6a488035 425 foreach ($dates as $key) {
a7488080 426 if (!empty($defaults[$key])) {
006389de
TO
427 list($defaults[$key], $defaults[$key . '_time'])
428 = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value($key, $defaults), 'activityDateTime');
6a488035
TO
429 }
430 }
431
8cc574cf 432 if (!$this->_id && empty($defaults['receive_date'])) {
6a488035
TO
433 list($defaults['receive_date'],
434 $defaults['receive_date_time']
435 ) = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
436 }
437
438 $this->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $defaults),
439 CRM_Utils_Array::value('receive_date_time', $defaults)
440 ));
441 $currency = CRM_Utils_Array::value('currency', $defaults);
442 $this->assign('currency', $currency);
bf56a083 443 // Hack to get currency info to the js layer. CRM-11440.
6a488035
TO
444 CRM_Utils_Money::format(1);
445 $this->assign('currencySymbol', CRM_Utils_Array::value($currency, CRM_Utils_Money::$_currencySymbols));
446 $this->assign('totalAmount', CRM_Utils_Array::value('total_amount', $defaults));
447
bf56a083 448 // Inherit campaign from pledge.
8cc574cf 449 if ($this->_ppID && !empty($this->_pledgeValues['campaign_id'])) {
6a488035
TO
450 $defaults['campaign_id'] = $this->_pledgeValues['campaign_id'];
451 }
452
453 $this->_defaults = $defaults;
454 return $defaults;
455 }
456
457 /**
fe482240 458 * Build the form object.
6a488035
TO
459 */
460 public function buildQuickForm() {
e3fa3fea 461 // FIXME: This probably needs to be done in preprocess
66af7c48
PN
462 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
463 && $this->_action & CRM_Core_Action::UPDATE
464 && CRM_Utils_Array::value('financial_type_id', $this->_values)
465 ) {
e3fa3fea 466 $financialTypeID = CRM_Contribute_PseudoConstant::financialType($this->_values['financial_type_id']);
59ccc8cd 467 CRM_Financial_BAO_FinancialType::checkPermissionedLineItems($this->_id, 'edit');
e3fa3fea
E
468 if (!CRM_Core_Permission::check('edit contributions of type ' . $financialTypeID)) {
469 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
470 }
471 }
5032bf07 472 $allPanes = array();
5e27919e 473 $recurJs = NULL;
6daab7fa 474 //tax rate from financialType
a1e457ff 475 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
049db839 476 $this->assign('currencies', json_encode(CRM_Core_OptionGroup::values('currencies_enabled')));
6a488035
TO
477
478 // build price set form.
479 $buildPriceSet = FALSE;
353ffa53 480 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
03b412ae 481 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
95f2107c 482 $this->assign('invoicing', $invoicing);
a32709be 483
03b412ae
PB
484 // display tax amount on edit contribution page
485 if ($invoicing && $this->_action & CRM_Core_Action::UPDATE && isset($this->_values['tax_amount'])) {
a32709be
PB
486 $this->assign('totalTaxAmount', $this->_values['tax_amount']);
487 }
488
6a488035 489 if (empty($this->_lineItems) &&
8cc574cf 490 ($this->_priceSetId || !empty($_POST['price_set_id']))
6a488035
TO
491 ) {
492 $buildPriceSet = TRUE;
493 $getOnlyPriceSetElements = TRUE;
494 if (!$this->_priceSetId) {
495 $this->_priceSetId = $_POST['price_set_id'];
496 $getOnlyPriceSetElements = FALSE;
497 }
498
499 $this->set('priceSetId', $this->_priceSetId);
9da8dc8c 500 CRM_Price_BAO_PriceSet::buildPriceSet($this);
6a488035
TO
501
502 // get only price set form elements.
503 if ($getOnlyPriceSetElements) {
504 return;
505 }
506 }
507 // use to build form during form rule.
508 $this->assign('buildPriceSet', $buildPriceSet);
509
6a488035
TO
510 $defaults = $this->_values;
511 $additionalDetailFields = array(
512 'note',
513 'thankyou_date',
514 'invoice_id',
515 'non_deductible_amount',
516 'fee_amount',
dfbad3f7 517 'net_amount',
6a488035
TO
518 );
519 foreach ($additionalDetailFields as $key) {
520 if (!empty($defaults[$key])) {
521 $defaults['hidden_AdditionalDetail'] = 1;
522 break;
523 }
524 }
525
6a488035
TO
526 if ($this->_productDAO) {
527 if ($this->_productDAO->product_id) {
528 $defaults['hidden_Premium'] = 1;
529 }
530 }
531
532 if ($this->_noteID &&
533 isset($this->_values['note'])
534 ) {
535 $defaults['hidden_AdditionalDetail'] = 1;
536 }
537
538 $paneNames = array(
539 ts('Additional Details') => 'AdditionalDetail',
6a488035
TO
540 );
541
542 //Add Premium pane only if Premium is exists.
543 $dao = new CRM_Contribute_DAO_Product();
544 $dao->is_active = 1;
545
546 if ($dao->find(TRUE)) {
547 $paneNames[ts('Premium Information')] = 'Premium';
548 }
549
6a488035 550 if ($this->_mode) {
225584c9 551 if (CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE) == TRUE) {
5e27919e 552 if (!empty($this->_recurPaymentProcessors)) {
4f3c361d 553 $buildRecurBlock = TRUE;
f231bf7f 554 if ($this->_ppID) {
4f3c361d
EM
555 // ppID denotes a pledge payment.
556 foreach ($this->_paymentProcessors as $processor) {
557 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
558 $buildRecurBlock = TRUE;
559 break;
560 }
561 $buildRecurBlock = FALSE;
562 }
563 }
564 if ($buildRecurBlock) {
565 CRM_Contribute_Form_Contribution_Main::buildRecur($this);
566 $this->setDefaults(array('is_recur' => 0));
567 $this->assign('buildRecurBlock', TRUE);
568 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
569 }
5e27919e 570 }
6a488035
TO
571 }
572 }
6a488035 573
6a488035 574 foreach ($paneNames as $name => $type) {
a5399a39 575 $allPanes[$name] = $this->generatePane($type, $defaults);
6a488035 576 }
5e27919e 577
6a488035
TO
578 $qfKey = $this->controller->_key;
579 $this->assign('qfKey', $qfKey);
580 $this->assign('allPanes', $allPanes);
6a488035 581
6c75c831 582 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
583
6a488035
TO
584 if ($this->_formType) {
585 $this->assign('formType', $this->_formType);
586 return;
587 }
588
589 $this->applyFilter('__ALL__', 'trim');
5a230af7 590
6a488035
TO
591 if ($this->_action & CRM_Core_Action::DELETE) {
592 $this->addButtons(array(
593 array(
594 'type' => 'next',
595 'name' => ts('Delete'),
596 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
597 'isDefault' => TRUE,
598 ),
599 array(
600 'type' => 'cancel',
21dfd5f5
TO
601 'name' => ts('Cancel'),
602 ),
6a488035
TO
603 )
604 );
605 return;
606 }
607
608 //need to assign custom data type and subtype to the template
609 $this->assign('customDataType', 'Contribution');
610 $this->assign('customDataSubType', $this->_contributionType);
611 $this->assign('entityID', $this->_id);
612
613 if ($this->_context == 'standalone') {
353ffa53
TO
614 $this->addEntityRef('contact_id', ts('Contact'), array(
615 'create' => TRUE,
acb1052e 616 'api' => array('extra' => array('email')),
353ffa53 617 ), TRUE);
6a488035
TO
618 }
619
620 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
e3fa3fea
E
621
622 // Check permissions for financial type first
a4ef4eac 623 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, 'add');
6a488035
TO
624
625 $financialType = $this->add('select', 'financial_type_id',
626 ts('Financial Type'),
e3fa3fea 627 array('' => ts('- select -')) + $financialTypes,
79ca865b
CW
628 TRUE,
629 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
6a488035 630 );
e3fa3fea 631
d77a0a58 632 $paymentInstrument = FALSE;
6a488035
TO
633 if (!$this->_mode) {
634 $paymentInstrument = $this->add('select', 'payment_instrument_id',
4db803dd 635 ts('Payment Method'),
6a488035 636 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
d96cf288 637 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
6a488035
TO
638 );
639 }
640
ce22fda6 641 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') + $attributes['trxn_id']);
6a488035
TO
642
643 //add receipt for offline contribution
644 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
645
646 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
647
648 $status = CRM_Contribute_PseudoConstant::contributionStatus();
649
650 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
651 $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
652 if ($this->_ppID) {
653 foreach (array(
654 'Cancelled',
655 'Failed',
21dfd5f5 656 'In Progress',
6a488035
TO
657 ) as $suppress) {
658 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
659 }
660 }
661 elseif ((!$this->_ppID && $this->_id) || !$this->_id) {
f73acc78
PN
662 $suppressFlag = FALSE;
663 if ($this->_id) {
664 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
665 if (CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails)) {
666 $suppressFlag = TRUE;
667 }
668 }
669 if (!$suppressFlag) {
670 foreach (array(
671 'Overdue',
21dfd5f5 672 'In Progress',
f73acc78
PN
673 ) as $suppress) {
674 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
675 }
676 }
677 else {
678 unset($status[CRM_Utils_Array::key('Overdue', $statusName)]);
6a488035
TO
679 }
680 }
b6545333 681
6a488035
TO
682 if ($this->_id) {
683 $contributionStatus = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id, 'contribution_status_id');
684 $name = CRM_Utils_Array::value($contributionStatus, $statusName);
d37ade2e 685 switch ($name) {
6a488035
TO
686 case 'Completed':
687 case 'Cancelled':
688 case 'Refunded':
f73acc78 689 unset($status[CRM_Utils_Array::key('In Progress', $statusName)]);
6a488035
TO
690 unset($status[CRM_Utils_Array::key('Pending', $statusName)]);
691 unset($status[CRM_Utils_Array::key('Failed', $statusName)]);
692 break;
ea100cb5 693
6a488035 694 case 'Pending':
f73acc78 695 case 'In Progress':
6a488035
TO
696 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
697 break;
ea100cb5 698
6a488035 699 case 'Failed':
d37ade2e 700 foreach (array(
701 'Pending',
702 'Refunded',
703 'Completed',
f73acc78 704 'In Progress',
21dfd5f5 705 'Cancelled',
d37ade2e 706 ) as $suppress) {
6a488035
TO
707 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
708 }
709 break;
710 }
d37ade2e 711 }
712 else {
6a488035
TO
713 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
714 }
715
716 $this->add('select', 'contribution_status_id',
717 ts('Contribution Status'),
718 $status,
719 FALSE
720 );
721
722 // add various dates
723 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
724
725 if ($this->_online) {
726 $this->assign('hideCalender', TRUE);
727 }
728 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
729
730 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
731 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
732
733 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
734
6a488035
TO
735 $element = $this->add('select',
736 'payment_processor_id',
737 ts('Payment Processor'),
738 $this->_processors,
739 NULL,
740 $recurJs
741 );
742
743 if ($this->_online) {
744 $element->freeze();
745 }
e02d7e96 746
6a488035
TO
747 $totalAmount = NULL;
748 if (empty($this->_lineItems)) {
749 $buildPriceSet = FALSE;
9da8dc8c 750 $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute');
6a488035
TO
751 if (!empty($priceSets) && !$this->_ppID) {
752 $buildPriceSet = TRUE;
753 }
754
755 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
756 // and if we already have line items for that participant. CRM-5095
757 if ($buildPriceSet && $this->_id) {
758 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
759 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
760 $this->_id,
761 'id',
762 'contribution_id'
763 );
764 if ($pledgePaymentId) {
765 $buildPriceSet = FALSE;
766 }
767 if ($participantID = CRM_Utils_Array::value('participant', $componentDetails)) {
768 $participantLI = CRM_Price_BAO_LineItem::getLineItems($participantID);
769 if (!CRM_Utils_System::isNull($participantLI)) {
770 $buildPriceSet = FALSE;
771 }
772 }
773 }
774
775 $hasPriceSets = FALSE;
776 if ($buildPriceSet) {
777 $hasPriceSets = TRUE;
6a3d8d2d
WA
778 // CRM-16451: set financial type of 'Price Set' in back office contribution
779 // instead of selecting manually
780 $financialTypeIds = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
6a488035
TO
781 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
782 array(
21dfd5f5 783 '' => ts('Choose price set'),
6a488035 784 ) + $priceSets,
d6d7af07 785 NULL, array('onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");")
5a230af7 786 );
6a488035
TO
787 if ($this->_online && !($this->_action & CRM_Core_Action::UPDATE)) {
788 $element->freeze();
789 }
790 }
791 $this->assign('hasPriceSets', $hasPriceSets);
792 $currencyFreeze = FALSE;
793 if (!($this->_action & CRM_Core_Action::UPDATE)) {
d37ade2e 794 if ($this->_online || $this->_ppID) {
795 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
796 'READONLY' => TRUE,
21dfd5f5 797 'style' => "background-color:#EBECE4",
d37ade2e 798 ));
799 $optionTypes = array(
800 '1' => ts('Adjust Pledge Payment Schedule?'),
801 '2' => ts('Adjust Total Pledge Amount?'),
802 );
803 $this->addRadio('option_type',
804 NULL,
805 $optionTypes,
806 array(), '<br/>'
807 );
808
809 $currencyFreeze = TRUE;
810 }
6a488035
TO
811 }
812
813 $totalAmount = $this->addMoney('total_amount',
814 ts('Total Amount'),
815 ($hasPriceSets) ? FALSE : TRUE,
816 $attributes['total_amount'],
817 TRUE, 'currency', NULL, $currencyFreeze
818 );
819 }
820
821 $this->add('text', 'source', ts('Source'), CRM_Utils_Array::value('source', $attributes));
822
161a2fe7 823 // CRM-7362 --add campaigns.
6a488035
TO
824 CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
825
0baed70b 826 CRM_Contribute_Form_SoftCredit::buildQuickForm($this);
0baed70b 827
6a488035
TO
828 $js = NULL;
829 if (!$this->_mode) {
830 $js = array('onclick' => "return verify( );");
831 }
832
833 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
834 'mailing_backend'
835 );
836 $this->assign('outBound_option', $mailingInfo['outBound_option']);
837
838 $this->addButtons(array(
839 array(
840 'type' => 'upload',
841 'name' => ts('Save'),
842 'js' => $js,
21dfd5f5 843 'isDefault' => TRUE,
6a488035
TO
844 ),
845 array(
846 'type' => 'upload',
847 'name' => ts('Save and New'),
848 'js' => $js,
21dfd5f5 849 'subName' => 'new',
6a488035
TO
850 ),
851 array(
852 'type' => 'cancel',
21dfd5f5 853 'name' => ts('Cancel'),
6a488035
TO
854 ),
855 )
856 );
857
858 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
859 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
860 if ($this->_id && $this->_values['contribution_status_id'] == array_search('Cancelled', $statusName)) {
5a230af7 861 if ($totalAmount) {
6a488035
TO
862 $totalAmount->freeze();
863 }
864 $checkNumber->freeze();
865 $paymentInstrument->freeze();
866 $trxnId->freeze();
867 $financialType->freeze();
868 }
869
b6f65362 870 // if contribution is related to membership or participant freeze Financial Type, Amount
871 if ($this->_id && isset($this->_values['tax_amount'])) {
872 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
873 if (CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails)) {
b5527a9a 874 if ($totalAmount) {
a13f3d8c 875 $totalAmount->freeze();
b5527a9a 876 }
b6f65362 877 $financialType->freeze();
b6f65362 878 $this->assign('freezeFinancialType', TRUE);
879 }
880 }
881
6a488035
TO
882 if ($this->_action & CRM_Core_Action::VIEW) {
883 $this->freeze();
884 }
885 }
886
887 /**
fe482240 888 * Global form rule.
6a488035 889 *
014c4014
TO
890 * @param array $fields
891 * The input form values.
892 * @param array $files
893 * The uploaded files if any.
2a6da8d7
EM
894 * @param $self
895 *
72b3a70c
CW
896 * @return bool|array
897 * true if no errors, else array of errors
6a488035 898 */
1cf3816f 899 public static function formRule($fields, $files, $self) {
6a488035 900 $errors = array();
161a2fe7 901 // Check for Credit Card Contribution.
6a488035
TO
902 if ($self->_mode) {
903 if (empty($fields['payment_processor_id'])) {
904 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
905 }
34089500 906 else {
907 // validate payment instrument (e.g. credit card number)
908 CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, $self);
909 }
6a488035
TO
910 }
911
161a2fe7 912 // Do the amount validations.
a7488080 913 if (empty($fields['total_amount']) && empty($self->_lineItems)) {
6a488035 914 if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) {
9da8dc8c 915 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $fields, $errors);
6a488035
TO
916 }
917 }
918
b326919b 919 $softErrors = CRM_Contribute_Form_SoftCredit::formRule($fields, $errors, $self);
d37ade2e 920
3256b416
JM
921 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) || !empty($fields['fee_amount']))) {
922 $sum = CRM_Utils_Rule::cleanMoney($fields['net_amount']) + CRM_Utils_Rule::cleanMoney($fields['fee_amount']);
f21310d8 923 // For taxable contribution we need to deduct taxable amount from
924 // (net amount + fee amount) before comparing it with total amount
925 if (!empty($self->_values['tax_amount'])) {
926 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($self->_id);
927 if (!(CRM_Utils_Array::value('membership', $componentDetails) ||
928 CRM_Utils_Array::value('participant', $componentDetails))
929 ) {
930 $sum = CRM_Utils_Money::format($sum - $self->_values['tax_amount'], NULL, '%a');
931 }
932 }
3256b416 933 if (CRM_Utils_Rule::cleanMoney($fields['total_amount']) != $sum) {
6a488035
TO
934 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
935 }
936 }
577d1236
WA
937
938 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
939 CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors);
940
161a2fe7 941 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
58d33659
PN
942 if (($self->_action & CRM_Core_Action::UPDATE)
943 && $self->_id
944 && $self->_values['contribution_status_id'] != $fields['contribution_status_id']
945 ) {
6a488035
TO
946 CRM_Contribute_BAO_Contribution::checkStatusValidation($self->_values, $fields, $errors);
947 }
4d47ad17 948 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
58d33659
PN
949 if (($self->_action & CRM_Core_Action::UPDATE)
950 && $self->_id
951 && $self->_values['financial_type_id'] != $fields['financial_type_id']
952 ) {
4d47ad17
PN
953 CRM_Contribute_BAO_Contribution::checkFinancialTypeChange(NULL, $self->_id, $errors);
954 }
6a488035 955 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
34089500 956 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution::validateFinancialType($fields['financial_type_id'])) {
51fa20cb 957 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
6a488035 958 }
133e2c99 959
7272e4fa
DG
960 // $trxn_id must be unique CRM-13919
961 if (!empty($fields['trxn_id'])) {
962 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
963 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
964 if ($self->_id) {
353ffa53 965 $queryParams[2] = array((int) $self->_id, 'Integer');
7272e4fa
DG
966 $query .= ' and id !=%2';
967 }
968 $tCnt = CRM_Core_DAO::singleValueQuery($query, $queryParams);
969 if ($tCnt) {
970 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
133e2c99 971 }
7272e4fa 972 }
d37ade2e 973
ac0c89ed 974 $errors = array_merge($errors, $softErrors);
6a488035
TO
975 return $errors;
976 }
977
978 /**
fe482240 979 * Process the form submission.
6a488035
TO
980 */
981 public function postProcess() {
6a488035
TO
982 if ($this->_action & CRM_Core_Action::DELETE) {
983 CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
c1cc3e0c 984 CRM_Core_Session::singleton()->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
6a488035
TO
985 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
986 ));
987 return;
988 }
77c081c2 989 // Get the submitted form values.
6a488035 990 $submittedValues = $this->controller->exportValues($this->_name);
7758bd2b
EM
991
992 try {
7758bd2b
EM
993 $contribution = $this->submit($submittedValues, $this->_action, $this->_ppID);
994 }
995 catch (PaymentProcessorException $e) {
996 // Set the contribution mode.
997 $urlParams = "action=add&cid={$this->_contactID}";
998 if ($this->_mode) {
999 $urlParams .= "&mode={$this->_mode}";
1000 }
1001 if (!empty($this->_ppID)) {
1002 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1003 }
1004
1005 CRM_Core_Error::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
1006 }
f75f0921
EM
1007 $session = CRM_Core_Session::singleton();
1008 $buttonName = $this->controller->getButtonName();
1009 if ($this->_context == 'standalone') {
1010 if ($buttonName == $this->getButtonName('upload', 'new')) {
1011 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add',
1012 'reset=1&action=add&context=standalone'
1013 ));
6a488035 1014 }
f75f0921
EM
1015 else {
1016 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1017 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1018 ));
1019 }
1020 }
1021 elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) {
1022 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1023 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1024 ));
1025 }
1026 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1027 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1028 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1029 ));
6a488035
TO
1030 }
1031
f75f0921
EM
1032 //store contribution ID if not yet set (on create)
1033 if (empty($this->_id) && !empty($contribution->id)) {
1034 $this->_id = $contribution->id;
6a488035 1035 }
f75f0921 1036 }
6a488035 1037
f75f0921
EM
1038 /**
1039 * Process credit card payment.
1040 *
1041 * @param array $submittedValues
1042 * @param array $lineItem
456b0145 1043 *
7126b55c
EM
1044 * @param int $contactID
1045 * Contact ID
1046 *
456b0145 1047 * @return bool|\CRM_Contribute_DAO_Contribution
f8453bef 1048 * @throws \CRM_Core_Exception
7758bd2b 1049 * @throws \Civi\Payment\Exception\PaymentProcessorException
456b0145 1050 */
7126b55c 1051 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
549cf0b9 1052 $isTest = ($this->_mode == 'test') ? 1 : 0;
f75f0921 1053 // CRM-12680 set $_lineItem if its not set
bf4253e7
EM
1054 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1055 // It would be better to pass line item out to functions than $this->_lineItem as
1056 // we don't know what is being changed where.
f75f0921
EM
1057 if (empty($this->_lineItem) && !empty($lineItem)) {
1058 $this->_lineItem = $lineItem;
6a488035 1059 }
6a488035 1060
bf4253e7
EM
1061 $this->_paymentObject = Civi\Payment\System::singleton()->getById($submittedValues['payment_processor_id']);
1062 $this->_paymentProcessor = $this->_paymentObject->getPaymentProcessor();
c52884b2 1063
7758bd2b
EM
1064 // Set source if not set
1065 if (empty($submittedValues['source'])) {
1066 $userID = CRM_Core_Session::singleton()->get('userID');
1067 $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1068 'sort_name'
1069 );
1070 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1071 }
1072
3b8e6c3f 1073 $params = $submittedValues;
1074 $this->_params = array_merge($this->_params, $submittedValues);
77e18ec7 1075
bf4253e7
EM
1076 // Mapping requiring documentation.
1077 $this->_params['payment_processor'] = $submittedValues['payment_processor_id'];
1078
f75f0921 1079 $now = date('YmdHis');
5a230af7 1080
f75f0921
EM
1081 // we need to retrieve email address
1082 if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1083 list($this->userDisplayName,
1084 $this->userEmail
7126b55c 1085 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
f75f0921 1086 $this->assign('displayName', $this->userDisplayName);
6a488035 1087 }
6a488035 1088
3b8e6c3f 1089 $this->_contributorEmail = $this->userEmail;
1090 $this->_contributorContactID = $contactID;
1091 $this->processBillingAddress();
f75f0921
EM
1092 if (!empty($params['source'])) {
1093 unset($params['source']);
6a488035 1094 }
c52884b2 1095
f75f0921
EM
1096 $this->_params['amount'] = $this->_params['total_amount'];
1097 $this->_params['amount_level'] = 0;
e47238e5 1098 $this->_params['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
f75f0921
EM
1099 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
1100 $this->_params,
1101 CRM_Core_Config::singleton()->defaultCurrency
1102 );
aefd7f6b 1103
f75f0921
EM
1104 if (!empty($this->_params['receive_date'])) {
1105 $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']);
6a488035 1106 }
6a488035 1107
f75f0921
EM
1108 $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
1109 $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
1110 $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
3f662d9d 1111
f75f0921
EM
1112 //Add common data to formatted params
1113 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
6a488035 1114
f75f0921
EM
1115 if (empty($this->_params['invoice_id'])) {
1116 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1117 }
1118 else {
1119 $this->_params['invoiceID'] = $this->_params['invoice_id'];
1120 }
6a488035 1121
f75f0921
EM
1122 // At this point we've created a contact and stored its address etc
1123 // all the payment processors expect the name and address to be in the
1124 // so we copy stuff over to first_name etc.
1125 $paymentParams = $this->_params;
7126b55c 1126 $paymentParams['contactID'] = $contactID;
f75f0921 1127 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
6a488035 1128
67256e0c
EM
1129 $financialType = new CRM_Financial_DAO_FinancialType();
1130 $financialType->id = $params['financial_type_id'];
6a488035 1131
f75f0921
EM
1132 // Add some financial type details to the params list
1133 // if folks need to use it.
67256e0c 1134 $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $financialType->name;
f75f0921 1135 $paymentParams['contributionPageID'] = NULL;
6a488035 1136
f75f0921
EM
1137 if (!empty($this->_params['is_email_receipt'])) {
1138 $paymentParams['email'] = $this->userEmail;
1139 $paymentParams['is_email_receipt'] = 1;
1140 }
1141 else {
1142 $paymentParams['is_email_receipt'] = 0;
1143 $this->_params['is_email_receipt'] = 0;
1144 }
1145 if (!empty($this->_params['receive_date'])) {
1146 $paymentParams['receive_date'] = $this->_params['receive_date'];
1147 }
6a488035 1148
f75f0921 1149 $this->_params['receive_date'] = $now;
6a488035 1150
f75f0921
EM
1151 if (!empty($this->_params['is_email_receipt'])) {
1152 $this->_params['receipt_date'] = $now;
1153 }
1154 else {
1155 $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'],
1156 $params['receipt_date_time'], TRUE
1157 );
1158 }
6a488035 1159
f75f0921 1160 $this->set('params', $this->_params);
7758bd2b 1161
f75f0921 1162 $this->assign('receive_date', $this->_params['receive_date']);
6a488035 1163
f75f0921
EM
1164 // Result has all the stuff we need
1165 // lets archive it to a financial transaction
67256e0c 1166 if ($financialType->is_deductible) {
f75f0921
EM
1167 $this->assign('is_deductible', TRUE);
1168 $this->set('is_deductible', TRUE);
1169 }
3febe800 1170 $contributionParams = array(
1171 'contact_id' => $contactID,
1172 'line_item' => $lineItem,
1173 'is_test' => $isTest,
1174 'campaign_id' => CRM_Utils_Array::value('campaign_id', $this->_params),
1175 'contribution_page_id' => CRM_Utils_Array::value('contribution_page_id', $this->_params),
1176 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)),
1177 'thankyou_date' => CRM_Utils_Array::value('thankyou_date', $this->_params),
1178 );
1179
1180 if (empty($paymentParams['is_pay_later'])) {
1181 // @todo look up payment_instrument_id on payment processor table.
1182 $contributionParams['payment_instrument_id'] = 1;
1183 }
6a488035 1184
ba013eea 1185 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this,
7758bd2b
EM
1186 $this->_params,
1187 NULL,
3febe800 1188 $contributionParams,
7758bd2b 1189 $financialType,
7758bd2b 1190 FALSE,
7758bd2b
EM
1191 $this->_bltID
1192 );
6a488035 1193
7758bd2b
EM
1194 $paymentParams['contributionID'] = $contribution->id;
1195 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
1196 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1197 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
6a488035 1198
7758bd2b
EM
1199 if ($paymentParams['amount'] > 0.0) {
1200 // force a re-get of the payment processor in case the form changed it, CRM-7179
9d8f43b1
EM
1201 // NOTE - I expect this is obsolete.
1202 $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
7758bd2b
EM
1203 try {
1204 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
1205 $result = $payment->doPayment($paymentParams, 'contribute');
1206 $this->assign('trxn_id', $result['trxn_id']);
1207 $contribution->trxn_id = $result['trxn_id'];
1208 /* Our scenarios here are
1209 * 1) the payment failed & an Exception should have been thrown
1210 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1211 * with a delayed start)
1212 * 3) the payment succeeded with an immediate payment.
1213 *
7c85dc65 1214 * The doPayment function ensures that payment_status_id is always set
7758bd2b
EM
1215 * as historically we have had to guess from the context - ie doDirectPayment
1216 * = error or success, unless it is a recurring contribution in which case it is pending.
1217 */
7c85dc65 1218 if ($result['payment_status_id'] == array_search('Completed', $statuses)) {
760278d3
EM
1219 try {
1220 civicrm_api3('contribution', 'completetransaction', array(
1221 'id' => $contribution->id,
1222 'trxn_id' => $result['trxn_id'],
1223 'payment_processor_id' => $this->_paymentProcessor['id'],
1224 'is_transactional' => FALSE,
22e39333 1225 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
760278d3
EM
1226 ));
1227 // This has now been set to 1 in the DB - declare it here also
1228 $contribution->contribution_status_id = 1;
1229 }
1230 catch (CiviCRM_API3_Exception $e) {
1231 if ($e->getErrorCode() != 'contribution_completed') {
1232 throw new CRM_Core_Exception('Failed to update contribution in database');
1233 }
1234 }
7758bd2b
EM
1235 }
1236 else {
1237 // Save the trxn_id.
1238 $contribution->save();
1239 }
1240 }
1241 catch (PaymentProcessorException $e) {
06d062ce 1242 CRM_Contribute_BAO_Contribution::failPayment($contribution->id, $paymentParams['contactID'], $e->getMessage());
7758bd2b
EM
1243 throw new PaymentProcessorException($e->getMessage());
1244 }
1245 }
f75f0921 1246 // Send receipt mail.
e390a377 1247 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
f75f0921
EM
1248 if ($contribution->id && !empty($this->_params['is_email_receipt'])) {
1249 $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
7126b55c 1250 $this->_params['contact_id'] = $contactID;
f75f0921 1251 $this->_params['contribution_id'] = $contribution->id;
c52884b2 1252 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE)) {
3e6a1f4a 1253 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
6a488035 1254 }
28d44c9f 1255 }
c52884b2 1256
5e27919e 1257 return $contribution;
6a488035 1258 }
5a230af7 1259
f75f0921
EM
1260 /**
1261 * Generate the data to construct a snippet based pane.
1262 *
1263 * This form also assigns the showAdditionalInfo var based on historical code.
1264 * This appears to mean 'there is a pane to show'.
1265 *
1266 * @param string $type
1267 * Type of Pane - this is generally used to determine the function name used to build it
1268 * - e.g CreditCard, AdditionalDetail
1269 * @param array $defaults
1270 *
1271 * @return array
1272 * We aim to further refactor & simplify this but currently
1273 * - the panes array
1274 * - should additional info be shown?
1275 */
1276 protected function generatePane($type, $defaults) {
1277 $urlParams = "snippet=4&formType={$type}";
1278 if ($this->_mode) {
1279 $urlParams .= "&mode={$this->_mode}";
6a488035
TO
1280 }
1281
f75f0921
EM
1282 $open = 'false';
1283 if ($type == 'CreditCard' ||
1284 $type == 'DirectDebit'
1285 ) {
1286 $open = 'true';
6a488035 1287 }
6a488035 1288
f75f0921
EM
1289 $pane = array(
1290 'url' => CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams),
1291 'open' => $open,
1292 'id' => $type,
6a488035 1293 );
6a488035 1294
f75f0921
EM
1295 // See if we need to include this paneName in the current form.
1296 if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) ||
1297 CRM_Utils_Array::value("hidden_{$type}", $defaults)
1298 ) {
1299 $this->assign('showAdditionalInfo', TRUE);
1300 $pane['open'] = 'true';
6a488035
TO
1301 }
1302
f75f0921
EM
1303 if ($type == 'CreditCard' || $type == 'DirectDebit') {
1304 // @todo would be good to align tpl name with form name...
1305 // @todo document why this hidden variable is required.
1306 $this->add('hidden', 'hidden_' . $type, 1);
1307 return $pane;
6a488035
TO
1308 }
1309 else {
f75f0921
EM
1310 $additionalInfoFormFunction = 'build' . $type;
1311 CRM_Contribute_Form_AdditionalInfo::$additionalInfoFormFunction($this);
1312 return $pane;
6a488035 1313 }
f75f0921 1314 }
6a488035 1315
f75f0921
EM
1316 /**
1317 * Wrapper for unit testing the post process submit function.
1318 *
1319 * (If we expose through api we can get default additions 'for free').
1320 *
1321 * @param array $params
5e27919e 1322 * @param int $action
39f47c0d
EM
1323 * @param string|null $creditCardMode
1324 *
1325 * @throws \CiviCRM_API3_Exception
f75f0921 1326 */
39f47c0d 1327 public function testSubmit($params, $action, $creditCardMode = NULL) {
f75f0921
EM
1328 $defaults = array(
1329 'soft_credit_contact_id' => array(),
1330 'receipt_date' => '',
1331 'receipt_date_time' => '',
1332 'cancel_date' => '',
1333 'cancel_date_time' => '',
43bf07d6 1334 'hidden_Premium' => 1,
f75f0921 1335 );
739a8336 1336 $this->_bltID = 5;
5e27919e
EM
1337 if (!empty($params['id'])) {
1338 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1339 'id' => $params['id'],
1340 ));
55e55e84 1341 $this->_id = $params['id'];
5e27919e
EM
1342 }
1343 else {
1344 $existingContribution = array();
1345 }
1346
1347 $this->_defaults['contribution_status_id'] = CRM_Utils_Array::value('contribution_status_id',
1348 $existingContribution
1349 );
1350
1351 $this->_defaults['total_amount'] = CRM_Utils_Array::value('total_amount',
1352 $existingContribution
1353 );
6a488035 1354
39f47c0d
EM
1355 if ($creditCardMode) {
1356 $this->_mode = $creditCardMode;
1357 }
1358
1359 // Required because processCreditCard calls set method on this.
1360 $_SERVER['REQUEST_METHOD'] = 'GET';
1361 $this->controller = new CRM_Core_Controller();
1362
3e6a1f4a
EM
1363 CRM_Contribute_Form_AdditionalInfo::buildPremium($this);
1364
39f47c0d 1365 $this->_fields = array();
31760f81 1366 $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array::value('pledge_payment_id', $params));
43bf07d6 1367
f75f0921 1368 }
c1cc3e0c 1369
f75f0921
EM
1370 /**
1371 * @param array $submittedValues
1372 *
bdbc1044
EM
1373 * @param int $action
1374 * Action constant
1375 * - CRM_Core_Action::UPDATE
1376 *
5e27919e
EM
1377 * @param $pledgePaymentID
1378 *
f75f0921
EM
1379 * @return array
1380 * @throws \Exception
1381 */
31760f81 1382 protected function submit($submittedValues, $action, $pledgePaymentID) {
f75f0921
EM
1383 $softParams = $softIDs = array();
1384 $pId = $contribution = $isRelatedId = FALSE;
3b8e6c3f 1385 $this->_params = $submittedValues;
1386 $this->beginPostProcess();
3e6a1f4a 1387
bdbc1044 1388 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action::UPDATE) {
f75f0921
EM
1389 $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
1390 $lineID = key($line);
1391 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
1392 $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1393 if ($quickConfig) {
1394 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
1395 }
6a488035 1396 }
f75f0921
EM
1397
1398 // Process price set and get total amount and line items.
1399 $lineItem = array();
1400 $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
1401 if (empty($priceSetId) && !$this->_id) {
1402 $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1403 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
1404 $fieldID = key($this->_priceSet['fields']);
1405 $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
1406 $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1407 $submittedValues['price_' . $fieldID] = 1;
6a488035 1408 }
6a488035 1409
f75f0921
EM
1410 if ($priceSetId) {
1411 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
1412 $submittedValues, $lineItem[$priceSetId]);
c1cc3e0c 1413
f75f0921
EM
1414 // Unset tax amount for offline 'is_quick_config' contribution.
1415 if ($this->_priceSet['is_quick_config'] &&
1416 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())
1417 ) {
1418 unset($submittedValues['tax_amount']);
1419 }
1420 $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
6a488035 1421 }
f75f0921
EM
1422 if ($this->_id) {
1423 if ($this->_compId) {
1424 if ($this->_context == 'participant') {
1425 $pId = $this->_compId;
1426 }
1427 elseif ($this->_context == 'membership') {
1428 $isRelatedId = TRUE;
1429 }
1430 else {
1431 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
1432 }
c1cc3e0c 1433 }
f75f0921
EM
1434 else {
1435 $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1436 if (array_key_exists('membership', $contributionDetails)) {
1437 $isRelatedId = TRUE;
c1cc3e0c 1438 }
f75f0921
EM
1439 elseif (array_key_exists('participant', $contributionDetails)) {
1440 $pId = $contributionDetails['participant'];
c1cc3e0c 1441 }
6a488035 1442 }
6a488035 1443 }
f75f0921
EM
1444 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
1445 // CRM-10117 update the line items for participants.
1446 if ($pId) {
1447 $entityTable = 'participant';
1448 $entityID = $pId;
1449 $isRelatedId = FALSE;
1450 $participantParams = array(
1451 'fee_amount' => $submittedValues['total_amount'],
1452 'id' => $entityID,
1453 );
1454 CRM_Event_BAO_Participant::add($participantParams);
1455 if (empty($this->_lineItems)) {
1456 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
1457 }
1458 }
1459 else {
1460 $entityTable = 'contribution';
1461 $entityID = $this->_id;
1462 }
6a488035 1463
f75f0921
EM
1464 $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
1465 foreach (array_keys($lineItems) as $id) {
1466 $lineItems[$id]['id'] = $id;
1467 }
1468 $itemId = key($lineItems);
1469 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1470 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1471 }
6a488035 1472
f75f0921 1473 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
f85b8063
KJ
1474 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1475 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1476 if (!CRM_Utils_Array::value('membership', $componentDetails) || !CRM_Utils_Array::value('participant', $componentDetails)) {
1477 if (!($this->_action & CRM_Core_Action::UPDATE && (($this->_defaults['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1478 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
1479 }
1480 }
6a488035 1481
f75f0921
EM
1482 // Update line total and total amount with tax on edit.
1483 $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
1484 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1485 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1486 }
1487 else {
1488 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1489 $submittedValues['tax_amount'] = 'null';
1490 }
1491 if ($lineItems[$itemId]['tax_rate']) {
1492 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1493 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
1494 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1495 }
1496 }
1497 // CRM-10117 update the line items for participants.
1498 if (!empty($lineItems[$itemId]['price_field_id'])) {
1499 $lineItem[$this->_priceSetId] = $lineItems;
1500 }
6a488035
TO
1501 }
1502
f75f0921
EM
1503 $isQuickConfig = 0;
1504 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1505 $isQuickConfig = 1;
6a488035 1506 }
f75f0921
EM
1507 //CRM-11529 for quick config back office transactions
1508 //when financial_type_id is passed in form, update the
1509 //line items with the financial type selected in form
1510 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)
1511 ) {
1512 foreach ($lineItem[$this->_priceSetId] as &$values) {
1513 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1514 }
6a488035
TO
1515 }
1516
f75f0921
EM
1517 if (!isset($submittedValues['total_amount'])) {
1518 $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
6a488035 1519 }
f75f0921 1520 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
6a488035 1521
f75f0921
EM
1522 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1523 if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
1524 //Delete existing soft credit records if soft credit list is empty on update
f85b8063 1525 CRM_Contribute_BAO_ContributionSoft::del(array('contribution_id' => $this->_id, 'pcp_id' => 0));
f75f0921 1526 }
c1cc3e0c 1527
f75f0921
EM
1528 // set the contact, when contact is selected
1529 if (!empty($submittedValues['contact_id'])) {
1530 $this->_contactID = $submittedValues['contact_id'];
c1cc3e0c 1531 }
7a13735b 1532
3e6a1f4a 1533 $formValues = $submittedValues;
96025800 1534
f75f0921 1535 // Credit Card Contribution.
a5399a39 1536 if ($this->_mode) {
bf4253e7
EM
1537 $paramsSetByPaymentProcessingSubsystem = array(
1538 'trxn_id',
1539 'payment_instrument_id',
1540 'contribution_status_id',
1541 'cancel_date',
1542 'cancel_reason',
1543 );
1544 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1545 if (isset($formValues[$key])) {
1546 unset($formValues[$key]);
1547 }
1548 }
7126b55c 1549 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID);
bf4253e7
EM
1550 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1551 $formValues[$key] = $contribution->$key;
1552 }
a5399a39 1553 }
f75f0921
EM
1554 else {
1555 // Offline Contribution.
1556 $submittedValues = $this->unsetCreditCardFields($submittedValues);
a5399a39 1557
f75f0921 1558 // get the required field value only.
3e6a1f4a 1559
f75f0921 1560 $params = $ids = array();
a5399a39 1561
f75f0921 1562 $params['contact_id'] = $this->_contactID;
f75f0921 1563 $params['currency'] = $this->getCurrency($submittedValues);
a5399a39 1564
7a13735b 1565 //format soft-credit/pcp param first
1566 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($submittedValues, $this);
1567 $params = array_merge($params, $submittedValues);
1568
f75f0921
EM
1569 $fields = array(
1570 'financial_type_id',
1571 'contribution_status_id',
1572 'payment_instrument_id',
1573 'cancel_reason',
1574 'source',
1575 'check_number',
1576 );
1577 foreach ($fields as $f) {
1578 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1579 }
a5399a39 1580
f75f0921
EM
1581 // CRM-5740 if priceset is used, no need to cleanup money.
1582 if ($priceSetId) {
1583 $params['skipCleanMoney'] = 1;
1584 }
1585
1586 $dates = array(
1587 'receive_date',
1588 'receipt_date',
1589 'cancel_date',
1590 );
1591
1592 foreach ($dates as $d) {
1593 $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1594 }
1595
1596 if (!empty($formValues['is_email_receipt'])) {
1597 $params['receipt_date'] = date("Y-m-d");
1598 }
1599
1600 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name')
1601 || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')
1602 ) {
1603 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
1604 $params['cancel_date'] = date('Y-m-d');
1605 }
1606 }
1607 else {
1608 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1609 }
1610
1611 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1612 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1613 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
1614 $params['is_pay_later'] = 1;
1615 }
1616 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
1617 $params['is_pay_later'] = 0;
1618 }
1619
1620 $ids['contribution'] = $params['id'] = $this->_id;
1621
1622 // Add Additional common information to formatted params.
1623 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
1624 if ($pId) {
1625 $params['contribution_mode'] = 'participant';
1626 $params['participant_id'] = $pId;
1627 $params['skipLineItem'] = 1;
1628 }
1629 elseif ($isRelatedId) {
1630 $params['contribution_mode'] = 'membership';
1631 }
1632 $params['line_item'] = $lineItem;
1633 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
1634 if (isset($submittedValues['tax_amount'])) {
1635 $params['tax_amount'] = $submittedValues['tax_amount'];
1636 }
1637 //create contribution.
1638 if ($isQuickConfig) {
1639 $params['is_quick_config'] = 1;
1640 }
07dd658b 1641 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
f75f0921 1642
f75f0921
EM
1643 $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
1644
1645 // process associated membership / participant, CRM-4395
bdbc1044 1646 if ($contribution->id && $action & CRM_Core_Action::UPDATE) {
3e6a1f4a 1647 $this->statusMessage[] = $this->updateRelatedComponent($contribution->id,
f75f0921
EM
1648 $contribution->contribution_status_id,
1649 CRM_Utils_Array::value('contribution_status_id',
1650 $this->_values
1651 ),
1652 $contribution->receive_date
1653 );
1654 }
1655
3e6a1f4a 1656 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
f75f0921 1657
6d4f5b21 1658 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
f75f0921
EM
1659
1660 //send receipt mail.
1661 if ($contribution->id && !empty($formValues['is_email_receipt'])) {
1662 $formValues['contact_id'] = $this->_contactID;
1663 $formValues['contribution_id'] = $contribution->id;
1664
1665 $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
1666
1667 // to get 'from email id' for send receipt
1668 $this->fromEmailId = $formValues['from_email_address'];
5e27919e 1669 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues)) {
3e6a1f4a 1670 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
5e27919e 1671 }
f75f0921
EM
1672 }
1673
7e5961cf
EM
1674 $this->statusMessageTitle = ts('Saved');
1675
f75f0921 1676 }
5e27919e 1677
bf4253e7 1678 if ($contribution->id && !empty($formValues['product_name'][0])) {
2dcbf765 1679 CRM_Contribute_Form_AdditionalInfo::processPremium($submittedValues, $contribution->id,
945f423d
EM
1680 $this->_premiumID, $this->_options
1681 );
1682 }
1683
1684 if ($contribution->id && isset($submittedValues['note'])) {
1685 CRM_Contribute_Form_AdditionalInfo::processNote($submittedValues, $this->_contactID, $contribution->id, $this->_noteID);
1686 }
1687
3e6a1f4a 1688 CRM_Core_Session::setStatus(implode(' ', $this->statusMessage), $this->statusMessageTitle, 'success');
7e5961cf 1689
5e27919e
EM
1690 CRM_Contribute_BAO_Contribution::updateRelatedPledge(
1691 $action,
1692 $pledgePaymentID,
1693 $contribution->id,
1694 (CRM_Utils_Array::value('option_type', $formValues) == 2) ? TRUE : FALSE,
1695 $formValues['total_amount'],
3e6a1f4a 1696 CRM_Utils_Array::value('total_amount', $this->_defaults),
5e27919e 1697 $formValues['contribution_status_id'],
3e6a1f4a 1698 CRM_Utils_Array::value('contribution_status_id', $this->_defaults)
5e27919e
EM
1699 );
1700 return $contribution;
2e03ce51
EM
1701 }
1702
6d4f5b21
EM
1703 /**
1704 * Assign tax calculations to contribution receipts.
1705 *
1706 * @param array $submittedValues
1707 * @param int $action
1708 * @param array $lineItem
1709 */
1710 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1711
1712 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
1713 if (!CRM_Utils_Array::value('invoicing', $invoiceSettings)) {
1714 return;
1715 }
1716 $taxRate = array();
1717 $getTaxDetails = FALSE;
1718 if ($action & CRM_Core_Action::ADD) {
1719 $line = $lineItem;
1720 }
1721 elseif ($action & CRM_Core_Action::UPDATE) {
1722 $line = $this->_lineItems;
1723 }
1724 foreach ($line as $key => $value) {
1725 foreach ($value as $v) {
1726 if (isset($taxRate[(string) CRM_Utils_Array::value('tax_rate', $v)])) {
1727 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array::value('tax_amount', $v);
1728 }
1729 else {
1730 if (isset($v['tax_rate'])) {
1731 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array::value('tax_amount', $v);
1732 $getTaxDetails = TRUE;
1733 }
1734 }
1735 }
1736 }
1737
1738 if ($action & CRM_Core_Action::UPDATE) {
1739 if (isset($submittedValues['tax_amount'])) {
1740 $totalTaxAmount = $submittedValues['tax_amount'];
1741 }
1742 else {
1743 $totalTaxAmount = $this->_values['tax_amount'];
1744 }
1745 $this->assign('totalTaxAmount', $totalTaxAmount);
1746 $this->assign('dataArray', $taxRate);
1747 }
1748 else {
1749 if (!empty($submittedValues['price_set_id'])) {
1750 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1751 $this->assign('getTaxDetails', $getTaxDetails);
1752 $this->assign('dataArray', $taxRate);
1753 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
1754 }
1755 else {
1756 $this->assign('totalTaxAmount', CRM_Utils_Array::value('tax_amount', $submittedValues));
1757 }
1758 }
1759 }
1760
07dd658b
EM
1761 /**
1762 * Calculate non deductible amount.
1763 *
1764 * CRM-11956
1765 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1766 * if non_deductible_amount does NOT exist - then calculate it depending on:
1767 * $financialType->is_deductible and whether there is a product (premium).
1768 *
1769 * @param $params
1770 * @param $formValues
1771 *
1772 * @return array
1773 */
1774 protected function calculateNonDeductibleAmount($params, $formValues) {
1775 if (!empty($params['non_deductible_amount'])) {
1776 return $params['non_deductible_amount'];
1777 }
07dd658b 1778
f70eb51f
EM
1779 $financialType = new CRM_Financial_DAO_FinancialType();
1780 $financialType->id = $params['financial_type_id'];
07dd658b 1781
f70eb51f
EM
1782 if ($financialType->is_deductible) {
1783
1784 if (isset($formValues['product_name'][0])) {
1785 $selectProduct = $formValues['product_name'][0];
1786 }
1787 // if there is a product - compare the value to the contribution amount
1788 if (isset($selectProduct)) {
1789 $productDAO = new CRM_Contribute_DAO_Product();
1790 $productDAO->id = $selectProduct;
1791 $productDAO->find(TRUE);
1792 // product value exceeds contribution amount
1793 if ($params['total_amount'] < $productDAO->price) {
1794 return $params['total_amount'];
07dd658b 1795 }
f70eb51f 1796 // product value does NOT exceed contribution amount
07dd658b 1797 else {
f70eb51f 1798 return $productDAO->price;
07dd658b
EM
1799 }
1800 }
f70eb51f 1801 // contribution is deductible - but there is no product
07dd658b 1802 else {
f70eb51f 1803 return '0.00';
07dd658b
EM
1804 }
1805 }
f70eb51f
EM
1806 // contribution is NOT deductible
1807 else {
1808 return $params['total_amount'];
1809 }
1810
07dd658b
EM
1811 return 0;
1812 }
1813
6a488035 1814}