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