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