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