Merge pull request #14024 from civicrm/5.13
[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 * @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 * @var integer
137 */
138 public $fromEmailId;
139
140 /**
141 * Store the line items if price set used.
142 * @var array
143 */
144 public $_lineItems;
145
146 /**
147 * Line item
148 * @var array
149 * @todo explain why we use lineItem & lineItems
150 */
151 public $_lineItem;
152
153 /**
154 * @var array soft credit info
155 */
156 public $_softCreditInfo;
157
158 protected $_formType;
159
160 /**
161 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
162 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
163 *
164 * @var array
165 */
166 public $_paymentFields = [];
167 /**
168 * Logged in user's email.
169 * @var string
170 */
171 public $userEmail;
172
173 /**
174 * Price set ID
175 * @var integer
176 */
177 public $_priceSetId;
178
179 /**
180 * Price set as an array
181 * @var array
182 */
183 public $_priceSet;
184
185 /**
186 * User display name
187 *
188 * @var string
189 */
190 public $userDisplayName;
191
192 /**
193 * Status message to be shown to the user.
194 *
195 * @var array
196 */
197 protected $statusMessage = [];
198
199 /**
200 * Status message title to be shown to the user.
201 *
202 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
203 * although this might not be a good fit with the broad range of processors.
204 *
205 * @var string
206 */
207 protected $statusMessageTitle;
208
209 /**
210 * @var int
211 *
212 * Max row count for soft credits. The value here is +1 the actual number of
213 * rows displayed.
214 */
215 public $_softCreditItemCount = 11;
216
217 /**
218 * Explicitly declare the form context.
219 */
220 public function getDefaultContext() {
221 return 'create';
222 }
223
224 /**
225 * Set variables up before form is built.
226 */
227 public function preProcess() {
228 // Check permission for action.
229 if (!CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
230 // @todo replace with throw new CRM_Core_Exception().
231 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
232 }
233
234 parent::preProcess();
235
236 $this->_formType = CRM_Utils_Array::value('formType', $_GET);
237
238 // Get price set id.
239 $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
240 $this->set('priceSetId', $this->_priceSetId);
241 $this->assign('priceSetId', $this->_priceSetId);
242
243 // Get the pledge payment id
244 $this->_ppID = CRM_Utils_Request::retrieve('ppid', 'Positive', $this);
245
246 $this->assign('action', $this->_action);
247
248 // Get the contribution id if update
249 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
250 if (!empty($this->_id)) {
251 $this->assignPaymentInfoBlock();
252 $this->assign('contribID', $this->_id);
253 $this->assign('isUsePaymentBlock', TRUE);
254 }
255
256 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
257 $this->assign('context', $this->_context);
258
259 $this->_compId = CRM_Utils_Request::retrieve('compId', 'Positive', $this);
260
261 $this->_compContext = CRM_Utils_Request::retrieve('compContext', 'String', $this);
262
263 //set the contribution mode.
264 $this->_mode = CRM_Utils_Request::retrieve('mode', 'Alphanumeric', $this);
265
266 $this->assign('contributionMode', $this->_mode);
267 if ($this->_action & CRM_Core_Action::DELETE) {
268 return;
269 }
270
271 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
272
273 if (in_array('CiviPledge', CRM_Core_Config::singleton()->enableComponents) && !$this->_formType) {
274 $this->preProcessPledge();
275 }
276
277 if ($this->_id) {
278 $this->showRecordLinkMesssage($this->_id);
279 }
280 $this->_values = [];
281
282 // Current contribution id.
283 if ($this->_id) {
284 $this->assignPremiumProduct($this->_id);
285 $this->buildValuesAndAssignOnline_Note_Type($this->_id, $this->_values);
286 }
287
288 // when custom data is included in this page
289 if (!empty($_POST['hidden_custom'])) {
290 $this->applyCustomData('Contribution', CRM_Utils_Array::value('financial_type_id', $_POST), $this->_id);
291 }
292
293 $this->_lineItems = [];
294 if ($this->_id) {
295 if (!empty($this->_compId) && $this->_compContext == 'participant') {
296 $this->assign('compId', $this->_compId);
297 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_compId);
298 }
299 else {
300 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution', 1, TRUE, TRUE);
301 }
302 // wtf?
303 empty($lineItem) ? NULL : $this->_lineItems[] = $lineItem;
304 }
305
306 $this->assign('lineItem', empty($lineItem) ? FALSE : [$lineItem]);
307
308 // Set title
309 if ($this->_mode && $this->_id) {
310 $this->_payNow = TRUE;
311 $this->assign('payNow', $this->_payNow);
312 CRM_Utils_System::setTitle(ts('Pay with Credit Card'));
313 }
314 elseif ($this->_mode) {
315 $this->setPageTitle($this->_ppID ? ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
316 }
317 else {
318 $this->setPageTitle($this->_ppID ? ts('Pledge Payment') : ts('Contribution'));
319 }
320 }
321
322 /**
323 * Set default values.
324 *
325 * @return array
326 */
327 public function setDefaultValues() {
328 $defaults = $this->_values;
329
330 // Set defaults for pledge payment.
331 if ($this->_ppID) {
332 $defaults['total_amount'] = CRM_Utils_Array::value('scheduled_amount', $this->_pledgeValues['pledgePayment']);
333 $defaults['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $this->_pledgeValues);
334 $defaults['currency'] = CRM_Utils_Array::value('currency', $this->_pledgeValues);
335 $defaults['option_type'] = 1;
336 }
337
338 if ($this->_action & CRM_Core_Action::DELETE) {
339 return $defaults;
340 }
341
342 $defaults['frequency_interval'] = 1;
343 $defaults['frequency_unit'] = 'month';
344
345 // Set soft credit defaults.
346 CRM_Contribute_Form_SoftCredit::setDefaultValues($defaults, $this);
347
348 if ($this->_mode) {
349 // @todo - remove this function as the parent does it too.
350 $config = CRM_Core_Config::singleton();
351 // Set default country from config if no country set.
352 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
353 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
354 }
355
356 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
357 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
358 }
359
360 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
361 $defaults = array_merge($defaults, $billingDefaults);
362 }
363
364 if ($this->_id) {
365 $this->_contactID = $defaults['contact_id'];
366 }
367
368 // Set $newCredit variable in template to control whether link to credit card mode is included.
369 $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
370
371 // Fix the display of the monetary value, CRM-4038.
372 if (isset($defaults['total_amount'])) {
373 $total_value = $defaults['total_amount'];
374 $defaults['total_amount'] = CRM_Utils_Money::format($total_value, NULL, '%a');
375 if (!empty($defaults['tax_amount'])) {
376 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
377 if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
378 $defaults['total_amount'] = CRM_Utils_Money::format($total_value - $defaults['tax_amount'], NULL, '%a');
379 }
380 }
381 }
382
383 $amountFields = ['non_deductible_amount', 'fee_amount'];
384 foreach ($amountFields as $amt) {
385 if (isset($defaults[$amt])) {
386 $defaults[$amt] = CRM_Utils_Money::format($defaults[$amt], NULL, '%a');
387 }
388 }
389
390 if ($this->_contributionType) {
391 $defaults['financial_type_id'] = $this->_contributionType;
392 }
393
394 if (empty($defaults['payment_instrument_id'])) {
395 $defaults['payment_instrument_id'] = $this->getDefaultPaymentInstrumentId();
396 }
397
398 if (!empty($defaults['is_test'])) {
399 $this->assign('is_test', TRUE);
400 }
401
402 $this->assign('showOption', TRUE);
403 // For Premium section.
404 if ($this->_premiumID) {
405 $this->assign('showOption', FALSE);
406 $options = isset($this->_options[$this->_productDAO->product_id]) ? $this->_options[$this->_productDAO->product_id] : "";
407 if (!$options) {
408 $this->assign('showOption', TRUE);
409 }
410 $options_key = CRM_Utils_Array::key($this->_productDAO->product_option, $options);
411 if ($options_key) {
412 $defaults['product_name'] = [$this->_productDAO->product_id, trim($options_key)];
413 }
414 else {
415 $defaults['product_name'] = [$this->_productDAO->product_id];
416 }
417 if ($this->_productDAO->fulfilled_date) {
418 $defaults['fulfilled_date'] = $this->_productDAO->fulfilled_date;
419 }
420 }
421
422 if (isset($this->userEmail)) {
423 $this->assign('email', $this->userEmail);
424 }
425
426 if (!empty($defaults['is_pay_later'])) {
427 $this->assign('is_pay_later', TRUE);
428 }
429 $this->assign('contribution_status_id', CRM_Utils_Array::value('contribution_status_id', $defaults));
430 if (!empty($defaults['contribution_status_id']) && in_array(
431 CRM_Contribute_PseudoConstant::contributionStatus($defaults['contribution_status_id'], 'name'),
432 // Historically not 'Cancelled' hence not using CRM_Contribute_BAO_Contribution::isContributionStatusNegative.
433 ['Refunded', 'Chargeback']
434 )) {
435 $defaults['refund_trxn_id'] = CRM_Core_BAO_FinancialTrxn::getRefundTransactionTrxnID($this->_id);
436 }
437 else {
438 $defaults['refund_trxn_id'] = isset($defaults['trxn_id']) ? $defaults['trxn_id'] : NULL;
439 }
440
441 if (!$this->_id && empty($defaults['receive_date'])) {
442 $defaults['receive_date'] = date('Y-m-d H:i:s');
443 }
444
445 $currency = CRM_Utils_Array::value('currency', $defaults);
446 $this->assign('currency', $currency);
447 // Hack to get currency info to the js layer. CRM-11440.
448 CRM_Utils_Money::format(1);
449 $this->assign('currencySymbol', CRM_Utils_Array::value($currency, CRM_Utils_Money::$_currencySymbols));
450 $this->assign('totalAmount', CRM_Utils_Array::value('total_amount', $defaults));
451
452 // Inherit campaign from pledge.
453 if ($this->_ppID && !empty($this->_pledgeValues['campaign_id'])) {
454 $defaults['campaign_id'] = $this->_pledgeValues['campaign_id'];
455 }
456
457 $this->_defaults = $defaults;
458 return $defaults;
459 }
460
461 /**
462 * Build the form object.
463 */
464 public function buildQuickForm() {
465 if ($this->_action & CRM_Core_Action::DELETE) {
466 $this->addButtons([
467 [
468 'type' => 'next',
469 'name' => ts('Delete'),
470 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
471 'isDefault' => TRUE,
472 ],
473 [
474 'type' => 'cancel',
475 'name' => ts('Cancel'),
476 ],
477 ]);
478 return;
479 }
480
481 // FIXME: This probably needs to be done in preprocess
482 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
483 && $this->_action & CRM_Core_Action::UPDATE
484 && CRM_Utils_Array::value('financial_type_id', $this->_values)
485 ) {
486 $financialTypeID = CRM_Contribute_PseudoConstant::financialType($this->_values['financial_type_id']);
487 CRM_Financial_BAO_FinancialType::checkPermissionedLineItems($this->_id, 'edit');
488 if (!CRM_Core_Permission::check('edit contributions of type ' . $financialTypeID)) {
489 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
490 }
491 }
492 $allPanes = [];
493
494 //tax rate from financialType
495 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
496 $this->assign('currencies', json_encode(CRM_Core_OptionGroup::values('currencies_enabled')));
497
498 // build price set form.
499 $buildPriceSet = FALSE;
500 $invoicing = CRM_Invoicing_Utils::isInvoicingEnabled();
501 $this->assign('invoicing', $invoicing);
502
503 $buildRecurBlock = FALSE;
504
505 // display tax amount on edit contribution page
506 if ($invoicing && $this->_action & CRM_Core_Action::UPDATE && isset($this->_values['tax_amount'])) {
507 $this->assign('totalTaxAmount', $this->_values['tax_amount']);
508 }
509
510 if (empty($this->_lineItems) &&
511 ($this->_priceSetId || !empty($_POST['price_set_id']))
512 ) {
513 $buildPriceSet = TRUE;
514 $getOnlyPriceSetElements = TRUE;
515 if (!$this->_priceSetId) {
516 $this->_priceSetId = $_POST['price_set_id'];
517 $getOnlyPriceSetElements = FALSE;
518 }
519
520 $this->set('priceSetId', $this->_priceSetId);
521 CRM_Price_BAO_PriceSet::buildPriceSet($this);
522
523 // get only price set form elements.
524 if ($getOnlyPriceSetElements) {
525 return;
526 }
527 }
528 // use to build form during form rule.
529 $this->assign('buildPriceSet', $buildPriceSet);
530
531 $defaults = $this->_values;
532 $additionalDetailFields = [
533 'note',
534 'thankyou_date',
535 'invoice_id',
536 'non_deductible_amount',
537 'fee_amount',
538 ];
539 foreach ($additionalDetailFields as $key) {
540 if (!empty($defaults[$key])) {
541 $defaults['hidden_AdditionalDetail'] = 1;
542 break;
543 }
544 }
545
546 if ($this->_productDAO) {
547 if ($this->_productDAO->product_id) {
548 $defaults['hidden_Premium'] = 1;
549 }
550 }
551
552 if ($this->_noteID &&
553 !CRM_Utils_System::isNull($this->_values['note'])
554 ) {
555 $defaults['hidden_AdditionalDetail'] = 1;
556 }
557
558 $paneNames = [];
559 if (empty($this->_payNow)) {
560 $paneNames[ts('Additional Details')] = 'AdditionalDetail';
561 }
562
563 //Add Premium pane only if Premium is exists.
564 $dao = new CRM_Contribute_DAO_Product();
565 $dao->is_active = 1;
566
567 if ($dao->find(TRUE) && empty($this->_payNow)) {
568 $paneNames[ts('Premium Information')] = 'Premium';
569 }
570
571 $this->payment_instrument_id = CRM_Utils_Array::value('payment_instrument_id', $defaults, $this->getDefaultPaymentInstrumentId());
572 if (CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE, $this->payment_instrument_id) == TRUE) {
573 if (!empty($this->_recurPaymentProcessors)) {
574 $buildRecurBlock = TRUE;
575 if ($this->_ppID) {
576 // ppID denotes a pledge payment.
577 foreach ($this->_paymentProcessors as $processor) {
578 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
579 $buildRecurBlock = TRUE;
580 break;
581 }
582 $buildRecurBlock = FALSE;
583 }
584 }
585 if ($buildRecurBlock) {
586 CRM_Contribute_Form_Contribution_Main::buildRecur($this);
587 $this->setDefaults(['is_recur' => 0]);
588 $this->assign('buildRecurBlock', TRUE);
589 }
590 }
591 }
592 $this->addPaymentProcessorSelect(FALSE, $buildRecurBlock);
593
594 foreach ($paneNames as $name => $type) {
595 $allPanes[$name] = $this->generatePane($type, $defaults);
596 }
597
598 $qfKey = $this->controller->_key;
599 $this->assign('qfKey', $qfKey);
600 $this->assign('allPanes', $allPanes);
601
602 $this->addFormRule(['CRM_Contribute_Form_Contribution', 'formRule'], $this);
603
604 if ($this->_formType) {
605 $this->assign('formType', $this->_formType);
606 return;
607 }
608
609 $this->applyFilter('__ALL__', 'trim');
610
611 //need to assign custom data type and subtype to the template
612 $this->assign('customDataType', 'Contribution');
613 $this->assign('customDataSubType', $this->_contributionType);
614 $this->assign('entityID', $this->_id);
615
616 if ($this->_context == 'standalone') {
617 $this->addEntityRef('contact_id', ts('Contact'), [
618 'create' => TRUE,
619 'api' => ['extra' => ['email']],
620 ], TRUE);
621 }
622
623 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
624
625 // Check permissions for financial type first
626 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action);
627 if (empty($financialTypes)) {
628 CRM_Core_Error::statusBounce(ts('You do not have all the permissions needed for this page.'));
629 }
630 $financialType = $this->add('select', 'financial_type_id',
631 ts('Financial Type'),
632 ['' => ts('- select -')] + $financialTypes,
633 TRUE,
634 ['onChange' => "CRM.buildCustomData( 'Contribution', this.value );"]
635 );
636
637 $paymentInstrument = FALSE;
638 if (!$this->_mode) {
639 // payment_instrument isn't required in edit and will not be present when payment block is enabled.
640 $required = $this->_id ? FALSE : TRUE;
641 $checkPaymentID = array_search('Check', CRM_Contribute_PseudoConstant::paymentInstrument('name'));
642 $paymentInstrument = $this->add('select', 'payment_instrument_id',
643 ts('Payment Method'),
644 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
645 $required, ['onChange' => "return showHideByValue('payment_instrument_id','{$checkPaymentID}','checkNumber','table-row','select',false);"]
646 );
647 }
648
649 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), ['class' => 'twelve'] + $attributes['trxn_id']);
650
651 //add receipt for offline contribution
652 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
653
654 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
655
656 $component = 'contribution';
657 $componentDetails = [];
658 if ($this->_id) {
659 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
660 if (CRM_Utils_Array::value('membership', $componentDetails)) {
661 $component = 'membership';
662 }
663 elseif (CRM_Utils_Array::value('participant', $componentDetails)) {
664 $component = 'participant';
665 }
666 }
667 if ($this->_ppID) {
668 $component = 'pledge';
669 }
670 $status = CRM_Contribute_BAO_Contribution_Utils::getContributionStatuses($component, $this->_id);
671
672 // define the status IDs that show the cancellation info, see CRM-17589
673 $cancelInfo_show_ids = [];
674 foreach (array_keys($status) as $status_id) {
675 if (CRM_Contribute_BAO_Contribution::isContributionStatusNegative($status_id)) {
676 $cancelInfo_show_ids[] = "'$status_id'";
677 }
678 }
679 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
680
681 $statusElement = $this->add('select', 'contribution_status_id',
682 ts('Contribution Status'),
683 $status,
684 FALSE
685 );
686
687 $currencyFreeze = FALSE;
688 if (!empty($this->_payNow) && ($this->_action & CRM_Core_Action::UPDATE)) {
689 $statusElement->freeze();
690 $currencyFreeze = TRUE;
691 $attributes['total_amount']['readonly'] = TRUE;
692 }
693
694 // CRM-16189, add Revenue Recognition Date
695 if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
696 $revenueDate = $this->add('date', 'revenue_recognition_date', ts('Revenue Recognition Date'), CRM_Core_SelectValues::date(NULL, 'M Y', NULL, 5));
697 if ($this->_id && !CRM_Contribute_BAO_Contribution::allowUpdateRevenueRecognitionDate($this->_id)) {
698 $revenueDate->freeze();
699 }
700 }
701
702 // add various dates
703 $this->addField('receive_date', ['entity' => 'contribution'], !$this->_mode, FALSE);
704 $this->addField('receipt_date', ['entity' => 'contribution'], FALSE, FALSE);
705 $this->addField('cancel_date', ['entity' => 'contribution', 'label' => ts('Cancelled / Refunded Date')], FALSE, FALSE);
706
707 if ($this->_online) {
708 $this->assign('hideCalender', TRUE);
709 }
710
711 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
712
713 $totalAmount = NULL;
714 if (empty($this->_lineItems)) {
715 $buildPriceSet = FALSE;
716 $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute');
717 if (!empty($priceSets) && !$this->_ppID) {
718 $buildPriceSet = TRUE;
719 }
720
721 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
722 // and if we already have line items for that participant. CRM-5095
723 if ($buildPriceSet && $this->_id) {
724 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
725 $this->_id,
726 'id',
727 'contribution_id'
728 );
729 if ($pledgePaymentId) {
730 $buildPriceSet = FALSE;
731 }
732 if ($participantID = CRM_Utils_Array::value('participant', $componentDetails)) {
733 $participantLI = CRM_Price_BAO_LineItem::getLineItems($participantID);
734 if (!CRM_Utils_System::isNull($participantLI)) {
735 $buildPriceSet = FALSE;
736 }
737 }
738 }
739
740 $hasPriceSets = FALSE;
741 if ($buildPriceSet) {
742 $hasPriceSets = TRUE;
743 // CRM-16451: set financial type of 'Price Set' in back office contribution
744 // instead of selecting manually
745 $financialTypeIds = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
746 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
747 [
748 '' => ts('Choose price set'),
749 ] + $priceSets,
750 NULL, ['onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");"]
751 );
752 if ($this->_online && !($this->_action & CRM_Core_Action::UPDATE)) {
753 $element->freeze();
754 }
755 }
756 $this->assign('hasPriceSets', $hasPriceSets);
757 if (!($this->_action & CRM_Core_Action::UPDATE)) {
758 if ($this->_online || $this->_ppID) {
759 $attributes['total_amount'] = array_merge($attributes['total_amount'], [
760 'READONLY' => TRUE,
761 'style' => "background-color:#EBECE4",
762 ]);
763 $optionTypes = [
764 '1' => ts('Adjust Pledge Payment Schedule?'),
765 '2' => ts('Adjust Total Pledge Amount?'),
766 ];
767 $this->addRadio('option_type',
768 NULL,
769 $optionTypes,
770 [], '<br/>'
771 );
772
773 $currencyFreeze = TRUE;
774 }
775 }
776
777 $totalAmount = $this->addMoney('total_amount',
778 ts('Total Amount'),
779 ($hasPriceSets) ? FALSE : TRUE,
780 $attributes['total_amount'],
781 TRUE, 'currency', NULL, $currencyFreeze
782 );
783 }
784
785 $this->add('text', 'source', ts('Source'), CRM_Utils_Array::value('source', $attributes));
786
787 // CRM-7362 --add campaigns.
788 CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
789
790 if (empty($this->_payNow)) {
791 CRM_Contribute_Form_SoftCredit::buildQuickForm($this);
792 }
793
794 $js = NULL;
795 if (!$this->_mode) {
796 $js = ['onclick' => "return verify( );"];
797 }
798
799 $mailingInfo = Civi::settings()->get('mailing_backend');
800 $this->assign('outBound_option', $mailingInfo['outBound_option']);
801
802 $this->addButtons([
803 [
804 'type' => 'upload',
805 'name' => ts('Save'),
806 'js' => $js,
807 'isDefault' => TRUE,
808 ],
809 [
810 'type' => 'upload',
811 'name' => ts('Save and New'),
812 'js' => $js,
813 'subName' => 'new',
814 ],
815 [
816 'type' => 'cancel',
817 'name' => ts('Cancel'),
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 = [];
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 = [1 => [$fields['trxn_id'], 'String']];
909 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
910 if ($self->_id) {
911 $queryParams[2] = [(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.', [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', ['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', ['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', [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 = [
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', [
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 = [
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 = [
1286 'soft_credit_contact_id' => [],
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', [
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', [
1301 'id' => $params['id'],
1302 'return' => 'tax_amount',
1303 ]);
1304 }
1305 }
1306 else {
1307 $existingContribution = [];
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 = [];
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 = [];
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 = [
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', ['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 = [
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 = [
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 = [];
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 }