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