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