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