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