Merge pull request #16334 from eileenmcnaughton/ev_tpl
[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 * @throws \CRM_Core_Exception
216 * @throws \CiviCRM_API3_Exception
217 */
218 public function preProcess() {
219 // Check permission for action.
220 if (!CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
221 CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
222 }
223
224 parent::preProcess();
225
226 $this->_formType = CRM_Utils_Array::value('formType', $_GET);
227
228 // Get price set id.
229 $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
230 $this->set('priceSetId', $this->_priceSetId);
231 $this->assign('priceSetId', $this->_priceSetId);
232
233 // Get the pledge payment id
234 $this->_ppID = CRM_Utils_Request::retrieve('ppid', 'Positive', $this);
235
236 $this->assign('action', $this->_action);
237
238 // Get the contribution id if update
239 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive');
240 if (!empty($this->_id)) {
241 $this->assignPaymentInfoBlock();
242 $this->assign('contribID', $this->_id);
243 $this->assign('isUsePaymentBlock', TRUE);
244 }
245
246 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
247 $this->assign('context', $this->_context);
248
249 $this->_compId = CRM_Utils_Request::retrieve('compId', 'Positive', $this);
250
251 $this->_compContext = CRM_Utils_Request::retrieve('compContext', 'String', $this);
252
253 //set the contribution mode.
254 $this->_mode = CRM_Utils_Request::retrieve('mode', 'Alphanumeric', $this);
255
256 $this->assign('contributionMode', $this->_mode);
257 if ($this->_action & CRM_Core_Action::DELETE) {
258 return;
259 }
260
261 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
262
263 if (in_array('CiviPledge', CRM_Core_Config::singleton()->enableComponents) && !$this->_formType) {
264 $this->preProcessPledge();
265 }
266
267 if ($this->_id) {
268 $this->showRecordLinkMesssage($this->_id);
269 }
270 $this->_values = [];
271
272 // Current contribution id.
273 if ($this->_id) {
274 $this->assignPremiumProduct($this->_id);
275 $this->buildValuesAndAssignOnline_Note_Type($this->_id, $this->_values);
276 }
277
278 // when custom data is included in this page
279 if (!empty($_POST['hidden_custom'])) {
280 $this->applyCustomData('Contribution', CRM_Utils_Array::value('financial_type_id', $_POST), $this->_id);
281 }
282
283 $this->_lineItems = [];
284 if ($this->_id) {
285 if (!empty($this->_compId) && $this->_compContext === 'participant') {
286 $this->assign('compId', $this->_compId);
287 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_compId);
288 }
289 else {
290 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution', 1, TRUE, TRUE);
291 }
292 // wtf?
293 empty($lineItem) ? NULL : $this->_lineItems[] = $lineItem;
294 }
295
296 $this->assign('lineItem', empty($lineItem) ? FALSE : [$lineItem]);
297
298 // Set title
299 if ($this->_mode && $this->_id) {
300 $this->_payNow = TRUE;
301 $this->assign('payNow', $this->_payNow);
302 CRM_Utils_System::setTitle(ts('Pay with Credit Card'));
303 }
304 elseif ($this->_mode) {
305 $this->setPageTitle($this->_ppID ? ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
306 }
307 else {
308 $this->setPageTitle($this->_ppID ? ts('Pledge Payment') : ts('Contribution'));
309 }
310 }
311
312 /**
313 * Set default values.
314 *
315 * @return array
316 *
317 * @throws \CRM_Core_Exception
318 */
319 public function setDefaultValues() {
320 $defaults = $this->_values;
321
322 // Set defaults for pledge payment.
323 if ($this->_ppID) {
324 $defaults['total_amount'] = CRM_Utils_Array::value('scheduled_amount', $this->_pledgeValues['pledgePayment']);
325 $defaults['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $this->_pledgeValues);
326 $defaults['currency'] = CRM_Utils_Array::value('currency', $this->_pledgeValues);
327 $defaults['option_type'] = 1;
328 }
329
330 if ($this->_action & CRM_Core_Action::DELETE) {
331 return $defaults;
332 }
333
334 $defaults['frequency_interval'] = 1;
335 $defaults['frequency_unit'] = 'month';
336
337 // Set soft credit defaults.
338 CRM_Contribute_Form_SoftCredit::setDefaultValues($defaults, $this);
339
340 if ($this->_mode) {
341 // @todo - remove this function as the parent does it too.
342 $config = CRM_Core_Config::singleton();
343 // Set default country from config if no country set.
344 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
345 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
346 }
347
348 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
349 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
350 }
351
352 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
353 $defaults = array_merge($defaults, $billingDefaults);
354 }
355
356 if ($this->_id) {
357 $this->_contactID = $defaults['contact_id'];
358 }
359 elseif ($this->_contactID) {
360 $defaults['contact_id'] = $this->_contactID;
361 }
362
363 // Set $newCredit variable in template to control whether link to credit card mode is included.
364 $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
365
366 // Fix the display of the monetary value, CRM-4038.
367 if (isset($defaults['total_amount'])) {
368 $total_value = $defaults['total_amount'];
369 $defaults['total_amount'] = CRM_Utils_Money::format($total_value, NULL, '%a');
370 if (!empty($defaults['tax_amount'])) {
371 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
372 if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
373 $defaults['total_amount'] = CRM_Utils_Money::format($total_value - $defaults['tax_amount'], NULL, '%a');
374 }
375 }
376 }
377
378 $amountFields = ['non_deductible_amount', 'fee_amount'];
379 foreach ($amountFields as $amt) {
380 if (isset($defaults[$amt])) {
381 $defaults[$amt] = CRM_Utils_Money::format($defaults[$amt], NULL, '%a');
382 }
383 }
384
385 if ($this->_contributionType) {
386 $defaults['financial_type_id'] = $this->_contributionType;
387 }
388
389 if (empty($defaults['payment_instrument_id'])) {
390 $defaults['payment_instrument_id'] = $this->getDefaultPaymentInstrumentId();
391 }
392
393 if (!empty($defaults['is_test'])) {
394 $this->assign('is_test', TRUE);
395 }
396
397 $this->assign('showOption', TRUE);
398 // For Premium section.
399 if ($this->_premiumID) {
400 $this->assign('showOption', FALSE);
401 $options = isset($this->_options[$this->_productDAO->product_id]) ? $this->_options[$this->_productDAO->product_id] : "";
402 if (!$options) {
403 $this->assign('showOption', TRUE);
404 }
405 $options_key = CRM_Utils_Array::key($this->_productDAO->product_option, $options);
406 if ($options_key) {
407 $defaults['product_name'] = [$this->_productDAO->product_id, trim($options_key)];
408 }
409 else {
410 $defaults['product_name'] = [$this->_productDAO->product_id];
411 }
412 if ($this->_productDAO->fulfilled_date) {
413 $defaults['fulfilled_date'] = $this->_productDAO->fulfilled_date;
414 }
415 }
416
417 if (isset($this->userEmail)) {
418 $this->assign('email', $this->userEmail);
419 }
420
421 if (!empty($defaults['is_pay_later'])) {
422 $this->assign('is_pay_later', TRUE);
423 }
424 $this->assign('contribution_status_id', CRM_Utils_Array::value('contribution_status_id', $defaults));
425 if (!empty($defaults['contribution_status_id']) && in_array(
426 CRM_Contribute_PseudoConstant::contributionStatus($defaults['contribution_status_id'], 'name'),
427 // Historically not 'Cancelled' hence not using CRM_Contribute_BAO_Contribution::isContributionStatusNegative.
428 ['Refunded', 'Chargeback']
429 )) {
430 $defaults['refund_trxn_id'] = CRM_Core_BAO_FinancialTrxn::getRefundTransactionTrxnID($this->_id);
431 }
432 else {
433 $defaults['refund_trxn_id'] = isset($defaults['trxn_id']) ? $defaults['trxn_id'] : NULL;
434 }
435
436 if (!$this->_id && empty($defaults['receive_date'])) {
437 $defaults['receive_date'] = date('Y-m-d H:i:s');
438 }
439
440 $currency = CRM_Utils_Array::value('currency', $defaults);
441 $this->assign('currency', $currency);
442 // Hack to get currency info to the js layer. CRM-11440.
443 CRM_Utils_Money::format(1);
444 $this->assign('currencySymbol', CRM_Utils_Array::value($currency, CRM_Utils_Money::$_currencySymbols));
445 $this->assign('totalAmount', CRM_Utils_Array::value('total_amount', $defaults));
446
447 // Inherit campaign from pledge.
448 if ($this->_ppID && !empty($this->_pledgeValues['campaign_id'])) {
449 $defaults['campaign_id'] = $this->_pledgeValues['campaign_id'];
450 }
451
452 $this->_defaults = $defaults;
453 return $defaults;
454 }
455
456 /**
457 * Build the form object.
458 *
459 * @throws \CiviCRM_API3_Exception
460 * @throws \CRM_Core_Exception
461 */
462 public function buildQuickForm() {
463 if ($this->_id) {
464 $this->add('hidden', 'id', $this->_id);
465 }
466
467 if ($this->_action & CRM_Core_Action::DELETE) {
468 $this->addButtons([
469 [
470 'type' => 'next',
471 'name' => ts('Delete'),
472 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
473 'isDefault' => TRUE,
474 ],
475 [
476 'type' => 'cancel',
477 'name' => ts('Cancel'),
478 ],
479 ]);
480 return;
481 }
482
483 // FIXME: This probably needs to be done in preprocess
484 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
485 && $this->_action & CRM_Core_Action::UPDATE
486 && CRM_Utils_Array::value('financial_type_id', $this->_values)
487 ) {
488 $financialTypeID = CRM_Contribute_PseudoConstant::financialType($this->_values['financial_type_id']);
489 CRM_Financial_BAO_FinancialType::checkPermissionedLineItems($this->_id, 'edit');
490 if (!CRM_Core_Permission::check('edit contributions of type ' . $financialTypeID)) {
491 CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
492 }
493 }
494 $allPanes = [];
495
496 //tax rate from financialType
497 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
498 $this->assign('currencies', json_encode(CRM_Core_OptionGroup::values('currencies_enabled')));
499
500 // build price set form.
501 $buildPriceSet = FALSE;
502 $invoicing = CRM_Invoicing_Utils::isInvoicingEnabled();
503 $this->assign('invoicing', $invoicing);
504
505 $buildRecurBlock = FALSE;
506
507 // display tax amount on edit contribution page
508 if ($invoicing && $this->_action & CRM_Core_Action::UPDATE && isset($this->_values['tax_amount'])) {
509 $this->assign('totalTaxAmount', $this->_values['tax_amount']);
510 }
511
512 if (empty($this->_lineItems) &&
513 ($this->_priceSetId || !empty($_POST['price_set_id']))
514 ) {
515 $buildPriceSet = TRUE;
516 $getOnlyPriceSetElements = TRUE;
517 if (!$this->_priceSetId) {
518 $this->_priceSetId = $_POST['price_set_id'];
519 $getOnlyPriceSetElements = FALSE;
520 }
521
522 $this->set('priceSetId', $this->_priceSetId);
523 CRM_Price_BAO_PriceSet::buildPriceSet($this);
524
525 // get only price set form elements.
526 if ($getOnlyPriceSetElements) {
527 return;
528 }
529 }
530 // use to build form during form rule.
531 $this->assign('buildPriceSet', $buildPriceSet);
532
533 $defaults = $this->_values;
534 $additionalDetailFields = [
535 'note',
536 'thankyou_date',
537 'invoice_id',
538 'non_deductible_amount',
539 'fee_amount',
540 ];
541 foreach ($additionalDetailFields as $key) {
542 if (!empty($defaults[$key])) {
543 $defaults['hidden_AdditionalDetail'] = 1;
544 break;
545 }
546 }
547
548 if ($this->_productDAO) {
549 if ($this->_productDAO->product_id) {
550 $defaults['hidden_Premium'] = 1;
551 }
552 }
553
554 if ($this->_noteID &&
555 !CRM_Utils_System::isNull($this->_values['note'])
556 ) {
557 $defaults['hidden_AdditionalDetail'] = 1;
558 }
559
560 $paneNames = [];
561 if (empty($this->_payNow)) {
562 $paneNames[ts('Additional Details')] = 'AdditionalDetail';
563 }
564
565 //Add Premium pane only if Premium is exists.
566 $dao = new CRM_Contribute_DAO_Product();
567 $dao->is_active = 1;
568
569 if ($dao->find(TRUE) && empty($this->_payNow)) {
570 $paneNames[ts('Premium Information')] = 'Premium';
571 }
572
573 $this->payment_instrument_id = CRM_Utils_Array::value('payment_instrument_id', $defaults, $this->getDefaultPaymentInstrumentId());
574 if (CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE, $this->payment_instrument_id) == TRUE) {
575 if (!empty($this->_recurPaymentProcessors)) {
576 $buildRecurBlock = TRUE;
577 if ($this->_ppID) {
578 // ppID denotes a pledge payment.
579 foreach ($this->_paymentProcessors as $processor) {
580 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
581 $buildRecurBlock = TRUE;
582 break;
583 }
584 $buildRecurBlock = FALSE;
585 }
586 }
587 if ($buildRecurBlock) {
588 CRM_Contribute_Form_Contribution_Main::buildRecur($this);
589 $this->setDefaults(['is_recur' => 0]);
590 $this->assign('buildRecurBlock', TRUE);
591 }
592 }
593 }
594 $this->addPaymentProcessorSelect(FALSE, $buildRecurBlock);
595
596 foreach ($paneNames as $name => $type) {
597 $allPanes[$name] = $this->generatePane($type, $defaults);
598 }
599
600 $qfKey = $this->controller->_key;
601 $this->assign('qfKey', $qfKey);
602 $this->assign('allPanes', $allPanes);
603
604 $this->addFormRule(['CRM_Contribute_Form_Contribution', 'formRule'], $this);
605
606 if ($this->_formType) {
607 $this->assign('formType', $this->_formType);
608 return;
609 }
610
611 $this->applyFilter('__ALL__', 'trim');
612
613 //need to assign custom data type and subtype to the template
614 $this->assign('customDataType', 'Contribution');
615 $this->assign('customDataSubType', $this->_contributionType);
616 $this->assign('entityID', $this->_id);
617
618 $contactField = $this->addEntityRef('contact_id', ts('Contributor'), ['create' => TRUE, 'api' => ['extra' => ['email']]], TRUE);
619 if ($this->_context !== 'standalone') {
620 $contactField->freeze();
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 (!empty($componentDetails['membership'])) {
661 $component = 'membership';
662 }
663 elseif (!empty($componentDetails['participant'])) {
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 (Civi::settings()->get('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 (!empty($componentDetails['membership']) ||
827 !empty($componentDetails['participant']) ||
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 *
1019 * @throws \CRM_Core_Exception
1020 * @throws \Civi\Payment\Exception\PaymentProcessorException
1021 * @throws \CiviCRM_API3_Exception
1022 */
1023 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1024 $isTest = ($this->_mode == 'test') ? 1 : 0;
1025 // CRM-12680 set $_lineItem if its not set
1026 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1027 // It would be better to pass line item out to functions than $this->_lineItem as
1028 // we don't know what is being changed where.
1029 if (empty($this->_lineItem) && !empty($lineItem)) {
1030 $this->_lineItem = $lineItem;
1031 }
1032
1033 $this->_paymentObject = Civi\Payment\System::singleton()->getById($submittedValues['payment_processor_id']);
1034 $this->_paymentProcessor = $this->_paymentObject->getPaymentProcessor();
1035
1036 // Set source if not set
1037 if (empty($submittedValues['source'])) {
1038 $userID = CRM_Core_Session::singleton()->get('userID');
1039 $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1040 'sort_name'
1041 );
1042 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', [1 => $userSortName]);
1043 }
1044
1045 $params = $submittedValues;
1046 $this->_params = array_merge($this->_params, $submittedValues);
1047
1048 // Mapping requiring documentation.
1049 $this->_params['payment_processor'] = $submittedValues['payment_processor_id'];
1050
1051 $now = date('YmdHis');
1052
1053 $this->_contributorEmail = $this->userEmail;
1054 $this->_contributorContactID = $contactID;
1055 $this->processBillingAddress();
1056 if (!empty($params['source'])) {
1057 unset($params['source']);
1058 }
1059
1060 $this->_params['amount'] = $this->_params['total_amount'];
1061 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1062 // function to get correct amount level consistently. Remove setting of the amount level in
1063 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1064 // to cover all variants.
1065 $this->_params['amount_level'] = 0;
1066 $this->_params['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1067 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
1068 $this->_params,
1069 CRM_Core_Config::singleton()->defaultCurrency
1070 );
1071
1072 $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
1073 $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
1074 $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
1075
1076 //Add common data to formatted params
1077 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
1078
1079 if (empty($this->_params['invoice_id'])) {
1080 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1081 }
1082 else {
1083 $this->_params['invoiceID'] = $this->_params['invoice_id'];
1084 }
1085
1086 // At this point we've created a contact and stored its address etc
1087 // all the payment processors expect the name and address to be in the
1088 // so we copy stuff over to first_name etc.
1089 $paymentParams = $this->_params;
1090 $paymentParams['contactID'] = $contactID;
1091 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
1092
1093 $financialType = new CRM_Financial_DAO_FinancialType();
1094 $financialType->id = $params['financial_type_id'];
1095 $financialType->find(TRUE);
1096
1097 // Add some financial type details to the params list
1098 // if folks need to use it.
1099 $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $financialType->name;
1100 $paymentParams['contributionPageID'] = NULL;
1101
1102 if (!empty($this->_params['is_email_receipt'])) {
1103 $paymentParams['email'] = $this->userEmail;
1104 $paymentParams['is_email_receipt'] = 1;
1105 }
1106 else {
1107 $paymentParams['is_email_receipt'] = 0;
1108 $this->_params['is_email_receipt'] = 0;
1109 }
1110 if (!empty($this->_params['receive_date'])) {
1111 $paymentParams['receive_date'] = $this->_params['receive_date'];
1112 }
1113
1114 if (!empty($this->_params['is_email_receipt'])) {
1115 $this->_params['receipt_date'] = $now;
1116 }
1117
1118 $this->set('params', $this->_params);
1119
1120 $this->assign('receive_date', $this->_params['receive_date']);
1121
1122 // Result has all the stuff we need
1123 // lets archive it to a financial transaction
1124 if ($financialType->is_deductible) {
1125 $this->assign('is_deductible', TRUE);
1126 $this->set('is_deductible', TRUE);
1127 }
1128 $contributionParams = [
1129 'id' => CRM_Utils_Array::value('contribution_id', $this->_params),
1130 'contact_id' => $contactID,
1131 'line_item' => $lineItem,
1132 'is_test' => $isTest,
1133 'campaign_id' => CRM_Utils_Array::value('campaign_id', $this->_params),
1134 'contribution_page_id' => CRM_Utils_Array::value('contribution_page_id', $this->_params),
1135 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)),
1136 'thankyou_date' => CRM_Utils_Array::value('thankyou_date', $this->_params),
1137 ];
1138 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor['payment_instrument_id'];
1139
1140 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this,
1141 $this->_params,
1142 NULL,
1143 $contributionParams,
1144 $financialType,
1145 FALSE,
1146 $this->_bltID,
1147 CRM_Utils_Array::value('is_recur', $this->_params)
1148 );
1149
1150 $paymentParams['contributionID'] = $contribution->id;
1151 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
1152 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1153 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
1154
1155 if ($paymentParams['amount'] > 0.0) {
1156 // force a re-get of the payment processor in case the form changed it, CRM-7179
1157 // NOTE - I expect this is obsolete.
1158 $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
1159 try {
1160 $completeStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1161 $result = $payment->doPayment($paymentParams, 'contribute');
1162 $this->assign('trxn_id', $result['trxn_id']);
1163 $contribution->trxn_id = $result['trxn_id'];
1164 /* Our scenarios here are
1165 * 1) the payment failed & an Exception should have been thrown
1166 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1167 * with a delayed start)
1168 * 3) the payment succeeded with an immediate payment.
1169 *
1170 * The doPayment function ensures that payment_status_id is always set
1171 * as historically we have had to guess from the context - ie doDirectPayment
1172 * = error or success, unless it is a recurring contribution in which case it is pending.
1173 */
1174 if ($result['payment_status_id'] == $completeStatusId) {
1175 try {
1176 civicrm_api3('contribution', 'completetransaction', [
1177 'id' => $contribution->id,
1178 'trxn_id' => $result['trxn_id'],
1179 'payment_processor_id' => $this->_paymentProcessor['id'],
1180 'is_transactional' => FALSE,
1181 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
1182 'card_type_id' => CRM_Utils_Array::value('card_type_id', $paymentParams),
1183 'pan_truncation' => CRM_Utils_Array::value('pan_truncation', $paymentParams),
1184 'is_email_receipt' => FALSE,
1185 ]);
1186 // This has now been set to 1 in the DB - declare it here also
1187 $contribution->contribution_status_id = 1;
1188 }
1189 catch (CiviCRM_API3_Exception $e) {
1190 if ($e->getErrorCode() != 'contribution_completed') {
1191 throw new CRM_Core_Exception('Failed to update contribution in database');
1192 }
1193 }
1194 }
1195 else {
1196 // Save the trxn_id.
1197 $contribution->save();
1198 }
1199 }
1200 catch (PaymentProcessorException $e) {
1201 CRM_Contribute_BAO_Contribution::failPayment($contribution->id, $paymentParams['contactID'], $e->getMessage());
1202 throw new PaymentProcessorException($e->getMessage());
1203 }
1204 }
1205 // Send receipt mail.
1206 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
1207 if ($contribution->id && !empty($this->_params['is_email_receipt'])) {
1208 $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
1209 $this->_params['contact_id'] = $contactID;
1210 $this->_params['contribution_id'] = $contribution->id;
1211 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE)) {
1212 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
1213 }
1214 }
1215
1216 return $contribution;
1217 }
1218
1219 /**
1220 * Generate the data to construct a snippet based pane.
1221 *
1222 * This form also assigns the showAdditionalInfo var based on historical code.
1223 * This appears to mean 'there is a pane to show'.
1224 *
1225 * @param string $type
1226 * Type of Pane - this is generally used to determine the function name used to build it
1227 * - e.g CreditCard, AdditionalDetail
1228 * @param array $defaults
1229 *
1230 * @return array
1231 * We aim to further refactor & simplify this but currently
1232 * - the panes array
1233 * - should additional info be shown?
1234 */
1235 protected function generatePane($type, $defaults) {
1236 $urlParams = "snippet=4&formType={$type}";
1237 if ($this->_mode) {
1238 $urlParams .= "&mode={$this->_mode}";
1239 }
1240
1241 $open = 'false';
1242 if ($type == 'CreditCard' ||
1243 $type == 'DirectDebit'
1244 ) {
1245 $open = 'true';
1246 }
1247
1248 $pane = [
1249 'url' => CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams),
1250 'open' => $open,
1251 'id' => $type,
1252 ];
1253
1254 // See if we need to include this paneName in the current form.
1255 if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) ||
1256 CRM_Utils_Array::value("hidden_{$type}", $defaults)
1257 ) {
1258 $this->assign('showAdditionalInfo', TRUE);
1259 $pane['open'] = 'true';
1260 }
1261
1262 if ($type == 'CreditCard' || $type == 'DirectDebit') {
1263 // @todo would be good to align tpl name with form name...
1264 // @todo document why this hidden variable is required.
1265 $this->add('hidden', 'hidden_' . $type, 1);
1266 return $pane;
1267 }
1268 else {
1269 $additionalInfoFormFunction = 'build' . $type;
1270 CRM_Contribute_Form_AdditionalInfo::$additionalInfoFormFunction($this);
1271 return $pane;
1272 }
1273 }
1274
1275 /**
1276 * Wrapper for unit testing the post process submit function.
1277 *
1278 * (If we expose through api we can get default additions 'for free').
1279 *
1280 * @param array $params
1281 * @param int $action
1282 * @param string|null $creditCardMode
1283 *
1284 * @return CRM_Contribute_BAO_Contribution
1285 *
1286 * @throws \CRM_Core_Exception
1287 * @throws \CiviCRM_API3_Exception
1288 * @throws \Civi\Payment\Exception\PaymentProcessorException
1289 */
1290 public function testSubmit($params, $action, $creditCardMode = NULL) {
1291 $defaults = [
1292 'soft_credit_contact_id' => [],
1293 'receive_date' => date('Y-m-d H:i:s'),
1294 'receipt_date' => '',
1295 'cancel_date' => '',
1296 'hidden_Premium' => 1,
1297 ];
1298 $this->_bltID = 5;
1299 if (!empty($params['id'])) {
1300 $existingContribution = civicrm_api3('contribution', 'getsingle', [
1301 'id' => $params['id'],
1302 ]);
1303 $this->_id = $params['id'];
1304 $this->_values = $existingContribution;
1305 if (CRM_Contribute_BAO_Contribution::checkContributeSettings('invoicing')) {
1306 $this->_values['tax_amount'] = civicrm_api3('contribution', 'getvalue', [
1307 'id' => $params['id'],
1308 'return' => 'tax_amount',
1309 ]);
1310 }
1311 }
1312 else {
1313 $existingContribution = [];
1314 }
1315
1316 $this->_defaults['contribution_status_id'] = CRM_Utils_Array::value('contribution_status_id',
1317 $existingContribution
1318 );
1319
1320 $this->_defaults['total_amount'] = CRM_Utils_Array::value('total_amount',
1321 $existingContribution
1322 );
1323
1324 if ($creditCardMode) {
1325 $this->_mode = $creditCardMode;
1326 }
1327
1328 // Required because processCreditCard calls set method on this.
1329 $_SERVER['REQUEST_METHOD'] = 'GET';
1330 $this->controller = new CRM_Core_Controller();
1331
1332 CRM_Contribute_Form_AdditionalInfo::buildPremium($this);
1333
1334 $this->_fields = [];
1335 return $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array::value('pledge_payment_id', $params));
1336
1337 }
1338
1339 /**
1340 * @param array $submittedValues
1341 *
1342 * @param int $action
1343 * Action constant
1344 * - CRM_Core_Action::UPDATE
1345 *
1346 * @param $pledgePaymentID
1347 *
1348 * @return \CRM_Contribute_BAO_Contribution
1349 *
1350 * @throws \CRM_Core_Exception
1351 * @throws \CiviCRM_API3_Exception
1352 * @throws \Civi\Payment\Exception\PaymentProcessorException
1353 */
1354 protected function submit($submittedValues, $action, $pledgePaymentID) {
1355 $pId = $contribution = $isRelatedId = FALSE;
1356 $this->_params = $submittedValues;
1357 $this->beginPostProcess();
1358 // reassign submitted form values if the any information is formatted via beginPostProcess
1359 $submittedValues = $this->_params;
1360
1361 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action::UPDATE) {
1362 $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
1363 $lineID = key($line);
1364 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
1365 $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1366 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1367 // config should be treated the same.
1368 if ($quickConfig) {
1369 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
1370 }
1371 }
1372
1373 // Process price set and get total amount and line items.
1374 $lineItem = [];
1375 $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
1376 if (empty($priceSetId) && !$this->_id) {
1377 $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1378 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
1379 $fieldID = key($this->_priceSet['fields']);
1380 $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
1381 $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1382 $submittedValues['price_' . $fieldID] = 1;
1383 }
1384
1385 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1386 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1387 // as a point of fragility rather than a logical 'if' clause.
1388 if ($priceSetId) {
1389 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
1390 $submittedValues, $lineItem[$priceSetId], $priceSetId);
1391 // Unset tax amount for offline 'is_quick_config' contribution.
1392 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1393 // this is an example of 'other' functionality being hung off it.
1394 if ($this->_priceSet['is_quick_config'] &&
1395 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())
1396 ) {
1397 unset($submittedValues['tax_amount']);
1398 }
1399 $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
1400 }
1401
1402 if ($this->_id) {
1403 if ($this->_compId) {
1404 if ($this->_context == 'participant') {
1405 $pId = $this->_compId;
1406 }
1407 elseif ($this->_context == 'membership') {
1408 $isRelatedId = TRUE;
1409 }
1410 else {
1411 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
1412 }
1413 }
1414 else {
1415 $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1416 if (array_key_exists('membership', $contributionDetails)) {
1417 $isRelatedId = TRUE;
1418 }
1419 elseif (array_key_exists('participant', $contributionDetails)) {
1420 $pId = $contributionDetails['participant'];
1421 }
1422 }
1423 if (!empty($this->_payNow)) {
1424 $this->_params['contribution_id'] = $this->_id;
1425 }
1426 }
1427
1428 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
1429 // CRM-10117 update the line items for participants.
1430 // @todo - if we are completing a contribution then the api call
1431 // civicrm_api3('Contribution', 'completetransaction') should take care of
1432 // all associated updates rather than replicating them on the form layer.
1433 if ($pId) {
1434 $entityTable = 'participant';
1435 $entityID = $pId;
1436 $isRelatedId = FALSE;
1437 $participantParams = [
1438 'fee_amount' => $submittedValues['total_amount'],
1439 'id' => $entityID,
1440 ];
1441 CRM_Event_BAO_Participant::add($participantParams);
1442 if (empty($this->_lineItems)) {
1443 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', TRUE);
1444 }
1445 }
1446 else {
1447 $entityTable = 'contribution';
1448 $entityID = $this->_id;
1449 }
1450
1451 $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
1452 foreach (array_keys($lineItems) as $id) {
1453 $lineItems[$id]['id'] = $id;
1454 }
1455 $itemId = key($lineItems);
1456 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1457 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1458 }
1459
1460 // @todo see above - new functionality has been inappropriately added to the quick config concept
1461 // and new functionality has been added onto the form layer rather than the BAO :-(
1462 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1463 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1464 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1465 if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
1466 if (!($this->_action & CRM_Core_Action::UPDATE && (($this->_defaults['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1467 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
1468 }
1469 }
1470
1471 // Update line total and total amount with tax on edit.
1472 $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
1473 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1474 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1475 }
1476 else {
1477 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1478 $submittedValues['tax_amount'] = 'null';
1479 }
1480 if ($lineItems[$itemId]['tax_rate']) {
1481 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1482 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
1483 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1484 }
1485 }
1486 // CRM-10117 update the line items for participants.
1487 if (!empty($lineItems[$itemId]['price_field_id'])) {
1488 $lineItem[$this->_priceSetId] = $lineItems;
1489 }
1490 }
1491
1492 $isQuickConfig = 0;
1493 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1494 $isQuickConfig = 1;
1495 }
1496 //CRM-11529 for quick config back office transactions
1497 //when financial_type_id is passed in form, update the
1498 //line items with the financial type selected in form
1499 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1500 // we should look at having a price field per contribution type & then there would be little reason
1501 // for the back-office contribution form postProcess to know if it is a quick-config form.
1502 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)
1503 ) {
1504 foreach ($lineItem[$this->_priceSetId] as &$values) {
1505 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1506 }
1507 }
1508
1509 if (!isset($submittedValues['total_amount'])) {
1510 $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
1511 // Avoid tax amount deduction on edit form and keep it original, because this will lead to error described in CRM-20676
1512 if (!$this->_id) {
1513 $submittedValues['total_amount'] -= CRM_Utils_Array::value('tax_amount', $this->_values, 0);
1514 }
1515 }
1516 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1517
1518 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1519 if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
1520 civicrm_api3('ContributionSoft', 'get', ['contribution_id' => $this->_id, 'pcp_id' => NULL, 'api.ContributionSoft.delete' => 1]);
1521 }
1522
1523 // set the contact, when contact is selected
1524 if (!empty($submittedValues['contact_id'])) {
1525 $this->_contactID = $submittedValues['contact_id'];
1526 }
1527
1528 $formValues = $submittedValues;
1529
1530 // Credit Card Contribution.
1531 if ($this->_mode) {
1532 $paramsSetByPaymentProcessingSubsystem = [
1533 'trxn_id',
1534 'payment_instrument_id',
1535 'contribution_status_id',
1536 'cancel_date',
1537 'cancel_reason',
1538 ];
1539 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1540 if (isset($formValues[$key])) {
1541 unset($formValues[$key]);
1542 }
1543 }
1544 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID);
1545 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1546 $formValues[$key] = $contribution->$key;
1547 }
1548 }
1549 else {
1550 // Offline Contribution.
1551 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1552
1553 // get the required field value only.
1554
1555 $params = [
1556 'contact_id' => $this->_contactID,
1557 'currency' => $this->getCurrency($submittedValues),
1558 'skipCleanMoney' => TRUE,
1559 'id' => $this->_id,
1560 ];
1561
1562 //format soft-credit/pcp param first
1563 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($submittedValues, $this);
1564 $params = array_merge($params, $submittedValues);
1565
1566 $fields = [
1567 'financial_type_id',
1568 'contribution_status_id',
1569 'payment_instrument_id',
1570 'cancel_reason',
1571 'source',
1572 'check_number',
1573 'card_type_id',
1574 'pan_truncation',
1575 ];
1576 foreach ($fields as $f) {
1577 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1578 }
1579
1580 $params['revenue_recognition_date'] = NULL;
1581 if (!empty($formValues['revenue_recognition_date'])
1582 && count(array_filter($formValues['revenue_recognition_date'])) == 2
1583 ) {
1584 $params['revenue_recognition_date'] = CRM_Utils_Date::processDate(
1585 '01-' . implode('-', $formValues['revenue_recognition_date'])
1586 );
1587 }
1588
1589 if (!empty($formValues['is_email_receipt'])) {
1590 $params['receipt_date'] = date("Y-m-d");
1591 }
1592
1593 if (CRM_Contribute_BAO_Contribution::isContributionStatusNegative($params['contribution_status_id'])
1594 ) {
1595 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
1596 $params['cancel_date'] = date('YmdHis');
1597 }
1598 }
1599 else {
1600 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1601 }
1602
1603 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1604 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1605 if ($params['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
1606 $params['is_pay_later'] = 1;
1607 }
1608 elseif ($params['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
1609 $params['is_pay_later'] = 0;
1610 }
1611
1612 // Add Additional common information to formatted params.
1613 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
1614 if ($pId) {
1615 $params['contribution_mode'] = 'participant';
1616 $params['participant_id'] = $pId;
1617 $params['skipLineItem'] = 1;
1618 }
1619 elseif ($isRelatedId) {
1620 $params['contribution_mode'] = 'membership';
1621 }
1622 $params['line_item'] = $lineItem;
1623 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
1624 $params['tax_amount'] = CRM_Utils_Array::value('tax_amount', $submittedValues, CRM_Utils_Array::value('tax_amount', $this->_values));
1625 //create contribution.
1626 if ($isQuickConfig) {
1627 $params['is_quick_config'] = 1;
1628 }
1629 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1630
1631 // we are already handling note below, so to avoid duplicate notes against $contribution
1632 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1633 unset($params['note']);
1634 }
1635 $contribution = CRM_Contribute_BAO_Contribution::create($params);
1636
1637 // process associated membership / participant, CRM-4395
1638 if ($contribution->id && $action & CRM_Core_Action::UPDATE) {
1639 $this->statusMessage[] = CRM_Contribute_BAO_Contribution::transitionComponentWithReturnMessage($contribution->id,
1640 $contribution->contribution_status_id,
1641 CRM_Utils_Array::value('contribution_status_id',
1642 $this->_values
1643 ),
1644 $contribution->receive_date
1645 );
1646 }
1647
1648 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
1649
1650 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1651
1652 //send receipt mail.
1653 if ($contribution->id && !empty($formValues['is_email_receipt'])) {
1654 $formValues['contact_id'] = $this->_contactID;
1655 $formValues['contribution_id'] = $contribution->id;
1656
1657 $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
1658
1659 // to get 'from email id' for send receipt
1660 $this->fromEmailId = CRM_Utils_Array::value('from_email_address', $formValues);
1661 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues)) {
1662 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
1663 }
1664 }
1665
1666 $this->statusMessageTitle = ts('Saved');
1667
1668 }
1669
1670 if ($contribution->id && isset($formValues['product_name'][0])) {
1671 CRM_Contribute_Form_AdditionalInfo::processPremium($submittedValues, $contribution->id,
1672 $this->_premiumID, $this->_options
1673 );
1674 }
1675
1676 if ($contribution->id && array_key_exists('note', $submittedValues)) {
1677 CRM_Contribute_Form_AdditionalInfo::processNote($submittedValues, $this->_contactID, $contribution->id, $this->_noteID);
1678 }
1679
1680 CRM_Core_Session::setStatus(implode(' ', $this->statusMessage), $this->statusMessageTitle, 'success');
1681
1682 CRM_Contribute_BAO_Contribution::updateRelatedPledge(
1683 $action,
1684 $pledgePaymentID,
1685 $contribution->id,
1686 (CRM_Utils_Array::value('option_type', $formValues) == 2) ? TRUE : FALSE,
1687 $formValues['total_amount'],
1688 CRM_Utils_Array::value('total_amount', $this->_defaults),
1689 $formValues['contribution_status_id'],
1690 CRM_Utils_Array::value('contribution_status_id', $this->_defaults)
1691 );
1692 return $contribution;
1693 }
1694
1695 /**
1696 * Assign tax calculations to contribution receipts.
1697 *
1698 * @param array $submittedValues
1699 * @param int $action
1700 * @param array $lineItem
1701 */
1702 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1703
1704 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
1705 if (empty($invoiceSettings['invoicing'])) {
1706 return;
1707 }
1708 $taxRate = [];
1709 $getTaxDetails = FALSE;
1710
1711 foreach ($lineItem as $key => $value) {
1712 foreach ($value as $v) {
1713 if (isset($taxRate[(string) CRM_Utils_Array::value('tax_rate', $v)])) {
1714 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array::value('tax_amount', $v);
1715 }
1716 else {
1717 if (isset($v['tax_rate'])) {
1718 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array::value('tax_amount', $v);
1719 $getTaxDetails = TRUE;
1720 }
1721 }
1722 }
1723 }
1724
1725 if ($action & CRM_Core_Action::UPDATE) {
1726 if (isset($submittedValues['tax_amount'])) {
1727 $totalTaxAmount = $submittedValues['tax_amount'];
1728 }
1729 else {
1730 $totalTaxAmount = $this->_values['tax_amount'];
1731 }
1732 $this->assign('totalTaxAmount', $totalTaxAmount);
1733 $this->assign('dataArray', $taxRate);
1734 }
1735 else {
1736 if (!empty($submittedValues['price_set_id'])) {
1737 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1738 $this->assign('getTaxDetails', $getTaxDetails);
1739 $this->assign('dataArray', $taxRate);
1740 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
1741 }
1742 else {
1743 $this->assign('totalTaxAmount', CRM_Utils_Array::value('tax_amount', $submittedValues));
1744 }
1745 }
1746 }
1747
1748 /**
1749 * Calculate non deductible amount.
1750 *
1751 * CRM-11956
1752 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1753 * if non_deductible_amount does NOT exist - then calculate it depending on:
1754 * $financialType->is_deductible and whether there is a product (premium).
1755 *
1756 * @param $params
1757 * @param $formValues
1758 *
1759 * @return array
1760 */
1761 protected function calculateNonDeductibleAmount($params, $formValues) {
1762 if (!empty($params['non_deductible_amount'])) {
1763 return $params['non_deductible_amount'];
1764 }
1765
1766 $priceSetId = CRM_Utils_Array::value('price_set_id', $params);
1767 // return non-deductible amount if it is set at the price field option level
1768 if ($priceSetId && !empty($params['line_item'])) {
1769 $nonDeductibleAmount = CRM_Price_BAO_PriceSet::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1770 if (!empty($nonDeductibleAmount)) {
1771 return $nonDeductibleAmount;
1772 }
1773 }
1774
1775 $financialType = new CRM_Financial_DAO_FinancialType();
1776 $financialType->id = $params['financial_type_id'];
1777 $financialType->find(TRUE);
1778
1779 if ($financialType->is_deductible) {
1780
1781 if (isset($formValues['product_name'][0])) {
1782 $selectProduct = $formValues['product_name'][0];
1783 }
1784 // if there is a product - compare the value to the contribution amount
1785 if (isset($selectProduct)) {
1786 $productDAO = new CRM_Contribute_DAO_Product();
1787 $productDAO->id = $selectProduct;
1788 $productDAO->find(TRUE);
1789 // product value exceeds contribution amount
1790 if ($params['total_amount'] < $productDAO->price) {
1791 return $params['total_amount'];
1792 }
1793 // product value does NOT exceed contribution amount
1794 else {
1795 return $productDAO->price;
1796 }
1797 }
1798 // contribution is deductible - but there is no product
1799 else {
1800 return '0.00';
1801 }
1802 }
1803 // contribution is NOT deductible
1804 else {
1805 return $params['total_amount'];
1806 }
1807
1808 return 0;
1809 }
1810
1811 }