Fix row ID not being set in contribution/participant 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() {
3db2d5ef 469 if ($this->_action & CRM_Core_Action::DELETE) {
be2fb01f 470 $this->addButtons([
1330f57a
SL
471 [
472 'type' => 'next',
473 'name' => ts('Delete'),
474 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
475 'isDefault' => TRUE,
476 ],
477 [
478 'type' => 'cancel',
479 'name' => ts('Cancel'),
480 ],
481 ]);
3db2d5ef
JP
482 return;
483 }
484
e3fa3fea 485 // FIXME: This probably needs to be done in preprocess
40c655aa
E
486 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
487 && $this->_action & CRM_Core_Action::UPDATE
66af7c48
PN
488 && CRM_Utils_Array::value('financial_type_id', $this->_values)
489 ) {
e3fa3fea 490 $financialTypeID = CRM_Contribute_PseudoConstant::financialType($this->_values['financial_type_id']);
59ccc8cd 491 CRM_Financial_BAO_FinancialType::checkPermissionedLineItems($this->_id, 'edit');
e3fa3fea
E
492 if (!CRM_Core_Permission::check('edit contributions of type ' . $financialTypeID)) {
493 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
494 }
495 }
be2fb01f 496 $allPanes = [];
b15c60e1 497
6daab7fa 498 //tax rate from financialType
a1e457ff 499 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
049db839 500 $this->assign('currencies', json_encode(CRM_Core_OptionGroup::values('currencies_enabled')));
6a488035
TO
501
502 // build price set form.
503 $buildPriceSet = FALSE;
d0df87f2 504 $invoicing = CRM_Invoicing_Utils::isInvoicingEnabled();
95f2107c 505 $this->assign('invoicing', $invoicing);
a32709be 506
b15c60e1 507 $buildRecurBlock = FALSE;
508
03b412ae
PB
509 // display tax amount on edit contribution page
510 if ($invoicing && $this->_action & CRM_Core_Action::UPDATE && isset($this->_values['tax_amount'])) {
a32709be
PB
511 $this->assign('totalTaxAmount', $this->_values['tax_amount']);
512 }
513
6a488035 514 if (empty($this->_lineItems) &&
8cc574cf 515 ($this->_priceSetId || !empty($_POST['price_set_id']))
6a488035
TO
516 ) {
517 $buildPriceSet = TRUE;
518 $getOnlyPriceSetElements = TRUE;
519 if (!$this->_priceSetId) {
520 $this->_priceSetId = $_POST['price_set_id'];
521 $getOnlyPriceSetElements = FALSE;
522 }
523
524 $this->set('priceSetId', $this->_priceSetId);
9da8dc8c 525 CRM_Price_BAO_PriceSet::buildPriceSet($this);
6a488035
TO
526
527 // get only price set form elements.
528 if ($getOnlyPriceSetElements) {
529 return;
530 }
531 }
532 // use to build form during form rule.
533 $this->assign('buildPriceSet', $buildPriceSet);
534
6a488035 535 $defaults = $this->_values;
be2fb01f 536 $additionalDetailFields = [
6a488035
TO
537 'note',
538 'thankyou_date',
539 'invoice_id',
540 'non_deductible_amount',
541 'fee_amount',
be2fb01f 542 ];
6a488035
TO
543 foreach ($additionalDetailFields as $key) {
544 if (!empty($defaults[$key])) {
545 $defaults['hidden_AdditionalDetail'] = 1;
546 break;
547 }
548 }
549
6a488035
TO
550 if ($this->_productDAO) {
551 if ($this->_productDAO->product_id) {
552 $defaults['hidden_Premium'] = 1;
553 }
554 }
555
556 if ($this->_noteID &&
5888a52d 557 !CRM_Utils_System::isNull($this->_values['note'])
6a488035
TO
558 ) {
559 $defaults['hidden_AdditionalDetail'] = 1;
560 }
561
be2fb01f 562 $paneNames = [];
b9a90a9c 563 if (empty($this->_payNow)) {
564 $paneNames[ts('Additional Details')] = 'AdditionalDetail';
565 }
6a488035
TO
566
567 //Add Premium pane only if Premium is exists.
568 $dao = new CRM_Contribute_DAO_Product();
569 $dao->is_active = 1;
570
b9a90a9c 571 if ($dao->find(TRUE) && empty($this->_payNow)) {
6a488035
TO
572 $paneNames[ts('Premium Information')] = 'Premium';
573 }
574
a576ecfa 575 $this->payment_instrument_id = CRM_Utils_Array::value('payment_instrument_id', $defaults, $this->getDefaultPaymentInstrumentId());
576 if (CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE, $this->payment_instrument_id) == TRUE) {
794d4fc0 577 if (!empty($this->_recurPaymentProcessors)) {
578 $buildRecurBlock = TRUE;
579 if ($this->_ppID) {
580 // ppID denotes a pledge payment.
581 foreach ($this->_paymentProcessors as $processor) {
582 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
583 $buildRecurBlock = TRUE;
584 break;
4f3c361d 585 }
794d4fc0 586 $buildRecurBlock = FALSE;
4f3c361d 587 }
794d4fc0 588 }
589 if ($buildRecurBlock) {
590 CRM_Contribute_Form_Contribution_Main::buildRecur($this);
be2fb01f 591 $this->setDefaults(['is_recur' => 0]);
794d4fc0 592 $this->assign('buildRecurBlock', TRUE);
5e27919e 593 }
6a488035
TO
594 }
595 }
b15c60e1 596 $this->addPaymentProcessorSelect(FALSE, $buildRecurBlock);
6a488035 597
6a488035 598 foreach ($paneNames as $name => $type) {
a5399a39 599 $allPanes[$name] = $this->generatePane($type, $defaults);
6a488035 600 }
5e27919e 601
6a488035
TO
602 $qfKey = $this->controller->_key;
603 $this->assign('qfKey', $qfKey);
604 $this->assign('allPanes', $allPanes);
6a488035 605
be2fb01f 606 $this->addFormRule(['CRM_Contribute_Form_Contribution', 'formRule'], $this);
6c75c831 607
6a488035
TO
608 if ($this->_formType) {
609 $this->assign('formType', $this->_formType);
610 return;
611 }
612
613 $this->applyFilter('__ALL__', 'trim');
5a230af7 614
6a488035
TO
615 //need to assign custom data type and subtype to the template
616 $this->assign('customDataType', 'Contribution');
617 $this->assign('customDataSubType', $this->_contributionType);
618 $this->assign('entityID', $this->_id);
619
620 if ($this->_context == 'standalone') {
be2fb01f 621 $this->addEntityRef('contact_id', ts('Contact'), [
1330f57a
SL
622 'create' => TRUE,
623 'api' => ['extra' => ['email']],
624 ], TRUE);
6a488035
TO
625 }
626
627 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
628
e3fa3fea 629 // Check permissions for financial type first
573fd305 630 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action);
b19a01c7 631 if (empty($financialTypes)) {
b55aa3de 632 CRM_Core_Error::statusBounce(ts('You do not have all the permissions needed for this page.'));
b19a01c7 633 }
6a488035
TO
634 $financialType = $this->add('select', 'financial_type_id',
635 ts('Financial Type'),
be2fb01f 636 ['' => ts('- select -')] + $financialTypes,
79ca865b 637 TRUE,
be2fb01f 638 ['onChange' => "CRM.buildCustomData( 'Contribution', this.value );"]
6a488035 639 );
e3fa3fea 640
d77a0a58 641 $paymentInstrument = FALSE;
6a488035 642 if (!$this->_mode) {
c485e792 643 // payment_instrument isn't required in edit and will not be present when payment block is enabled.
644 $required = $this->_id ? FALSE : TRUE;
6f26f78f 645 $checkPaymentID = array_search('Check', CRM_Contribute_PseudoConstant::paymentInstrument('name'));
6a488035 646 $paymentInstrument = $this->add('select', 'payment_instrument_id',
4db803dd 647 ts('Payment Method'),
be2fb01f
CW
648 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
649 $required, ['onChange' => "return showHideByValue('payment_instrument_id','{$checkPaymentID}','checkNumber','table-row','select',false);"]
6a488035
TO
650 );
651 }
652
be2fb01f 653 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), ['class' => 'twelve'] + $attributes['trxn_id']);
6a488035
TO
654
655 //add receipt for offline contribution
656 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
657
658 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
659
7fe7b63d 660 $component = 'contribution';
6bc9ca96 661 $componentDetails = [];
7fe7b63d 662 if ($this->_id) {
7fe7b63d 663 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
664 if (CRM_Utils_Array::value('membership', $componentDetails)) {
665 $component = 'membership';
f73acc78 666 }
7fe7b63d 667 elseif (CRM_Utils_Array::value('participant', $componentDetails)) {
668 $component = 'participant';
6a488035
TO
669 }
670 }
2077cf67 671 if ($this->_ppID) {
7fe7b63d 672 $component = 'pledge';
673 }
674 $status = CRM_Contribute_BAO_Contribution_Utils::getContributionStatuses($component, $this->_id);
b6545333 675
d4849da4 676 // define the status IDs that show the cancellation info, see CRM-17589
be2fb01f 677 $cancelInfo_show_ids = [];
7fe7b63d 678 foreach (array_keys($status) as $status_id) {
d682fc35 679 if (CRM_Contribute_BAO_Contribution::isContributionStatusNegative($status_id)) {
d4849da4 680 $cancelInfo_show_ids[] = "'$status_id'";
681 }
682 }
683 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
684
29cb4724 685 $statusElement = $this->add('select', 'contribution_status_id',
6a488035
TO
686 ts('Contribution Status'),
687 $status,
688 FALSE
689 );
690
29cb4724 691 $currencyFreeze = FALSE;
b9a90a9c 692 if (!empty($this->_payNow) && ($this->_action & CRM_Core_Action::UPDATE)) {
29cb4724 693 $statusElement->freeze();
694 $currencyFreeze = TRUE;
695 $attributes['total_amount']['readonly'] = TRUE;
696 }
697
46d173ef 698 // CRM-16189, add Revenue Recognition Date
a17bec97 699 if (Civi::settings()->get('deferred_revenue_enabled')) {
cb8ce66b
PN
700 $revenueDate = $this->add('date', 'revenue_recognition_date', ts('Revenue Recognition Date'), CRM_Core_SelectValues::date(NULL, 'M Y', NULL, 5));
701 if ($this->_id && !CRM_Contribute_BAO_Contribution::allowUpdateRevenueRecognitionDate($this->_id)) {
702 $revenueDate->freeze();
703 }
46d173ef
PN
704 }
705
6a488035 706 // add various dates
be2fb01f
CW
707 $this->addField('receive_date', ['entity' => 'contribution'], !$this->_mode, FALSE);
708 $this->addField('receipt_date', ['entity' => 'contribution'], FALSE, FALSE);
709 $this->addField('cancel_date', ['entity' => 'contribution', 'label' => ts('Cancelled / Refunded Date')], FALSE, FALSE);
6a488035
TO
710
711 if ($this->_online) {
712 $this->assign('hideCalender', TRUE);
713 }
6a488035 714
6a488035 715 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
e02d7e96 716
6a488035
TO
717 $totalAmount = NULL;
718 if (empty($this->_lineItems)) {
719 $buildPriceSet = FALSE;
9da8dc8c 720 $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute');
6a488035
TO
721 if (!empty($priceSets) && !$this->_ppID) {
722 $buildPriceSet = TRUE;
723 }
724
725 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
726 // and if we already have line items for that participant. CRM-5095
727 if ($buildPriceSet && $this->_id) {
6a488035
TO
728 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
729 $this->_id,
730 'id',
731 'contribution_id'
732 );
733 if ($pledgePaymentId) {
734 $buildPriceSet = FALSE;
735 }
736 if ($participantID = CRM_Utils_Array::value('participant', $componentDetails)) {
737 $participantLI = CRM_Price_BAO_LineItem::getLineItems($participantID);
738 if (!CRM_Utils_System::isNull($participantLI)) {
739 $buildPriceSet = FALSE;
740 }
741 }
742 }
743
744 $hasPriceSets = FALSE;
745 if ($buildPriceSet) {
746 $hasPriceSets = TRUE;
6a3d8d2d
WA
747 // CRM-16451: set financial type of 'Price Set' in back office contribution
748 // instead of selecting manually
749 $financialTypeIds = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
6a488035 750 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
be2fb01f 751 [
21dfd5f5 752 '' => ts('Choose price set'),
be2fb01f
CW
753 ] + $priceSets,
754 NULL, ['onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");"]
5a230af7 755 );
6a488035
TO
756 if ($this->_online && !($this->_action & CRM_Core_Action::UPDATE)) {
757 $element->freeze();
758 }
759 }
760 $this->assign('hasPriceSets', $hasPriceSets);
6a488035 761 if (!($this->_action & CRM_Core_Action::UPDATE)) {
d37ade2e 762 if ($this->_online || $this->_ppID) {
be2fb01f 763 $attributes['total_amount'] = array_merge($attributes['total_amount'], [
d37ade2e 764 'READONLY' => TRUE,
21dfd5f5 765 'style' => "background-color:#EBECE4",
be2fb01f
CW
766 ]);
767 $optionTypes = [
d37ade2e 768 '1' => ts('Adjust Pledge Payment Schedule?'),
769 '2' => ts('Adjust Total Pledge Amount?'),
be2fb01f 770 ];
d37ade2e 771 $this->addRadio('option_type',
772 NULL,
773 $optionTypes,
be2fb01f 774 [], '<br/>'
d37ade2e 775 );
776
777 $currencyFreeze = TRUE;
778 }
6a488035
TO
779 }
780
781 $totalAmount = $this->addMoney('total_amount',
782 ts('Total Amount'),
783 ($hasPriceSets) ? FALSE : TRUE,
784 $attributes['total_amount'],
785 TRUE, 'currency', NULL, $currencyFreeze
786 );
787 }
788
789 $this->add('text', 'source', ts('Source'), CRM_Utils_Array::value('source', $attributes));
790
161a2fe7 791 // CRM-7362 --add campaigns.
6a488035
TO
792 CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
793
b9a90a9c 794 if (empty($this->_payNow)) {
795 CRM_Contribute_Form_SoftCredit::buildQuickForm($this);
796 }
0baed70b 797
6a488035
TO
798 $js = NULL;
799 if (!$this->_mode) {
be2fb01f 800 $js = ['onclick' => "return verify( );"];
6a488035
TO
801 }
802
aaffa79f 803 $mailingInfo = Civi::settings()->get('mailing_backend');
6a488035
TO
804 $this->assign('outBound_option', $mailingInfo['outBound_option']);
805
be2fb01f 806 $this->addButtons([
1330f57a
SL
807 [
808 'type' => 'upload',
809 'name' => ts('Save'),
810 'js' => $js,
811 'isDefault' => TRUE,
812 ],
813 [
814 'type' => 'upload',
815 'name' => ts('Save and New'),
816 'js' => $js,
817 'subName' => 'new',
818 ],
819 [
820 'type' => 'cancel',
821 'name' => ts('Cancel'),
822 ],
823 ]);
6a488035 824
b6f65362 825 // if contribution is related to membership or participant freeze Financial Type, Amount
6bc9ca96 826 if ($this->_id) {
0fc5a6b9 827 $this->add('hidden', 'id', $this->_id);
b6f65362 828 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
6bc9ca96 829 $isCancelledStatus = ($this->_values['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Cancelled'));
830
831 if (CRM_Utils_Array::value('membership', $componentDetails) ||
832 CRM_Utils_Array::value('participant', $componentDetails) ||
833 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
834 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
835 $isCancelledStatus
836 ) {
b5527a9a 837 if ($totalAmount) {
a13f3d8c 838 $totalAmount->freeze();
6bc9ca96 839 $this->getElement('currency')->freeze();
840 }
841 if ($isCancelledStatus) {
842 $paymentInstrument->freeze();
843 $trxnId->freeze();
b5527a9a 844 }
b6f65362 845 $financialType->freeze();
b6f65362 846 $this->assign('freezeFinancialType', TRUE);
847 }
848 }
849
6a488035
TO
850 if ($this->_action & CRM_Core_Action::VIEW) {
851 $this->freeze();
852 }
853 }
854
855 /**
fe482240 856 * Global form rule.
6a488035 857 *
014c4014
TO
858 * @param array $fields
859 * The input form values.
860 * @param array $files
861 * The uploaded files if any.
2a6da8d7
EM
862 * @param $self
863 *
72b3a70c
CW
864 * @return bool|array
865 * true if no errors, else array of errors
6a488035 866 */
1cf3816f 867 public static function formRule($fields, $files, $self) {
be2fb01f 868 $errors = [];
161a2fe7 869 // Check for Credit Card Contribution.
6a488035
TO
870 if ($self->_mode) {
871 if (empty($fields['payment_processor_id'])) {
872 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
873 }
34089500 874 else {
875 // validate payment instrument (e.g. credit card number)
1d1fee72 876 CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
34089500 877 }
6a488035
TO
878 }
879
161a2fe7 880 // Do the amount validations.
a7488080 881 if (empty($fields['total_amount']) && empty($self->_lineItems)) {
6a488035 882 if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) {
9da8dc8c 883 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $fields, $errors);
6a488035
TO
884 }
885 }
886
b326919b 887 $softErrors = CRM_Contribute_Form_SoftCredit::formRule($fields, $errors, $self);
d37ade2e 888
577d1236
WA
889 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
890 CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors);
891
161a2fe7 892 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
58d33659
PN
893 if (($self->_action & CRM_Core_Action::UPDATE)
894 && $self->_id
895 && $self->_values['contribution_status_id'] != $fields['contribution_status_id']
896 ) {
6a488035
TO
897 CRM_Contribute_BAO_Contribution::checkStatusValidation($self->_values, $fields, $errors);
898 }
4d47ad17 899 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
58d33659
PN
900 if (($self->_action & CRM_Core_Action::UPDATE)
901 && $self->_id
902 && $self->_values['financial_type_id'] != $fields['financial_type_id']
903 ) {
4d47ad17
PN
904 CRM_Contribute_BAO_Contribution::checkFinancialTypeChange(NULL, $self->_id, $errors);
905 }
6a488035 906 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
34089500 907 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution::validateFinancialType($fields['financial_type_id'])) {
51fa20cb 908 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
6a488035 909 }
133e2c99 910
7272e4fa
DG
911 // $trxn_id must be unique CRM-13919
912 if (!empty($fields['trxn_id'])) {
be2fb01f 913 $queryParams = [1 => [$fields['trxn_id'], 'String']];
7272e4fa
DG
914 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
915 if ($self->_id) {
be2fb01f 916 $queryParams[2] = [(int) $self->_id, 'Integer'];
7272e4fa
DG
917 $query .= ' and id !=%2';
918 }
919 $tCnt = CRM_Core_DAO::singleValueQuery($query, $queryParams);
920 if ($tCnt) {
be2fb01f 921 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', [1 => $fields['trxn_id']]);
133e2c99 922 }
7272e4fa 923 }
46d173ef
PN
924 if (!empty($fields['revenue_recognition_date'])
925 && count(array_filter($fields['revenue_recognition_date'])) == 1
926 ) {
927 $errors['revenue_recognition_date'] = ts('Month and Year are required field for Revenue Recognition.');
928 }
3adac159 929 // CRM-16189
96039749
PN
930 try {
931 CRM_Financial_BAO_FinancialAccount::checkFinancialTypeHasDeferred($fields, $self->_id, $self->_priceSet['fields']);
932 }
933 catch (CRM_Core_Exception $e) {
c9b68130 934 $errors['financial_type_id'] = ' ';
96039749 935 $errors['_qf_default'] = $e->getMessage();
3adac159 936 }
ac0c89ed 937 $errors = array_merge($errors, $softErrors);
6a488035
TO
938 return $errors;
939 }
940
941 /**
fe482240 942 * Process the form submission.
6a488035
TO
943 */
944 public function postProcess() {
6a488035
TO
945 if ($this->_action & CRM_Core_Action::DELETE) {
946 CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
c1cc3e0c 947 CRM_Core_Session::singleton()->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
6a488035
TO
948 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
949 ));
950 return;
951 }
77c081c2 952 // Get the submitted form values.
6a488035 953 $submittedValues = $this->controller->exportValues($this->_name);
7758bd2b
EM
954
955 try {
7758bd2b
EM
956 $contribution = $this->submit($submittedValues, $this->_action, $this->_ppID);
957 }
958 catch (PaymentProcessorException $e) {
959 // Set the contribution mode.
960 $urlParams = "action=add&cid={$this->_contactID}";
961 if ($this->_mode) {
962 $urlParams .= "&mode={$this->_mode}";
963 }
964 if (!empty($this->_ppID)) {
965 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
966 }
967
968 CRM_Core_Error::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
969 }
f75f0921
EM
970 $session = CRM_Core_Session::singleton();
971 $buttonName = $this->controller->getButtonName();
972 if ($this->_context == 'standalone') {
973 if ($buttonName == $this->getButtonName('upload', 'new')) {
974 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add',
975 'reset=1&action=add&context=standalone'
976 ));
6a488035 977 }
f75f0921
EM
978 else {
979 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
980 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
981 ));
982 }
983 }
984 elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) {
985 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
986 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
987 ));
988 }
989 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
990 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
991 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
992 ));
6a488035
TO
993 }
994
f75f0921
EM
995 //store contribution ID if not yet set (on create)
996 if (empty($this->_id) && !empty($contribution->id)) {
997 $this->_id = $contribution->id;
6a488035 998 }
94c8aed1 999 if (!empty($this->_id) && CRM_Core_Permission::access('CiviMember')) {
be2fb01f 1000 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', ['contribution_id' => $this->_id]);
5a53dd1f 1001 if ($membershipPaymentCount) {
94c8aed1
E
1002 $this->ajaxResponse['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact::getCountComponent('membership', $this->_contactID);
1003 }
1004 }
5a53dd1f 1005 if (!empty($this->_id) && CRM_Core_Permission::access('CiviEvent')) {
be2fb01f 1006 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', ['contribution_id' => $this->_id]);
5a53dd1f
E
1007 if ($participantPaymentCount) {
1008 $this->ajaxResponse['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact::getCountComponent('participant', $this->_contactID);
1009 }
1010 }
f75f0921 1011 }
6a488035 1012
f75f0921
EM
1013 /**
1014 * Process credit card payment.
1015 *
1016 * @param array $submittedValues
1017 * @param array $lineItem
456b0145 1018 *
7126b55c
EM
1019 * @param int $contactID
1020 * Contact ID
1021 *
456b0145 1022 * @return bool|\CRM_Contribute_DAO_Contribution
f8453bef 1023 * @throws \CRM_Core_Exception
7758bd2b 1024 * @throws \Civi\Payment\Exception\PaymentProcessorException
456b0145 1025 */
7126b55c 1026 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
549cf0b9 1027 $isTest = ($this->_mode == 'test') ? 1 : 0;
f75f0921 1028 // CRM-12680 set $_lineItem if its not set
bf4253e7
EM
1029 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1030 // It would be better to pass line item out to functions than $this->_lineItem as
1031 // we don't know what is being changed where.
f75f0921
EM
1032 if (empty($this->_lineItem) && !empty($lineItem)) {
1033 $this->_lineItem = $lineItem;
6a488035 1034 }
6a488035 1035
bf4253e7
EM
1036 $this->_paymentObject = Civi\Payment\System::singleton()->getById($submittedValues['payment_processor_id']);
1037 $this->_paymentProcessor = $this->_paymentObject->getPaymentProcessor();
c52884b2 1038
7758bd2b
EM
1039 // Set source if not set
1040 if (empty($submittedValues['source'])) {
1041 $userID = CRM_Core_Session::singleton()->get('userID');
1042 $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1043 'sort_name'
1044 );
be2fb01f 1045 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', [1 => $userSortName]);
7758bd2b
EM
1046 }
1047
3b8e6c3f 1048 $params = $submittedValues;
1049 $this->_params = array_merge($this->_params, $submittedValues);
77e18ec7 1050
bf4253e7
EM
1051 // Mapping requiring documentation.
1052 $this->_params['payment_processor'] = $submittedValues['payment_processor_id'];
1053
f75f0921 1054 $now = date('YmdHis');
5a230af7 1055
3b8e6c3f 1056 $this->_contributorEmail = $this->userEmail;
1057 $this->_contributorContactID = $contactID;
1058 $this->processBillingAddress();
f75f0921
EM
1059 if (!empty($params['source'])) {
1060 unset($params['source']);
6a488035 1061 }
c52884b2 1062
f75f0921 1063 $this->_params['amount'] = $this->_params['total_amount'];
c039f658 1064 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1065 // function to get correct amount level consistently. Remove setting of the amount level in
1066 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1067 // to cover all variants.
f75f0921 1068 $this->_params['amount_level'] = 0;
e47238e5 1069 $this->_params['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
f75f0921
EM
1070 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
1071 $this->_params,
1072 CRM_Core_Config::singleton()->defaultCurrency
1073 );
aefd7f6b 1074
f75f0921
EM
1075 $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
1076 $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
1077 $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
3f662d9d 1078
f75f0921
EM
1079 //Add common data to formatted params
1080 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
6a488035 1081
f75f0921
EM
1082 if (empty($this->_params['invoice_id'])) {
1083 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1084 }
1085 else {
1086 $this->_params['invoiceID'] = $this->_params['invoice_id'];
1087 }
6a488035 1088
f75f0921
EM
1089 // At this point we've created a contact and stored its address etc
1090 // all the payment processors expect the name and address to be in the
1091 // so we copy stuff over to first_name etc.
1092 $paymentParams = $this->_params;
7126b55c 1093 $paymentParams['contactID'] = $contactID;
f75f0921 1094 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
6a488035 1095
67256e0c
EM
1096 $financialType = new CRM_Financial_DAO_FinancialType();
1097 $financialType->id = $params['financial_type_id'];
11829025 1098 $financialType->find(TRUE);
6a488035 1099
f75f0921
EM
1100 // Add some financial type details to the params list
1101 // if folks need to use it.
67256e0c 1102 $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $financialType->name;
f75f0921 1103 $paymentParams['contributionPageID'] = NULL;
6a488035 1104
f75f0921
EM
1105 if (!empty($this->_params['is_email_receipt'])) {
1106 $paymentParams['email'] = $this->userEmail;
1107 $paymentParams['is_email_receipt'] = 1;
1108 }
1109 else {
1110 $paymentParams['is_email_receipt'] = 0;
1111 $this->_params['is_email_receipt'] = 0;
1112 }
1113 if (!empty($this->_params['receive_date'])) {
1114 $paymentParams['receive_date'] = $this->_params['receive_date'];
1115 }
6a488035 1116
f75f0921
EM
1117 if (!empty($this->_params['is_email_receipt'])) {
1118 $this->_params['receipt_date'] = $now;
1119 }
6a488035 1120
f75f0921 1121 $this->set('params', $this->_params);
7758bd2b 1122
f75f0921 1123 $this->assign('receive_date', $this->_params['receive_date']);
6a488035 1124
f75f0921
EM
1125 // Result has all the stuff we need
1126 // lets archive it to a financial transaction
67256e0c 1127 if ($financialType->is_deductible) {
f75f0921
EM
1128 $this->assign('is_deductible', TRUE);
1129 $this->set('is_deductible', TRUE);
1130 }
be2fb01f 1131 $contributionParams = [
29cb4724 1132 'id' => CRM_Utils_Array::value('contribution_id', $this->_params),
3febe800 1133 'contact_id' => $contactID,
1134 'line_item' => $lineItem,
1135 'is_test' => $isTest,
1136 'campaign_id' => CRM_Utils_Array::value('campaign_id', $this->_params),
1137 'contribution_page_id' => CRM_Utils_Array::value('contribution_page_id', $this->_params),
1138 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)),
1139 'thankyou_date' => CRM_Utils_Array::value('thankyou_date', $this->_params),
be2fb01f 1140 ];
16f3bd02 1141 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor['payment_instrument_id'];
6a488035 1142
ba013eea 1143 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this,
7758bd2b
EM
1144 $this->_params,
1145 NULL,
3febe800 1146 $contributionParams,
7758bd2b 1147 $financialType,
7758bd2b 1148 FALSE,
449f4c90 1149 $this->_bltID,
1150 CRM_Utils_Array::value('is_recur', $this->_params)
7758bd2b 1151 );
6a488035 1152
7758bd2b
EM
1153 $paymentParams['contributionID'] = $contribution->id;
1154 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
1155 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1156 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
6a488035 1157
7758bd2b
EM
1158 if ($paymentParams['amount'] > 0.0) {
1159 // force a re-get of the payment processor in case the form changed it, CRM-7179
9d8f43b1
EM
1160 // NOTE - I expect this is obsolete.
1161 $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
7758bd2b 1162 try {
003e9340 1163 $completeStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
7758bd2b
EM
1164 $result = $payment->doPayment($paymentParams, 'contribute');
1165 $this->assign('trxn_id', $result['trxn_id']);
1166 $contribution->trxn_id = $result['trxn_id'];
1167 /* Our scenarios here are
1168 * 1) the payment failed & an Exception should have been thrown
1169 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1170 * with a delayed start)
1171 * 3) the payment succeeded with an immediate payment.
1172 *
7c85dc65 1173 * The doPayment function ensures that payment_status_id is always set
7758bd2b
EM
1174 * as historically we have had to guess from the context - ie doDirectPayment
1175 * = error or success, unless it is a recurring contribution in which case it is pending.
1176 */
003e9340 1177 if ($result['payment_status_id'] == $completeStatusId) {
760278d3 1178 try {
be2fb01f 1179 civicrm_api3('contribution', 'completetransaction', [
760278d3
EM
1180 'id' => $contribution->id,
1181 'trxn_id' => $result['trxn_id'],
1182 'payment_processor_id' => $this->_paymentProcessor['id'],
1183 'is_transactional' => FALSE,
22e39333 1184 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
a55e39e9 1185 'card_type_id' => CRM_Utils_Array::value('card_type_id', $paymentParams),
1186 'pan_truncation' => CRM_Utils_Array::value('pan_truncation', $paymentParams),
0af52f61 1187 'is_email_receipt' => FALSE,
be2fb01f 1188 ]);
760278d3
EM
1189 // This has now been set to 1 in the DB - declare it here also
1190 $contribution->contribution_status_id = 1;
1191 }
1192 catch (CiviCRM_API3_Exception $e) {
1193 if ($e->getErrorCode() != 'contribution_completed') {
1194 throw new CRM_Core_Exception('Failed to update contribution in database');
1195 }
1196 }
7758bd2b
EM
1197 }
1198 else {
1199 // Save the trxn_id.
1200 $contribution->save();
1201 }
1202 }
1203 catch (PaymentProcessorException $e) {
06d062ce 1204 CRM_Contribute_BAO_Contribution::failPayment($contribution->id, $paymentParams['contactID'], $e->getMessage());
7758bd2b
EM
1205 throw new PaymentProcessorException($e->getMessage());
1206 }
1207 }
f75f0921 1208 // Send receipt mail.
e390a377 1209 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
f75f0921
EM
1210 if ($contribution->id && !empty($this->_params['is_email_receipt'])) {
1211 $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
7126b55c 1212 $this->_params['contact_id'] = $contactID;
f75f0921 1213 $this->_params['contribution_id'] = $contribution->id;
c52884b2 1214 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE)) {
3e6a1f4a 1215 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
6a488035 1216 }
28d44c9f 1217 }
c52884b2 1218
5e27919e 1219 return $contribution;
6a488035 1220 }
5a230af7 1221
f75f0921
EM
1222 /**
1223 * Generate the data to construct a snippet based pane.
1224 *
1225 * This form also assigns the showAdditionalInfo var based on historical code.
1226 * This appears to mean 'there is a pane to show'.
1227 *
1228 * @param string $type
1229 * Type of Pane - this is generally used to determine the function name used to build it
1230 * - e.g CreditCard, AdditionalDetail
1231 * @param array $defaults
1232 *
1233 * @return array
1234 * We aim to further refactor & simplify this but currently
1235 * - the panes array
1236 * - should additional info be shown?
1237 */
1238 protected function generatePane($type, $defaults) {
1239 $urlParams = "snippet=4&formType={$type}";
1240 if ($this->_mode) {
1241 $urlParams .= "&mode={$this->_mode}";
6a488035
TO
1242 }
1243
f75f0921
EM
1244 $open = 'false';
1245 if ($type == 'CreditCard' ||
1246 $type == 'DirectDebit'
1247 ) {
1248 $open = 'true';
6a488035 1249 }
6a488035 1250
be2fb01f 1251 $pane = [
f75f0921
EM
1252 'url' => CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams),
1253 'open' => $open,
1254 'id' => $type,
be2fb01f 1255 ];
6a488035 1256
f75f0921
EM
1257 // See if we need to include this paneName in the current form.
1258 if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) ||
1259 CRM_Utils_Array::value("hidden_{$type}", $defaults)
1260 ) {
1261 $this->assign('showAdditionalInfo', TRUE);
1262 $pane['open'] = 'true';
6a488035
TO
1263 }
1264
f75f0921
EM
1265 if ($type == 'CreditCard' || $type == 'DirectDebit') {
1266 // @todo would be good to align tpl name with form name...
1267 // @todo document why this hidden variable is required.
1268 $this->add('hidden', 'hidden_' . $type, 1);
1269 return $pane;
6a488035
TO
1270 }
1271 else {
f75f0921
EM
1272 $additionalInfoFormFunction = 'build' . $type;
1273 CRM_Contribute_Form_AdditionalInfo::$additionalInfoFormFunction($this);
1274 return $pane;
6a488035 1275 }
f75f0921 1276 }
6a488035 1277
f75f0921
EM
1278 /**
1279 * Wrapper for unit testing the post process submit function.
1280 *
1281 * (If we expose through api we can get default additions 'for free').
1282 *
1283 * @param array $params
5e27919e 1284 * @param int $action
39f47c0d
EM
1285 * @param string|null $creditCardMode
1286 *
1287 * @throws \CiviCRM_API3_Exception
f75f0921 1288 */
39f47c0d 1289 public function testSubmit($params, $action, $creditCardMode = NULL) {
be2fb01f
CW
1290 $defaults = [
1291 'soft_credit_contact_id' => [],
6298b166 1292 'receive_date' => date('Y-m-d H:i:s'),
f75f0921 1293 'receipt_date' => '',
f75f0921 1294 'cancel_date' => '',
43bf07d6 1295 'hidden_Premium' => 1,
be2fb01f 1296 ];
739a8336 1297 $this->_bltID = 5;
5e27919e 1298 if (!empty($params['id'])) {
be2fb01f 1299 $existingContribution = civicrm_api3('contribution', 'getsingle', [
5e27919e 1300 'id' => $params['id'],
be2fb01f 1301 ]);
55e55e84 1302 $this->_id = $params['id'];
0f07bb06 1303 $this->_values = $existingContribution;
7c002a4d 1304 if (CRM_Contribute_BAO_Contribution::checkContributeSettings('invoicing')) {
be2fb01f 1305 $this->_values['tax_amount'] = civicrm_api3('contribution', 'getvalue', [
7c002a4d 1306 'id' => $params['id'],
1307 'return' => 'tax_amount',
be2fb01f 1308 ]);
7c002a4d 1309 }
5e27919e
EM
1310 }
1311 else {
be2fb01f 1312 $existingContribution = [];
5e27919e
EM
1313 }
1314
1315 $this->_defaults['contribution_status_id'] = CRM_Utils_Array::value('contribution_status_id',
1316 $existingContribution
1317 );
1318
1319 $this->_defaults['total_amount'] = CRM_Utils_Array::value('total_amount',
1320 $existingContribution
1321 );
6a488035 1322
39f47c0d
EM
1323 if ($creditCardMode) {
1324 $this->_mode = $creditCardMode;
1325 }
1326
1327 // Required because processCreditCard calls set method on this.
1328 $_SERVER['REQUEST_METHOD'] = 'GET';
1329 $this->controller = new CRM_Core_Controller();
1330
3e6a1f4a
EM
1331 CRM_Contribute_Form_AdditionalInfo::buildPremium($this);
1332
be2fb01f 1333 $this->_fields = [];
0495f30c 1334 return $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array::value('pledge_payment_id', $params));
43bf07d6 1335
f75f0921 1336 }
c1cc3e0c 1337
f75f0921
EM
1338 /**
1339 * @param array $submittedValues
1340 *
bdbc1044
EM
1341 * @param int $action
1342 * Action constant
1343 * - CRM_Core_Action::UPDATE
1344 *
5e27919e
EM
1345 * @param $pledgePaymentID
1346 *
f75f0921
EM
1347 * @return array
1348 * @throws \Exception
1349 */
31760f81 1350 protected function submit($submittedValues, $action, $pledgePaymentID) {
f75f0921 1351 $pId = $contribution = $isRelatedId = FALSE;
3b8e6c3f 1352 $this->_params = $submittedValues;
1353 $this->beginPostProcess();
a55e39e9 1354 // reassign submitted form values if the any information is formatted via beginPostProcess
1355 $submittedValues = $this->_params;
3e6a1f4a 1356
bdbc1044 1357 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action::UPDATE) {
f75f0921
EM
1358 $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
1359 $lineID = key($line);
1360 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
1361 $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
2b308818
DG
1362 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1363 // config should be treated the same.
f75f0921
EM
1364 if ($quickConfig) {
1365 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
1366 }
6a488035 1367 }
f75f0921
EM
1368
1369 // Process price set and get total amount and line items.
be2fb01f 1370 $lineItem = [];
f75f0921
EM
1371 $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
1372 if (empty($priceSetId) && !$this->_id) {
1373 $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1374 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
1375 $fieldID = key($this->_priceSet['fields']);
1376 $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
1377 $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1378 $submittedValues['price_' . $fieldID] = 1;
6a488035 1379 }
6a488035 1380
2b308818
DG
1381 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1382 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1383 // as a point of fragility rather than a logical 'if' clause.
f75f0921
EM
1384 if ($priceSetId) {
1385 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
f436577a 1386 $submittedValues, $lineItem[$priceSetId], NULL, $priceSetId);
f75f0921 1387 // Unset tax amount for offline 'is_quick_config' contribution.
2b308818
DG
1388 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1389 // this is an example of 'other' functionality being hung off it.
f75f0921
EM
1390 if ($this->_priceSet['is_quick_config'] &&
1391 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())
1392 ) {
1393 unset($submittedValues['tax_amount']);
1394 }
1395 $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
6a488035 1396 }
189f0360 1397
f75f0921
EM
1398 if ($this->_id) {
1399 if ($this->_compId) {
1400 if ($this->_context == 'participant') {
1401 $pId = $this->_compId;
1402 }
1403 elseif ($this->_context == 'membership') {
1404 $isRelatedId = TRUE;
1405 }
1406 else {
1407 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
1408 }
c1cc3e0c 1409 }
f75f0921
EM
1410 else {
1411 $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1412 if (array_key_exists('membership', $contributionDetails)) {
1413 $isRelatedId = TRUE;
c1cc3e0c 1414 }
f75f0921
EM
1415 elseif (array_key_exists('participant', $contributionDetails)) {
1416 $pId = $contributionDetails['participant'];
c1cc3e0c 1417 }
6a488035 1418 }
17d83f50 1419 if (!empty($this->_payNow)) {
1420 $this->_params['contribution_id'] = $this->_id;
1421 }
6a488035 1422 }
2b308818 1423
f75f0921
EM
1424 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
1425 // CRM-10117 update the line items for participants.
2b308818
DG
1426 // @todo - if we are completing a contribution then the api call
1427 // civicrm_api3('Contribution', 'completetransaction') should take care of
1428 // all associated updates rather than replicating them on the form layer.
f75f0921
EM
1429 if ($pId) {
1430 $entityTable = 'participant';
1431 $entityID = $pId;
1432 $isRelatedId = FALSE;
be2fb01f 1433 $participantParams = [
f75f0921
EM
1434 'fee_amount' => $submittedValues['total_amount'],
1435 'id' => $entityID,
be2fb01f 1436 ];
f75f0921
EM
1437 CRM_Event_BAO_Participant::add($participantParams);
1438 if (empty($this->_lineItems)) {
77dbdcbc 1439 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', TRUE);
f75f0921
EM
1440 }
1441 }
1442 else {
1443 $entityTable = 'contribution';
1444 $entityID = $this->_id;
1445 }
6a488035 1446
77dbdcbc 1447 $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
f75f0921
EM
1448 foreach (array_keys($lineItems) as $id) {
1449 $lineItems[$id]['id'] = $id;
1450 }
1451 $itemId = key($lineItems);
1452 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1453 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1454 }
6a488035 1455
2b308818
DG
1456 // @todo see above - new functionality has been inappropriately added to the quick config concept
1457 // and new functionality has been added onto the form layer rather than the BAO :-(
f75f0921 1458 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
f85b8063
KJ
1459 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1460 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
a5b08a92 1461 if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
f85b8063
KJ
1462 if (!($this->_action & CRM_Core_Action::UPDATE && (($this->_defaults['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1463 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
1464 }
1465 }
6a488035 1466
f75f0921
EM
1467 // Update line total and total amount with tax on edit.
1468 $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
1469 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1470 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1471 }
1472 else {
1473 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1474 $submittedValues['tax_amount'] = 'null';
1475 }
1476 if ($lineItems[$itemId]['tax_rate']) {
1477 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1478 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
1479 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1480 }
1481 }
1482 // CRM-10117 update the line items for participants.
1483 if (!empty($lineItems[$itemId]['price_field_id'])) {
1484 $lineItem[$this->_priceSetId] = $lineItems;
1485 }
6a488035
TO
1486 }
1487
f75f0921
EM
1488 $isQuickConfig = 0;
1489 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1490 $isQuickConfig = 1;
6a488035 1491 }
f75f0921
EM
1492 //CRM-11529 for quick config back office transactions
1493 //when financial_type_id is passed in form, update the
1494 //line items with the financial type selected in form
2b308818
DG
1495 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1496 // we should look at having a price field per contribution type & then there would be little reason
1497 // for the back-office contribution form postProcess to know if it is a quick-config form.
f75f0921
EM
1498 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)
1499 ) {
1500 foreach ($lineItem[$this->_priceSetId] as &$values) {
1501 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1502 }
6a488035
TO
1503 }
1504
f75f0921 1505 if (!isset($submittedValues['total_amount'])) {
7c002a4d 1506 $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
1507 // Avoid tax amount deduction on edit form and keep it original, because this will lead to error described in CRM-20676
1508 if (!$this->_id) {
1509 $submittedValues['total_amount'] -= CRM_Utils_Array::value('tax_amount', $this->_values, 0);
1510 }
6a488035 1511 }
f75f0921 1512 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
6a488035 1513
f75f0921
EM
1514 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1515 if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
be2fb01f 1516 civicrm_api3('ContributionSoft', 'get', ['contribution_id' => $this->_id, 'pcp_id' => NULL, 'api.ContributionSoft.delete' => 1]);
f75f0921 1517 }
c1cc3e0c 1518
f75f0921
EM
1519 // set the contact, when contact is selected
1520 if (!empty($submittedValues['contact_id'])) {
1521 $this->_contactID = $submittedValues['contact_id'];
c1cc3e0c 1522 }
7a13735b 1523
3e6a1f4a 1524 $formValues = $submittedValues;
96025800 1525
f75f0921 1526 // Credit Card Contribution.
a5399a39 1527 if ($this->_mode) {
be2fb01f 1528 $paramsSetByPaymentProcessingSubsystem = [
bf4253e7
EM
1529 'trxn_id',
1530 'payment_instrument_id',
1531 'contribution_status_id',
1532 'cancel_date',
1533 'cancel_reason',
be2fb01f 1534 ];
bf4253e7
EM
1535 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1536 if (isset($formValues[$key])) {
1537 unset($formValues[$key]);
1538 }
1539 }
7126b55c 1540 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID);
bf4253e7
EM
1541 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1542 $formValues[$key] = $contribution->$key;
1543 }
a5399a39 1544 }
f75f0921
EM
1545 else {
1546 // Offline Contribution.
1547 $submittedValues = $this->unsetCreditCardFields($submittedValues);
a5399a39 1548
f75f0921 1549 // get the required field value only.
3e6a1f4a 1550
66ea9833 1551 $params = [
1552 'contact_id' => $this->_contactID,
1553 'currency' => $this->getCurrency($submittedValues),
1554 'skipCleanMoney' => TRUE,
1555 'id' => $this->_id,
1556 ];
a5399a39 1557
7a13735b 1558 //format soft-credit/pcp param first
1559 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($submittedValues, $this);
1560 $params = array_merge($params, $submittedValues);
1561
be2fb01f 1562 $fields = [
f75f0921
EM
1563 'financial_type_id',
1564 'contribution_status_id',
1565 'payment_instrument_id',
1566 'cancel_reason',
1567 'source',
1568 'check_number',
a55e39e9 1569 'card_type_id',
1570 'pan_truncation',
be2fb01f 1571 ];
f75f0921
EM
1572 foreach ($fields as $f) {
1573 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1574 }
a5399a39 1575
46d173ef
PN
1576 $params['revenue_recognition_date'] = NULL;
1577 if (!empty($formValues['revenue_recognition_date'])
1578 && count(array_filter($formValues['revenue_recognition_date'])) == 2
1579 ) {
1580 $params['revenue_recognition_date'] = CRM_Utils_Date::processDate(
1581 '01-' . implode('-', $formValues['revenue_recognition_date'])
1582 );
1583 }
f75f0921
EM
1584
1585 if (!empty($formValues['is_email_receipt'])) {
1586 $params['receipt_date'] = date("Y-m-d");
1587 }
1588
d682fc35 1589 if (CRM_Contribute_BAO_Contribution::isContributionStatusNegative($params['contribution_status_id'])
f75f0921
EM
1590 ) {
1591 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
b53052cb 1592 $params['cancel_date'] = date('YmdHis');
f75f0921
EM
1593 }
1594 }
1595 else {
1596 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1597 }
1598
1599 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1600 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
f527e012 1601 if ($params['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
f75f0921
EM
1602 $params['is_pay_later'] = 1;
1603 }
f527e012 1604 elseif ($params['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
f75f0921
EM
1605 $params['is_pay_later'] = 0;
1606 }
1607
f75f0921
EM
1608 // Add Additional common information to formatted params.
1609 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
1610 if ($pId) {
1611 $params['contribution_mode'] = 'participant';
1612 $params['participant_id'] = $pId;
1613 $params['skipLineItem'] = 1;
1614 }
1615 elseif ($isRelatedId) {
1616 $params['contribution_mode'] = 'membership';
1617 }
1618 $params['line_item'] = $lineItem;
1619 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
2e813c49 1620 $params['tax_amount'] = CRM_Utils_Array::value('tax_amount', $submittedValues, CRM_Utils_Array::value('tax_amount', $this->_values));
f75f0921
EM
1621 //create contribution.
1622 if ($isQuickConfig) {
1623 $params['is_quick_config'] = 1;
1624 }
07dd658b 1625 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
f75f0921 1626
7fd21004 1627 // we are already handling note below, so to avoid duplicate notes against $contribution
1628 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1629 unset($params['note']);
1630 }
66ea9833 1631 $contribution = CRM_Contribute_BAO_Contribution::create($params);
f75f0921
EM
1632
1633 // process associated membership / participant, CRM-4395
bdbc1044 1634 if ($contribution->id && $action & CRM_Core_Action::UPDATE) {
643413a0 1635 $this->statusMessage[] = CRM_Contribute_BAO_Contribution::transitionComponentWithReturnMessage($contribution->id,
f75f0921
EM
1636 $contribution->contribution_status_id,
1637 CRM_Utils_Array::value('contribution_status_id',
1638 $this->_values
1639 ),
1640 $contribution->receive_date
1641 );
1642 }
1643
3e6a1f4a 1644 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
f75f0921 1645
6d4f5b21 1646 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
f75f0921
EM
1647
1648 //send receipt mail.
1649 if ($contribution->id && !empty($formValues['is_email_receipt'])) {
1650 $formValues['contact_id'] = $this->_contactID;
1651 $formValues['contribution_id'] = $contribution->id;
1652
1653 $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
1654
1655 // to get 'from email id' for send receipt
beac1417 1656 $this->fromEmailId = CRM_Utils_Array::value('from_email_address', $formValues);
5e27919e 1657 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues)) {
3e6a1f4a 1658 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
5e27919e 1659 }
f75f0921
EM
1660 }
1661
7e5961cf
EM
1662 $this->statusMessageTitle = ts('Saved');
1663
f75f0921 1664 }
5e27919e 1665
99af166d 1666 if ($contribution->id && isset($formValues['product_name'][0])) {
2dcbf765 1667 CRM_Contribute_Form_AdditionalInfo::processPremium($submittedValues, $contribution->id,
945f423d
EM
1668 $this->_premiumID, $this->_options
1669 );
1670 }
1671
dce847cf 1672 if ($contribution->id && array_key_exists('note', $submittedValues)) {
945f423d
EM
1673 CRM_Contribute_Form_AdditionalInfo::processNote($submittedValues, $this->_contactID, $contribution->id, $this->_noteID);
1674 }
1675
3e6a1f4a 1676 CRM_Core_Session::setStatus(implode(' ', $this->statusMessage), $this->statusMessageTitle, 'success');
7e5961cf 1677
5e27919e
EM
1678 CRM_Contribute_BAO_Contribution::updateRelatedPledge(
1679 $action,
1680 $pledgePaymentID,
1681 $contribution->id,
1682 (CRM_Utils_Array::value('option_type', $formValues) == 2) ? TRUE : FALSE,
1683 $formValues['total_amount'],
3e6a1f4a 1684 CRM_Utils_Array::value('total_amount', $this->_defaults),
5e27919e 1685 $formValues['contribution_status_id'],
3e6a1f4a 1686 CRM_Utils_Array::value('contribution_status_id', $this->_defaults)
5e27919e
EM
1687 );
1688 return $contribution;
2e03ce51
EM
1689 }
1690
6d4f5b21
EM
1691 /**
1692 * Assign tax calculations to contribution receipts.
1693 *
1694 * @param array $submittedValues
1695 * @param int $action
1696 * @param array $lineItem
1697 */
1698 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1699
aaffa79f 1700 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
6d4f5b21
EM
1701 if (!CRM_Utils_Array::value('invoicing', $invoiceSettings)) {
1702 return;
1703 }
be2fb01f 1704 $taxRate = [];
6d4f5b21 1705 $getTaxDetails = FALSE;
f1662cbd 1706
1707 foreach ($lineItem as $key => $value) {
6d4f5b21
EM
1708 foreach ($value as $v) {
1709 if (isset($taxRate[(string) CRM_Utils_Array::value('tax_rate', $v)])) {
1710 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array::value('tax_amount', $v);
1711 }
1712 else {
1713 if (isset($v['tax_rate'])) {
1714 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array::value('tax_amount', $v);
1715 $getTaxDetails = TRUE;
1716 }
1717 }
1718 }
1719 }
1720
1721 if ($action & CRM_Core_Action::UPDATE) {
1722 if (isset($submittedValues['tax_amount'])) {
1723 $totalTaxAmount = $submittedValues['tax_amount'];
1724 }
1725 else {
1726 $totalTaxAmount = $this->_values['tax_amount'];
1727 }
1728 $this->assign('totalTaxAmount', $totalTaxAmount);
1729 $this->assign('dataArray', $taxRate);
1730 }
1731 else {
1732 if (!empty($submittedValues['price_set_id'])) {
1733 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1734 $this->assign('getTaxDetails', $getTaxDetails);
1735 $this->assign('dataArray', $taxRate);
1736 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
1737 }
1738 else {
1739 $this->assign('totalTaxAmount', CRM_Utils_Array::value('tax_amount', $submittedValues));
1740 }
1741 }
1742 }
1743
07dd658b
EM
1744 /**
1745 * Calculate non deductible amount.
1746 *
1747 * CRM-11956
1748 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1749 * if non_deductible_amount does NOT exist - then calculate it depending on:
1750 * $financialType->is_deductible and whether there is a product (premium).
1751 *
1752 * @param $params
1753 * @param $formValues
1754 *
1755 * @return array
1756 */
1757 protected function calculateNonDeductibleAmount($params, $formValues) {
1758 if (!empty($params['non_deductible_amount'])) {
1759 return $params['non_deductible_amount'];
1760 }
5afce5ad 1761
05465712 1762 $priceSetId = CRM_Utils_Array::value('price_set_id', $params);
5afce5ad 1763 // return non-deductible amount if it is set at the price field option level
05465712 1764 if ($priceSetId && !empty($params['line_item'])) {
1765 $nonDeductibleAmount = CRM_Price_BAO_PriceSet::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1766 if (!empty($nonDeductibleAmount)) {
5afce5ad 1767 return $nonDeductibleAmount;
1768 }
1769 }
07dd658b 1770
f70eb51f
EM
1771 $financialType = new CRM_Financial_DAO_FinancialType();
1772 $financialType->id = $params['financial_type_id'];
11829025 1773 $financialType->find(TRUE);
07dd658b 1774
f70eb51f
EM
1775 if ($financialType->is_deductible) {
1776
1777 if (isset($formValues['product_name'][0])) {
1778 $selectProduct = $formValues['product_name'][0];
1779 }
1780 // if there is a product - compare the value to the contribution amount
1781 if (isset($selectProduct)) {
1782 $productDAO = new CRM_Contribute_DAO_Product();
1783 $productDAO->id = $selectProduct;
1784 $productDAO->find(TRUE);
1785 // product value exceeds contribution amount
1786 if ($params['total_amount'] < $productDAO->price) {
1787 return $params['total_amount'];
07dd658b 1788 }
f70eb51f 1789 // product value does NOT exceed contribution amount
07dd658b 1790 else {
f70eb51f 1791 return $productDAO->price;
07dd658b
EM
1792 }
1793 }
f70eb51f 1794 // contribution is deductible - but there is no product
07dd658b 1795 else {
f70eb51f 1796 return '0.00';
07dd658b
EM
1797 }
1798 }
f70eb51f
EM
1799 // contribution is NOT deductible
1800 else {
1801 return $params['total_amount'];
1802 }
1803
07dd658b
EM
1804 return 0;
1805 }
1806
6a488035 1807}