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