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