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