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