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