Merge pull request #9326 from eileenmcnaughton/cont_page_null
[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 );
1247
1248 if (empty($paymentParams['is_pay_later'])) {
1249 // @todo look up payment_instrument_id on payment processor table.
1250 $contributionParams['payment_instrument_id'] = 1;
1251 }
6a488035 1252
ba013eea 1253 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this,
7758bd2b
EM
1254 $this->_params,
1255 NULL,
3febe800 1256 $contributionParams,
7758bd2b 1257 $financialType,
7758bd2b 1258 FALSE,
449f4c90 1259 $this->_bltID,
1260 CRM_Utils_Array::value('is_recur', $this->_params)
7758bd2b 1261 );
6a488035 1262
7758bd2b
EM
1263 $paymentParams['contributionID'] = $contribution->id;
1264 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
1265 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1266 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
6a488035 1267
7758bd2b
EM
1268 if ($paymentParams['amount'] > 0.0) {
1269 // force a re-get of the payment processor in case the form changed it, CRM-7179
9d8f43b1
EM
1270 // NOTE - I expect this is obsolete.
1271 $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
7758bd2b
EM
1272 try {
1273 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
1274 $result = $payment->doPayment($paymentParams, 'contribute');
1275 $this->assign('trxn_id', $result['trxn_id']);
1276 $contribution->trxn_id = $result['trxn_id'];
1277 /* Our scenarios here are
1278 * 1) the payment failed & an Exception should have been thrown
1279 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1280 * with a delayed start)
1281 * 3) the payment succeeded with an immediate payment.
1282 *
7c85dc65 1283 * The doPayment function ensures that payment_status_id is always set
7758bd2b
EM
1284 * as historically we have had to guess from the context - ie doDirectPayment
1285 * = error or success, unless it is a recurring contribution in which case it is pending.
1286 */
7c85dc65 1287 if ($result['payment_status_id'] == array_search('Completed', $statuses)) {
760278d3
EM
1288 try {
1289 civicrm_api3('contribution', 'completetransaction', array(
1290 'id' => $contribution->id,
1291 'trxn_id' => $result['trxn_id'],
1292 'payment_processor_id' => $this->_paymentProcessor['id'],
1293 'is_transactional' => FALSE,
22e39333 1294 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
760278d3
EM
1295 ));
1296 // This has now been set to 1 in the DB - declare it here also
1297 $contribution->contribution_status_id = 1;
1298 }
1299 catch (CiviCRM_API3_Exception $e) {
1300 if ($e->getErrorCode() != 'contribution_completed') {
1301 throw new CRM_Core_Exception('Failed to update contribution in database');
1302 }
1303 }
7758bd2b
EM
1304 }
1305 else {
1306 // Save the trxn_id.
1307 $contribution->save();
1308 }
1309 }
1310 catch (PaymentProcessorException $e) {
06d062ce 1311 CRM_Contribute_BAO_Contribution::failPayment($contribution->id, $paymentParams['contactID'], $e->getMessage());
7758bd2b
EM
1312 throw new PaymentProcessorException($e->getMessage());
1313 }
1314 }
f75f0921 1315 // Send receipt mail.
e390a377 1316 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
f75f0921
EM
1317 if ($contribution->id && !empty($this->_params['is_email_receipt'])) {
1318 $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
7126b55c 1319 $this->_params['contact_id'] = $contactID;
f75f0921 1320 $this->_params['contribution_id'] = $contribution->id;
c52884b2 1321 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE)) {
3e6a1f4a 1322 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
6a488035 1323 }
28d44c9f 1324 }
c52884b2 1325
5e27919e 1326 return $contribution;
6a488035 1327 }
5a230af7 1328
f75f0921
EM
1329 /**
1330 * Generate the data to construct a snippet based pane.
1331 *
1332 * This form also assigns the showAdditionalInfo var based on historical code.
1333 * This appears to mean 'there is a pane to show'.
1334 *
1335 * @param string $type
1336 * Type of Pane - this is generally used to determine the function name used to build it
1337 * - e.g CreditCard, AdditionalDetail
1338 * @param array $defaults
1339 *
1340 * @return array
1341 * We aim to further refactor & simplify this but currently
1342 * - the panes array
1343 * - should additional info be shown?
1344 */
1345 protected function generatePane($type, $defaults) {
1346 $urlParams = "snippet=4&formType={$type}";
1347 if ($this->_mode) {
1348 $urlParams .= "&mode={$this->_mode}";
6a488035
TO
1349 }
1350
f75f0921
EM
1351 $open = 'false';
1352 if ($type == 'CreditCard' ||
1353 $type == 'DirectDebit'
1354 ) {
1355 $open = 'true';
6a488035 1356 }
6a488035 1357
f75f0921
EM
1358 $pane = array(
1359 'url' => CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams),
1360 'open' => $open,
1361 'id' => $type,
6a488035 1362 );
6a488035 1363
f75f0921
EM
1364 // See if we need to include this paneName in the current form.
1365 if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) ||
1366 CRM_Utils_Array::value("hidden_{$type}", $defaults)
1367 ) {
1368 $this->assign('showAdditionalInfo', TRUE);
1369 $pane['open'] = 'true';
6a488035
TO
1370 }
1371
f75f0921
EM
1372 if ($type == 'CreditCard' || $type == 'DirectDebit') {
1373 // @todo would be good to align tpl name with form name...
1374 // @todo document why this hidden variable is required.
1375 $this->add('hidden', 'hidden_' . $type, 1);
1376 return $pane;
6a488035
TO
1377 }
1378 else {
f75f0921
EM
1379 $additionalInfoFormFunction = 'build' . $type;
1380 CRM_Contribute_Form_AdditionalInfo::$additionalInfoFormFunction($this);
1381 return $pane;
6a488035 1382 }
f75f0921 1383 }
6a488035 1384
f75f0921
EM
1385 /**
1386 * Wrapper for unit testing the post process submit function.
1387 *
1388 * (If we expose through api we can get default additions 'for free').
1389 *
1390 * @param array $params
5e27919e 1391 * @param int $action
39f47c0d
EM
1392 * @param string|null $creditCardMode
1393 *
1394 * @throws \CiviCRM_API3_Exception
f75f0921 1395 */
39f47c0d 1396 public function testSubmit($params, $action, $creditCardMode = NULL) {
f75f0921
EM
1397 $defaults = array(
1398 'soft_credit_contact_id' => array(),
1399 'receipt_date' => '',
1400 'receipt_date_time' => '',
1401 'cancel_date' => '',
1402 'cancel_date_time' => '',
43bf07d6 1403 'hidden_Premium' => 1,
f75f0921 1404 );
739a8336 1405 $this->_bltID = 5;
5e27919e
EM
1406 if (!empty($params['id'])) {
1407 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1408 'id' => $params['id'],
1409 ));
55e55e84 1410 $this->_id = $params['id'];
5e27919e
EM
1411 }
1412 else {
1413 $existingContribution = array();
1414 }
1415
1416 $this->_defaults['contribution_status_id'] = CRM_Utils_Array::value('contribution_status_id',
1417 $existingContribution
1418 );
1419
1420 $this->_defaults['total_amount'] = CRM_Utils_Array::value('total_amount',
1421 $existingContribution
1422 );
6a488035 1423
39f47c0d
EM
1424 if ($creditCardMode) {
1425 $this->_mode = $creditCardMode;
1426 }
1427
1428 // Required because processCreditCard calls set method on this.
1429 $_SERVER['REQUEST_METHOD'] = 'GET';
1430 $this->controller = new CRM_Core_Controller();
1431
3e6a1f4a
EM
1432 CRM_Contribute_Form_AdditionalInfo::buildPremium($this);
1433
39f47c0d 1434 $this->_fields = array();
31760f81 1435 $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array::value('pledge_payment_id', $params));
43bf07d6 1436
f75f0921 1437 }
c1cc3e0c 1438
f75f0921
EM
1439 /**
1440 * @param array $submittedValues
1441 *
bdbc1044
EM
1442 * @param int $action
1443 * Action constant
1444 * - CRM_Core_Action::UPDATE
1445 *
5e27919e
EM
1446 * @param $pledgePaymentID
1447 *
f75f0921
EM
1448 * @return array
1449 * @throws \Exception
1450 */
31760f81 1451 protected function submit($submittedValues, $action, $pledgePaymentID) {
f75f0921
EM
1452 $softParams = $softIDs = array();
1453 $pId = $contribution = $isRelatedId = FALSE;
3b8e6c3f 1454 $this->_params = $submittedValues;
1455 $this->beginPostProcess();
3e6a1f4a 1456
bdbc1044 1457 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action::UPDATE) {
f75f0921
EM
1458 $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
1459 $lineID = key($line);
1460 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
1461 $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
2b308818
DG
1462 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1463 // config should be treated the same.
f75f0921
EM
1464 if ($quickConfig) {
1465 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
1466 }
6a488035 1467 }
f75f0921
EM
1468
1469 // Process price set and get total amount and line items.
1470 $lineItem = array();
1471 $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
1472 if (empty($priceSetId) && !$this->_id) {
1473 $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1474 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
1475 $fieldID = key($this->_priceSet['fields']);
1476 $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
1477 $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1478 $submittedValues['price_' . $fieldID] = 1;
6a488035 1479 }
6a488035 1480
2b308818
DG
1481 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1482 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1483 // as a point of fragility rather than a logical 'if' clause.
f75f0921
EM
1484 if ($priceSetId) {
1485 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
1486 $submittedValues, $lineItem[$priceSetId]);
f75f0921 1487 // Unset tax amount for offline 'is_quick_config' contribution.
2b308818
DG
1488 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1489 // this is an example of 'other' functionality being hung off it.
f75f0921
EM
1490 if ($this->_priceSet['is_quick_config'] &&
1491 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())
1492 ) {
1493 unset($submittedValues['tax_amount']);
1494 }
1495 $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
6a488035 1496 }
f75f0921
EM
1497 if ($this->_id) {
1498 if ($this->_compId) {
1499 if ($this->_context == 'participant') {
1500 $pId = $this->_compId;
1501 }
1502 elseif ($this->_context == 'membership') {
1503 $isRelatedId = TRUE;
1504 }
1505 else {
1506 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
1507 }
c1cc3e0c 1508 }
f75f0921
EM
1509 else {
1510 $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1511 if (array_key_exists('membership', $contributionDetails)) {
1512 $isRelatedId = TRUE;
c1cc3e0c 1513 }
f75f0921
EM
1514 elseif (array_key_exists('participant', $contributionDetails)) {
1515 $pId = $contributionDetails['participant'];
c1cc3e0c 1516 }
6a488035 1517 }
17d83f50 1518 if (!empty($this->_payNow)) {
1519 $this->_params['contribution_id'] = $this->_id;
1520 }
6a488035 1521 }
2b308818 1522
f75f0921
EM
1523 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
1524 // CRM-10117 update the line items for participants.
2b308818
DG
1525 // @todo - if we are completing a contribution then the api call
1526 // civicrm_api3('Contribution', 'completetransaction') should take care of
1527 // all associated updates rather than replicating them on the form layer.
f75f0921
EM
1528 if ($pId) {
1529 $entityTable = 'participant';
1530 $entityID = $pId;
1531 $isRelatedId = FALSE;
1532 $participantParams = array(
1533 'fee_amount' => $submittedValues['total_amount'],
1534 'id' => $entityID,
1535 );
1536 CRM_Event_BAO_Participant::add($participantParams);
1537 if (empty($this->_lineItems)) {
1538 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
1539 }
1540 }
1541 else {
1542 $entityTable = 'contribution';
1543 $entityID = $this->_id;
1544 }
6a488035 1545
f75f0921
EM
1546 $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
1547 foreach (array_keys($lineItems) as $id) {
1548 $lineItems[$id]['id'] = $id;
1549 }
1550 $itemId = key($lineItems);
1551 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1552 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1553 }
6a488035 1554
2b308818
DG
1555 // @todo see above - new functionality has been inappropriately added to the quick config concept
1556 // and new functionality has been added onto the form layer rather than the BAO :-(
f75f0921 1557 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
f85b8063
KJ
1558 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1559 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
a5b08a92 1560 if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
f85b8063
KJ
1561 if (!($this->_action & CRM_Core_Action::UPDATE && (($this->_defaults['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1562 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
1563 }
1564 }
6a488035 1565
f75f0921
EM
1566 // Update line total and total amount with tax on edit.
1567 $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
1568 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1569 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1570 }
1571 else {
1572 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1573 $submittedValues['tax_amount'] = 'null';
1574 }
1575 if ($lineItems[$itemId]['tax_rate']) {
1576 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1577 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
1578 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1579 }
1580 }
1581 // CRM-10117 update the line items for participants.
1582 if (!empty($lineItems[$itemId]['price_field_id'])) {
1583 $lineItem[$this->_priceSetId] = $lineItems;
1584 }
6a488035
TO
1585 }
1586
f75f0921
EM
1587 $isQuickConfig = 0;
1588 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1589 $isQuickConfig = 1;
6a488035 1590 }
f75f0921
EM
1591 //CRM-11529 for quick config back office transactions
1592 //when financial_type_id is passed in form, update the
1593 //line items with the financial type selected in form
2b308818
DG
1594 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1595 // we should look at having a price field per contribution type & then there would be little reason
1596 // for the back-office contribution form postProcess to know if it is a quick-config form.
f75f0921
EM
1597 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)
1598 ) {
1599 foreach ($lineItem[$this->_priceSetId] as &$values) {
1600 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1601 }
6a488035
TO
1602 }
1603
f75f0921
EM
1604 if (!isset($submittedValues['total_amount'])) {
1605 $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
6a488035 1606 }
f75f0921 1607 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
6a488035 1608
f75f0921
EM
1609 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1610 if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
1611 //Delete existing soft credit records if soft credit list is empty on update
f85b8063 1612 CRM_Contribute_BAO_ContributionSoft::del(array('contribution_id' => $this->_id, 'pcp_id' => 0));
f75f0921 1613 }
c1cc3e0c 1614
f75f0921
EM
1615 // set the contact, when contact is selected
1616 if (!empty($submittedValues['contact_id'])) {
1617 $this->_contactID = $submittedValues['contact_id'];
c1cc3e0c 1618 }
7a13735b 1619
3e6a1f4a 1620 $formValues = $submittedValues;
96025800 1621
f75f0921 1622 // Credit Card Contribution.
a5399a39 1623 if ($this->_mode) {
bf4253e7
EM
1624 $paramsSetByPaymentProcessingSubsystem = array(
1625 'trxn_id',
1626 'payment_instrument_id',
1627 'contribution_status_id',
1628 'cancel_date',
1629 'cancel_reason',
1630 );
1631 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1632 if (isset($formValues[$key])) {
1633 unset($formValues[$key]);
1634 }
1635 }
7126b55c 1636 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID);
bf4253e7
EM
1637 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1638 $formValues[$key] = $contribution->$key;
1639 }
a5399a39 1640 }
f75f0921
EM
1641 else {
1642 // Offline Contribution.
1643 $submittedValues = $this->unsetCreditCardFields($submittedValues);
a5399a39 1644
f75f0921 1645 // get the required field value only.
3e6a1f4a 1646
f75f0921 1647 $params = $ids = array();
a5399a39 1648
f75f0921 1649 $params['contact_id'] = $this->_contactID;
f75f0921 1650 $params['currency'] = $this->getCurrency($submittedValues);
a5399a39 1651
7a13735b 1652 //format soft-credit/pcp param first
1653 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($submittedValues, $this);
1654 $params = array_merge($params, $submittedValues);
1655
f75f0921
EM
1656 $fields = array(
1657 'financial_type_id',
1658 'contribution_status_id',
1659 'payment_instrument_id',
1660 'cancel_reason',
1661 'source',
1662 'check_number',
1663 );
1664 foreach ($fields as $f) {
1665 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1666 }
a5399a39 1667
f75f0921
EM
1668 // CRM-5740 if priceset is used, no need to cleanup money.
1669 if ($priceSetId) {
1670 $params['skipCleanMoney'] = 1;
1671 }
46d173ef
PN
1672 $params['revenue_recognition_date'] = NULL;
1673 if (!empty($formValues['revenue_recognition_date'])
1674 && count(array_filter($formValues['revenue_recognition_date'])) == 2
1675 ) {
1676 $params['revenue_recognition_date'] = CRM_Utils_Date::processDate(
1677 '01-' . implode('-', $formValues['revenue_recognition_date'])
1678 );
1679 }
f75f0921
EM
1680 $dates = array(
1681 'receive_date',
1682 'receipt_date',
1683 'cancel_date',
1684 );
1685
1686 foreach ($dates as $d) {
46d173ef
PN
1687 if (isset($formValues[$d])) {
1688 $params[$d] = CRM_Utils_Date::processDate($formValues[$d], CRM_Utils_Array::value($d . '_time', $formValues), TRUE);
1689 }
f75f0921
EM
1690 }
1691
1692 if (!empty($formValues['is_email_receipt'])) {
1693 $params['receipt_date'] = date("Y-m-d");
1694 }
1695
d682fc35 1696 if (CRM_Contribute_BAO_Contribution::isContributionStatusNegative($params['contribution_status_id'])
f75f0921
EM
1697 ) {
1698 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
b53052cb 1699 $params['cancel_date'] = date('YmdHis');
f75f0921
EM
1700 }
1701 }
1702 else {
1703 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1704 }
1705
1706 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1707 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1708 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
1709 $params['is_pay_later'] = 1;
1710 }
1711 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
1712 $params['is_pay_later'] = 0;
1713 }
1714
1715 $ids['contribution'] = $params['id'] = $this->_id;
1716
1717 // Add Additional common information to formatted params.
1718 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
1719 if ($pId) {
1720 $params['contribution_mode'] = 'participant';
1721 $params['participant_id'] = $pId;
1722 $params['skipLineItem'] = 1;
1723 }
1724 elseif ($isRelatedId) {
1725 $params['contribution_mode'] = 'membership';
1726 }
1727 $params['line_item'] = $lineItem;
1728 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
1729 if (isset($submittedValues['tax_amount'])) {
1730 $params['tax_amount'] = $submittedValues['tax_amount'];
1731 }
1732 //create contribution.
1733 if ($isQuickConfig) {
1734 $params['is_quick_config'] = 1;
1735 }
07dd658b 1736 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
f75f0921 1737
7fd21004 1738 // we are already handling note below, so to avoid duplicate notes against $contribution
1739 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1740 unset($params['note']);
1741 }
f75f0921
EM
1742 $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
1743
1744 // process associated membership / participant, CRM-4395
bdbc1044 1745 if ($contribution->id && $action & CRM_Core_Action::UPDATE) {
643413a0 1746 $this->statusMessage[] = CRM_Contribute_BAO_Contribution::transitionComponentWithReturnMessage($contribution->id,
f75f0921
EM
1747 $contribution->contribution_status_id,
1748 CRM_Utils_Array::value('contribution_status_id',
1749 $this->_values
1750 ),
1751 $contribution->receive_date
1752 );
1753 }
1754
3e6a1f4a 1755 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
f75f0921 1756
6d4f5b21 1757 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
f75f0921
EM
1758
1759 //send receipt mail.
1760 if ($contribution->id && !empty($formValues['is_email_receipt'])) {
1761 $formValues['contact_id'] = $this->_contactID;
1762 $formValues['contribution_id'] = $contribution->id;
1763
1764 $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
1765
1766 // to get 'from email id' for send receipt
1767 $this->fromEmailId = $formValues['from_email_address'];
5e27919e 1768 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues)) {
3e6a1f4a 1769 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
5e27919e 1770 }
f75f0921
EM
1771 }
1772
7e5961cf
EM
1773 $this->statusMessageTitle = ts('Saved');
1774
f75f0921 1775 }
5e27919e 1776
99af166d 1777 if ($contribution->id && isset($formValues['product_name'][0])) {
2dcbf765 1778 CRM_Contribute_Form_AdditionalInfo::processPremium($submittedValues, $contribution->id,
945f423d
EM
1779 $this->_premiumID, $this->_options
1780 );
1781 }
1782
7fd21004 1783 if ($contribution->id && !empty($submittedValues['note'])) {
945f423d
EM
1784 CRM_Contribute_Form_AdditionalInfo::processNote($submittedValues, $this->_contactID, $contribution->id, $this->_noteID);
1785 }
1786
3e6a1f4a 1787 CRM_Core_Session::setStatus(implode(' ', $this->statusMessage), $this->statusMessageTitle, 'success');
7e5961cf 1788
5e27919e
EM
1789 CRM_Contribute_BAO_Contribution::updateRelatedPledge(
1790 $action,
1791 $pledgePaymentID,
1792 $contribution->id,
1793 (CRM_Utils_Array::value('option_type', $formValues) == 2) ? TRUE : FALSE,
1794 $formValues['total_amount'],
3e6a1f4a 1795 CRM_Utils_Array::value('total_amount', $this->_defaults),
5e27919e 1796 $formValues['contribution_status_id'],
3e6a1f4a 1797 CRM_Utils_Array::value('contribution_status_id', $this->_defaults)
5e27919e
EM
1798 );
1799 return $contribution;
2e03ce51
EM
1800 }
1801
6d4f5b21
EM
1802 /**
1803 * Assign tax calculations to contribution receipts.
1804 *
1805 * @param array $submittedValues
1806 * @param int $action
1807 * @param array $lineItem
1808 */
1809 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1810
aaffa79f 1811 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
6d4f5b21
EM
1812 if (!CRM_Utils_Array::value('invoicing', $invoiceSettings)) {
1813 return;
1814 }
1815 $taxRate = array();
1816 $getTaxDetails = FALSE;
1817 if ($action & CRM_Core_Action::ADD) {
1818 $line = $lineItem;
1819 }
1820 elseif ($action & CRM_Core_Action::UPDATE) {
1821 $line = $this->_lineItems;
1822 }
1823 foreach ($line as $key => $value) {
1824 foreach ($value as $v) {
1825 if (isset($taxRate[(string) CRM_Utils_Array::value('tax_rate', $v)])) {
1826 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array::value('tax_amount', $v);
1827 }
1828 else {
1829 if (isset($v['tax_rate'])) {
1830 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array::value('tax_amount', $v);
1831 $getTaxDetails = TRUE;
1832 }
1833 }
1834 }
1835 }
1836
1837 if ($action & CRM_Core_Action::UPDATE) {
1838 if (isset($submittedValues['tax_amount'])) {
1839 $totalTaxAmount = $submittedValues['tax_amount'];
1840 }
1841 else {
1842 $totalTaxAmount = $this->_values['tax_amount'];
1843 }
1844 $this->assign('totalTaxAmount', $totalTaxAmount);
1845 $this->assign('dataArray', $taxRate);
1846 }
1847 else {
1848 if (!empty($submittedValues['price_set_id'])) {
1849 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1850 $this->assign('getTaxDetails', $getTaxDetails);
1851 $this->assign('dataArray', $taxRate);
1852 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
1853 }
1854 else {
1855 $this->assign('totalTaxAmount', CRM_Utils_Array::value('tax_amount', $submittedValues));
1856 }
1857 }
1858 }
1859
07dd658b
EM
1860 /**
1861 * Calculate non deductible amount.
1862 *
1863 * CRM-11956
1864 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1865 * if non_deductible_amount does NOT exist - then calculate it depending on:
1866 * $financialType->is_deductible and whether there is a product (premium).
1867 *
1868 * @param $params
1869 * @param $formValues
1870 *
1871 * @return array
1872 */
1873 protected function calculateNonDeductibleAmount($params, $formValues) {
1874 if (!empty($params['non_deductible_amount'])) {
1875 return $params['non_deductible_amount'];
1876 }
5afce5ad 1877
05465712 1878 $priceSetId = CRM_Utils_Array::value('price_set_id', $params);
5afce5ad 1879 // return non-deductible amount if it is set at the price field option level
05465712 1880 if ($priceSetId && !empty($params['line_item'])) {
1881 $nonDeductibleAmount = CRM_Price_BAO_PriceSet::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1882 if (!empty($nonDeductibleAmount)) {
5afce5ad 1883 return $nonDeductibleAmount;
1884 }
1885 }
07dd658b 1886
f70eb51f
EM
1887 $financialType = new CRM_Financial_DAO_FinancialType();
1888 $financialType->id = $params['financial_type_id'];
11829025 1889 $financialType->find(TRUE);
07dd658b 1890
f70eb51f
EM
1891 if ($financialType->is_deductible) {
1892
1893 if (isset($formValues['product_name'][0])) {
1894 $selectProduct = $formValues['product_name'][0];
1895 }
1896 // if there is a product - compare the value to the contribution amount
1897 if (isset($selectProduct)) {
1898 $productDAO = new CRM_Contribute_DAO_Product();
1899 $productDAO->id = $selectProduct;
1900 $productDAO->find(TRUE);
1901 // product value exceeds contribution amount
1902 if ($params['total_amount'] < $productDAO->price) {
1903 return $params['total_amount'];
07dd658b 1904 }
f70eb51f 1905 // product value does NOT exceed contribution amount
07dd658b 1906 else {
f70eb51f 1907 return $productDAO->price;
07dd658b
EM
1908 }
1909 }
f70eb51f 1910 // contribution is deductible - but there is no product
07dd658b 1911 else {
f70eb51f 1912 return '0.00';
07dd658b
EM
1913 }
1914 }
f70eb51f
EM
1915 // contribution is NOT deductible
1916 else {
1917 return $params['total_amount'];
1918 }
1919
07dd658b
EM
1920 return 0;
1921 }
1922
6a488035 1923}