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