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