Fix comment block for variable declarations
[civicrm-core.git] / CRM / Contribute / Form / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 use Civi\Payment\Exception\PaymentProcessorException;
29
30 /**
31 * This class generates form components for processing a contribution.
32 */
33 class CRM_Contribute_Form_Contribution extends CRM_Contribute_Form_AbstractEditPayment {
34 /**
35 * The id of the contribution that we are processing.
36 *
37 * @var int
38 */
39 public $_id;
40
41 /**
42 * The id of the premium that we are processing.
43 *
44 * @var int
45 */
46 public $_premiumID = NULL;
47
48 /**
49 * @var CRM_Contribute_DAO_ContributionProduct
50 */
51 public $_productDAO = NULL;
52
53 /**
54 * The id of the note.
55 *
56 * @var int
57 */
58 public $_noteID;
59
60 /**
61 * The id of the contact associated with this contribution.
62 *
63 * @var int
64 */
65 public $_contactID;
66
67 /**
68 * The id of the pledge payment that we are processing.
69 *
70 * @var int
71 */
72 public $_ppID;
73
74 /**
75 * Is this contribution associated with an online.
76 * financial transaction
77 *
78 * @var bool
79 */
80 public $_online = FALSE;
81
82 /**
83 * Stores all product options.
84 *
85 * @var array
86 */
87 public $_options;
88
89 /**
90 * Storage of parameters from form
91 *
92 * @var array
93 */
94 public $_params;
95
96 /**
97 * Store the contribution Type ID
98 *
99 * @var array
100 */
101 public $_contributionType;
102
103 /**
104 * The contribution values if an existing contribution
105 * @var array
106 */
107 public $_values;
108
109 /**
110 * The pledge values if this contribution is associated with pledge
111 * @var array
112 */
113 public $_pledgeValues;
114
115 public $_contributeMode = 'direct';
116
117 public $_context;
118
119 /**
120 * Parameter with confusing name.
121 * @var string
122 * @todo what is it?
123 */
124 public $_compContext;
125
126 public $_compId;
127
128 /**
129 * Possible From email addresses
130 * @var array
131 */
132 public $_fromEmails;
133
134 /**
135 * ID of from email.
136 *
137 * @var int
138 */
139 public $fromEmailId;
140
141 /**
142 * Store the line items if price set used.
143 * @var array
144 */
145 public $_lineItems;
146
147 /**
148 * Line item
149 * @var array
150 * @todo explain why we use lineItem & lineItems
151 */
152 public $_lineItem;
153
154 /**
155 * @var array soft credit info
156 */
157 public $_softCreditInfo;
158
159 protected $_formType;
160
161 /**
162 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
163 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
164 *
165 * @var array
166 */
167 public $_paymentFields = [];
168 /**
169 * Logged in user's email.
170 * @var string
171 */
172 public $userEmail;
173
174 /**
175 * Price set ID.
176 *
177 * @var int
178 */
179 public $_priceSetId;
180
181 /**
182 * Price set as an array
183 * @var array
184 */
185 public $_priceSet;
186
187 /**
188 * User display name
189 *
190 * @var string
191 */
192 public $userDisplayName;
193
194 /**
195 * Status message to be shown to the user.
196 *
197 * @var array
198 */
199 protected $statusMessage = [];
200
201 /**
202 * Status message title to be shown to the user.
203 *
204 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
205 * although this might not be a good fit with the broad range of processors.
206 *
207 * @var string
208 */
209 protected $statusMessageTitle;
210
211 /**
212 * @var int
213 *
214 * Max row count for soft credits. The value here is +1 the actual number of
215 * rows displayed.
216 */
217 public $_softCreditItemCount = 11;
218
219 /**
220 * Explicitly declare the form context.
221 */
222 public function getDefaultContext() {
223 return 'create';
224 }
225
226 /**
227 * Set variables up before form is built.
228 */
229 public function preProcess() {
230 // Check permission for action.
231 if (!CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
232 // @todo replace with throw new CRM_Core_Exception().
233 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
234 }
235
236 parent::preProcess();
237
238 $this->_formType = CRM_Utils_Array::value('formType', $_GET);
239
240 // Get price set id.
241 $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
242 $this->set('priceSetId', $this->_priceSetId);
243 $this->assign('priceSetId', $this->_priceSetId);
244
245 // Get the pledge payment id
246 $this->_ppID = CRM_Utils_Request::retrieve('ppid', 'Positive', $this);
247
248 $this->assign('action', $this->_action);
249
250 // Get the contribution id if update
251 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
252 if (!empty($this->_id)) {
253 $this->assignPaymentInfoBlock();
254 $this->assign('contribID', $this->_id);
255 $this->assign('isUsePaymentBlock', TRUE);
256 }
257
258 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
259 $this->assign('context', $this->_context);
260
261 $this->_compId = CRM_Utils_Request::retrieve('compId', 'Positive', $this);
262
263 $this->_compContext = CRM_Utils_Request::retrieve('compContext', 'String', $this);
264
265 //set the contribution mode.
266 $this->_mode = CRM_Utils_Request::retrieve('mode', 'Alphanumeric', $this);
267
268 $this->assign('contributionMode', $this->_mode);
269 if ($this->_action & CRM_Core_Action::DELETE) {
270 return;
271 }
272
273 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
274
275 if (in_array('CiviPledge', CRM_Core_Config::singleton()->enableComponents) && !$this->_formType) {
276 $this->preProcessPledge();
277 }
278
279 if ($this->_id) {
280 $this->showRecordLinkMesssage($this->_id);
281 }
282 $this->_values = [];
283
284 // Current contribution id.
285 if ($this->_id) {
286 $this->assignPremiumProduct($this->_id);
287 $this->buildValuesAndAssignOnline_Note_Type($this->_id, $this->_values);
288 }
289
290 // when custom data is included in this page
291 if (!empty($_POST['hidden_custom'])) {
292 $this->applyCustomData('Contribution', CRM_Utils_Array::value('financial_type_id', $_POST), $this->_id);
293 }
294
295 $this->_lineItems = [];
296 if ($this->_id) {
297 if (!empty($this->_compId) && $this->_compContext == 'participant') {
298 $this->assign('compId', $this->_compId);
299 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_compId);
300 }
301 else {
302 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution', 1, TRUE, TRUE);
303 }
304 // wtf?
305 empty($lineItem) ? NULL : $this->_lineItems[] = $lineItem;
306 }
307
308 $this->assign('lineItem', empty($lineItem) ? FALSE : [$lineItem]);
309
310 // Set title
311 if ($this->_mode && $this->_id) {
312 $this->_payNow = TRUE;
313 $this->assign('payNow', $this->_payNow);
314 CRM_Utils_System::setTitle(ts('Pay with Credit Card'));
315 }
316 elseif ($this->_mode) {
317 $this->setPageTitle($this->_ppID ? ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
318 }
319 else {
320 $this->setPageTitle($this->_ppID ? ts('Pledge Payment') : ts('Contribution'));
321 }
322 }
323
324 /**
325 * Set default values.
326 *
327 * @return array
328 */
329 public function setDefaultValues() {
330 $defaults = $this->_values;
331
332 // Set defaults for pledge payment.
333 if ($this->_ppID) {
334 $defaults['total_amount'] = CRM_Utils_Array::value('scheduled_amount', $this->_pledgeValues['pledgePayment']);
335 $defaults['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $this->_pledgeValues);
336 $defaults['currency'] = CRM_Utils_Array::value('currency', $this->_pledgeValues);
337 $defaults['option_type'] = 1;
338 }
339
340 if ($this->_action & CRM_Core_Action::DELETE) {
341 return $defaults;
342 }
343
344 $defaults['frequency_interval'] = 1;
345 $defaults['frequency_unit'] = 'month';
346
347 // Set soft credit defaults.
348 CRM_Contribute_Form_SoftCredit::setDefaultValues($defaults, $this);
349
350 if ($this->_mode) {
351 // @todo - remove this function as the parent does it too.
352 $config = CRM_Core_Config::singleton();
353 // Set default country from config if no country set.
354 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
355 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
356 }
357
358 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
359 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
360 }
361
362 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
363 $defaults = array_merge($defaults, $billingDefaults);
364 }
365
366 if ($this->_id) {
367 $this->_contactID = $defaults['contact_id'];
368 }
369
370 // Set $newCredit variable in template to control whether link to credit card mode is included.
371 $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
372
373 // Fix the display of the monetary value, CRM-4038.
374 if (isset($defaults['total_amount'])) {
375 $total_value = $defaults['total_amount'];
376 $defaults['total_amount'] = CRM_Utils_Money::format($total_value, NULL, '%a');
377 if (!empty($defaults['tax_amount'])) {
378 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
379 if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
380 $defaults['total_amount'] = CRM_Utils_Money::format($total_value - $defaults['tax_amount'], NULL, '%a');
381 }
382 }
383 }
384
385 $amountFields = ['non_deductible_amount', 'fee_amount'];
386 foreach ($amountFields as $amt) {
387 if (isset($defaults[$amt])) {
388 $defaults[$amt] = CRM_Utils_Money::format($defaults[$amt], NULL, '%a');
389 }
390 }
391
392 if ($this->_contributionType) {
393 $defaults['financial_type_id'] = $this->_contributionType;
394 }
395
396 if (empty($defaults['payment_instrument_id'])) {
397 $defaults['payment_instrument_id'] = $this->getDefaultPaymentInstrumentId();
398 }
399
400 if (!empty($defaults['is_test'])) {
401 $this->assign('is_test', TRUE);
402 }
403
404 $this->assign('showOption', TRUE);
405 // For Premium section.
406 if ($this->_premiumID) {
407 $this->assign('showOption', FALSE);
408 $options = isset($this->_options[$this->_productDAO->product_id]) ? $this->_options[$this->_productDAO->product_id] : "";
409 if (!$options) {
410 $this->assign('showOption', TRUE);
411 }
412 $options_key = CRM_Utils_Array::key($this->_productDAO->product_option, $options);
413 if ($options_key) {
414 $defaults['product_name'] = [$this->_productDAO->product_id, trim($options_key)];
415 }
416 else {
417 $defaults['product_name'] = [$this->_productDAO->product_id];
418 }
419 if ($this->_productDAO->fulfilled_date) {
420 $defaults['fulfilled_date'] = $this->_productDAO->fulfilled_date;
421 }
422 }
423
424 if (isset($this->userEmail)) {
425 $this->assign('email', $this->userEmail);
426 }
427
428 if (!empty($defaults['is_pay_later'])) {
429 $this->assign('is_pay_later', TRUE);
430 }
431 $this->assign('contribution_status_id', CRM_Utils_Array::value('contribution_status_id', $defaults));
432 if (!empty($defaults['contribution_status_id']) && in_array(
433 CRM_Contribute_PseudoConstant::contributionStatus($defaults['contribution_status_id'], 'name'),
434 // Historically not 'Cancelled' hence not using CRM_Contribute_BAO_Contribution::isContributionStatusNegative.
435 ['Refunded', 'Chargeback']
436 )) {
437 $defaults['refund_trxn_id'] = CRM_Core_BAO_FinancialTrxn::getRefundTransactionTrxnID($this->_id);
438 }
439 else {
440 $defaults['refund_trxn_id'] = isset($defaults['trxn_id']) ? $defaults['trxn_id'] : NULL;
441 }
442
443 if (!$this->_id && empty($defaults['receive_date'])) {
444 $defaults['receive_date'] = date('Y-m-d H:i:s');
445 }
446
447 $currency = CRM_Utils_Array::value('currency', $defaults);
448 $this->assign('currency', $currency);
449 // Hack to get currency info to the js layer. CRM-11440.
450 CRM_Utils_Money::format(1);
451 $this->assign('currencySymbol', CRM_Utils_Array::value($currency, CRM_Utils_Money::$_currencySymbols));
452 $this->assign('totalAmount', CRM_Utils_Array::value('total_amount', $defaults));
453
454 // Inherit campaign from pledge.
455 if ($this->_ppID && !empty($this->_pledgeValues['campaign_id'])) {
456 $defaults['campaign_id'] = $this->_pledgeValues['campaign_id'];
457 }
458
459 $this->_defaults = $defaults;
460 return $defaults;
461 }
462
463 /**
464 * Build the form object.
465 */
466 public function buildQuickForm() {
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::fatal(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 if ($this->_context == 'standalone') {
619 $this->addEntityRef('contact_id', ts('Contact'), [
620 'create' => TRUE,
621 'api' => ['extra' => ['email']],
622 ], TRUE);
623 }
624
625 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
626
627 // Check permissions for financial type first
628 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action);
629 if (empty($financialTypes)) {
630 CRM_Core_Error::statusBounce(ts('You do not have all the permissions needed for this page.'));
631 }
632 $financialType = $this->add('select', 'financial_type_id',
633 ts('Financial Type'),
634 ['' => ts('- select -')] + $financialTypes,
635 TRUE,
636 ['onChange' => "CRM.buildCustomData( 'Contribution', this.value );"]
637 );
638
639 $paymentInstrument = FALSE;
640 if (!$this->_mode) {
641 // payment_instrument isn't required in edit and will not be present when payment block is enabled.
642 $required = $this->_id ? FALSE : TRUE;
643 $checkPaymentID = array_search('Check', CRM_Contribute_PseudoConstant::paymentInstrument('name'));
644 $paymentInstrument = $this->add('select', 'payment_instrument_id',
645 ts('Payment Method'),
646 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
647 $required, ['onChange' => "return showHideByValue('payment_instrument_id','{$checkPaymentID}','checkNumber','table-row','select',false);"]
648 );
649 }
650
651 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), ['class' => 'twelve'] + $attributes['trxn_id']);
652
653 //add receipt for offline contribution
654 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
655
656 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
657
658 $component = 'contribution';
659 $componentDetails = [];
660 if ($this->_id) {
661 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
662 if (CRM_Utils_Array::value('membership', $componentDetails)) {
663 $component = 'membership';
664 }
665 elseif (CRM_Utils_Array::value('participant', $componentDetails)) {
666 $component = 'participant';
667 }
668 }
669 if ($this->_ppID) {
670 $component = 'pledge';
671 }
672 $status = CRM_Contribute_BAO_Contribution_Utils::getContributionStatuses($component, $this->_id);
673
674 // define the status IDs that show the cancellation info, see CRM-17589
675 $cancelInfo_show_ids = [];
676 foreach (array_keys($status) as $status_id) {
677 if (CRM_Contribute_BAO_Contribution::isContributionStatusNegative($status_id)) {
678 $cancelInfo_show_ids[] = "'$status_id'";
679 }
680 }
681 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
682
683 $statusElement = $this->add('select', 'contribution_status_id',
684 ts('Contribution Status'),
685 $status,
686 FALSE
687 );
688
689 $currencyFreeze = FALSE;
690 if (!empty($this->_payNow) && ($this->_action & CRM_Core_Action::UPDATE)) {
691 $statusElement->freeze();
692 $currencyFreeze = TRUE;
693 $attributes['total_amount']['readonly'] = TRUE;
694 }
695
696 // CRM-16189, add Revenue Recognition Date
697 if (Civi::settings()->get('deferred_revenue_enabled')) {
698 $revenueDate = $this->add('date', 'revenue_recognition_date', ts('Revenue Recognition Date'), CRM_Core_SelectValues::date(NULL, 'M Y', NULL, 5));
699 if ($this->_id && !CRM_Contribute_BAO_Contribution::allowUpdateRevenueRecognitionDate($this->_id)) {
700 $revenueDate->freeze();
701 }
702 }
703
704 // add various dates
705 $this->addField('receive_date', ['entity' => 'contribution'], !$this->_mode, FALSE);
706 $this->addField('receipt_date', ['entity' => 'contribution'], FALSE, FALSE);
707 $this->addField('cancel_date', ['entity' => 'contribution', 'label' => ts('Cancelled / Refunded Date')], FALSE, FALSE);
708
709 if ($this->_online) {
710 $this->assign('hideCalender', TRUE);
711 }
712
713 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
714
715 $totalAmount = NULL;
716 if (empty($this->_lineItems)) {
717 $buildPriceSet = FALSE;
718 $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute');
719 if (!empty($priceSets) && !$this->_ppID) {
720 $buildPriceSet = TRUE;
721 }
722
723 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
724 // and if we already have line items for that participant. CRM-5095
725 if ($buildPriceSet && $this->_id) {
726 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
727 $this->_id,
728 'id',
729 'contribution_id'
730 );
731 if ($pledgePaymentId) {
732 $buildPriceSet = FALSE;
733 }
734 if ($participantID = CRM_Utils_Array::value('participant', $componentDetails)) {
735 $participantLI = CRM_Price_BAO_LineItem::getLineItems($participantID);
736 if (!CRM_Utils_System::isNull($participantLI)) {
737 $buildPriceSet = FALSE;
738 }
739 }
740 }
741
742 $hasPriceSets = FALSE;
743 if ($buildPriceSet) {
744 $hasPriceSets = TRUE;
745 // CRM-16451: set financial type of 'Price Set' in back office contribution
746 // instead of selecting manually
747 $financialTypeIds = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
748 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
749 [
750 '' => ts('Choose price set'),
751 ] + $priceSets,
752 NULL, ['onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");"]
753 );
754 if ($this->_online && !($this->_action & CRM_Core_Action::UPDATE)) {
755 $element->freeze();
756 }
757 }
758 $this->assign('hasPriceSets', $hasPriceSets);
759 if (!($this->_action & CRM_Core_Action::UPDATE)) {
760 if ($this->_online || $this->_ppID) {
761 $attributes['total_amount'] = array_merge($attributes['total_amount'], [
762 'READONLY' => TRUE,
763 'style' => "background-color:#EBECE4",
764 ]);
765 $optionTypes = [
766 '1' => ts('Adjust Pledge Payment Schedule?'),
767 '2' => ts('Adjust Total Pledge Amount?'),
768 ];
769 $this->addRadio('option_type',
770 NULL,
771 $optionTypes,
772 [], '<br/>'
773 );
774
775 $currencyFreeze = TRUE;
776 }
777 }
778
779 $totalAmount = $this->addMoney('total_amount',
780 ts('Total Amount'),
781 ($hasPriceSets) ? FALSE : TRUE,
782 $attributes['total_amount'],
783 TRUE, 'currency', NULL, $currencyFreeze
784 );
785 }
786
787 $this->add('text', 'source', ts('Source'), CRM_Utils_Array::value('source', $attributes));
788
789 // CRM-7362 --add campaigns.
790 CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
791
792 if (empty($this->_payNow)) {
793 CRM_Contribute_Form_SoftCredit::buildQuickForm($this);
794 }
795
796 $js = NULL;
797 if (!$this->_mode) {
798 $js = ['onclick' => "return verify( );"];
799 }
800
801 $mailingInfo = Civi::settings()->get('mailing_backend');
802 $this->assign('outBound_option', $mailingInfo['outBound_option']);
803
804 $this->addButtons([
805 [
806 'type' => 'upload',
807 'name' => ts('Save'),
808 'js' => $js,
809 'isDefault' => TRUE,
810 ],
811 [
812 'type' => 'upload',
813 'name' => ts('Save and New'),
814 'js' => $js,
815 'subName' => 'new',
816 ],
817 [
818 'type' => 'cancel',
819 'name' => ts('Cancel'),
820 ],
821 ]);
822
823 // if contribution is related to membership or participant freeze Financial Type, Amount
824 if ($this->_id) {
825 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
826 $isCancelledStatus = ($this->_values['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Cancelled'));
827
828 if (CRM_Utils_Array::value('membership', $componentDetails) ||
829 CRM_Utils_Array::value('participant', $componentDetails) ||
830 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
831 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
832 $isCancelledStatus
833 ) {
834 if ($totalAmount) {
835 $totalAmount->freeze();
836 $this->getElement('currency')->freeze();
837 }
838 if ($isCancelledStatus) {
839 $paymentInstrument->freeze();
840 $trxnId->freeze();
841 }
842 $financialType->freeze();
843 $this->assign('freezeFinancialType', TRUE);
844 }
845 }
846
847 if ($this->_action & CRM_Core_Action::VIEW) {
848 $this->freeze();
849 }
850 }
851
852 /**
853 * Global form rule.
854 *
855 * @param array $fields
856 * The input form values.
857 * @param array $files
858 * The uploaded files if any.
859 * @param $self
860 *
861 * @return bool|array
862 * true if no errors, else array of errors
863 */
864 public static function formRule($fields, $files, $self) {
865 $errors = [];
866 // Check for Credit Card Contribution.
867 if ($self->_mode) {
868 if (empty($fields['payment_processor_id'])) {
869 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
870 }
871 else {
872 // validate payment instrument (e.g. credit card number)
873 CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
874 }
875 }
876
877 // Do the amount validations.
878 if (empty($fields['total_amount']) && empty($self->_lineItems)) {
879 if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) {
880 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $fields, $errors);
881 }
882 }
883
884 $softErrors = CRM_Contribute_Form_SoftCredit::formRule($fields, $errors, $self);
885
886 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
887 CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors);
888
889 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
890 if (($self->_action & CRM_Core_Action::UPDATE)
891 && $self->_id
892 && $self->_values['contribution_status_id'] != $fields['contribution_status_id']
893 ) {
894 CRM_Contribute_BAO_Contribution::checkStatusValidation($self->_values, $fields, $errors);
895 }
896 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
897 if (($self->_action & CRM_Core_Action::UPDATE)
898 && $self->_id
899 && $self->_values['financial_type_id'] != $fields['financial_type_id']
900 ) {
901 CRM_Contribute_BAO_Contribution::checkFinancialTypeChange(NULL, $self->_id, $errors);
902 }
903 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
904 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution::validateFinancialType($fields['financial_type_id'])) {
905 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
906 }
907
908 // $trxn_id must be unique CRM-13919
909 if (!empty($fields['trxn_id'])) {
910 $queryParams = [1 => [$fields['trxn_id'], 'String']];
911 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
912 if ($self->_id) {
913 $queryParams[2] = [(int) $self->_id, 'Integer'];
914 $query .= ' and id !=%2';
915 }
916 $tCnt = CRM_Core_DAO::singleValueQuery($query, $queryParams);
917 if ($tCnt) {
918 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', [1 => $fields['trxn_id']]);
919 }
920 }
921 if (!empty($fields['revenue_recognition_date'])
922 && count(array_filter($fields['revenue_recognition_date'])) == 1
923 ) {
924 $errors['revenue_recognition_date'] = ts('Month and Year are required field for Revenue Recognition.');
925 }
926 // CRM-16189
927 try {
928 CRM_Financial_BAO_FinancialAccount::checkFinancialTypeHasDeferred($fields, $self->_id, $self->_priceSet['fields']);
929 }
930 catch (CRM_Core_Exception $e) {
931 $errors['financial_type_id'] = ' ';
932 $errors['_qf_default'] = $e->getMessage();
933 }
934 $errors = array_merge($errors, $softErrors);
935 return $errors;
936 }
937
938 /**
939 * Process the form submission.
940 */
941 public function postProcess() {
942 if ($this->_action & CRM_Core_Action::DELETE) {
943 CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
944 CRM_Core_Session::singleton()->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
945 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
946 ));
947 return;
948 }
949 // Get the submitted form values.
950 $submittedValues = $this->controller->exportValues($this->_name);
951
952 try {
953 $contribution = $this->submit($submittedValues, $this->_action, $this->_ppID);
954 }
955 catch (PaymentProcessorException $e) {
956 // Set the contribution mode.
957 $urlParams = "action=add&cid={$this->_contactID}";
958 if ($this->_mode) {
959 $urlParams .= "&mode={$this->_mode}";
960 }
961 if (!empty($this->_ppID)) {
962 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
963 }
964
965 CRM_Core_Error::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
966 }
967 $session = CRM_Core_Session::singleton();
968 $buttonName = $this->controller->getButtonName();
969 if ($this->_context == 'standalone') {
970 if ($buttonName == $this->getButtonName('upload', 'new')) {
971 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add',
972 'reset=1&action=add&context=standalone'
973 ));
974 }
975 else {
976 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
977 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
978 ));
979 }
980 }
981 elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) {
982 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
983 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
984 ));
985 }
986 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
987 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
988 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
989 ));
990 }
991
992 //store contribution ID if not yet set (on create)
993 if (empty($this->_id) && !empty($contribution->id)) {
994 $this->_id = $contribution->id;
995 }
996 if (!empty($this->_id) && CRM_Core_Permission::access('CiviMember')) {
997 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', ['contribution_id' => $this->_id]);
998 if ($membershipPaymentCount) {
999 $this->ajaxResponse['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact::getCountComponent('membership', $this->_contactID);
1000 }
1001 }
1002 if (!empty($this->_id) && CRM_Core_Permission::access('CiviEvent')) {
1003 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', ['contribution_id' => $this->_id]);
1004 if ($participantPaymentCount) {
1005 $this->ajaxResponse['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact::getCountComponent('participant', $this->_contactID);
1006 }
1007 }
1008 }
1009
1010 /**
1011 * Process credit card payment.
1012 *
1013 * @param array $submittedValues
1014 * @param array $lineItem
1015 *
1016 * @param int $contactID
1017 * Contact ID
1018 *
1019 * @return bool|\CRM_Contribute_DAO_Contribution
1020 * @throws \CRM_Core_Exception
1021 * @throws \Civi\Payment\Exception\PaymentProcessorException
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 * @throws \CiviCRM_API3_Exception
1285 */
1286 public function testSubmit($params, $action, $creditCardMode = NULL) {
1287 $defaults = [
1288 'soft_credit_contact_id' => [],
1289 'receive_date' => date('Y-m-d H:i:s'),
1290 'receipt_date' => '',
1291 'cancel_date' => '',
1292 'hidden_Premium' => 1,
1293 ];
1294 $this->_bltID = 5;
1295 if (!empty($params['id'])) {
1296 $existingContribution = civicrm_api3('contribution', 'getsingle', [
1297 'id' => $params['id'],
1298 ]);
1299 $this->_id = $params['id'];
1300 $this->_values = $existingContribution;
1301 if (CRM_Contribute_BAO_Contribution::checkContributeSettings('invoicing')) {
1302 $this->_values['tax_amount'] = civicrm_api3('contribution', 'getvalue', [
1303 'id' => $params['id'],
1304 'return' => 'tax_amount',
1305 ]);
1306 }
1307 }
1308 else {
1309 $existingContribution = [];
1310 }
1311
1312 $this->_defaults['contribution_status_id'] = CRM_Utils_Array::value('contribution_status_id',
1313 $existingContribution
1314 );
1315
1316 $this->_defaults['total_amount'] = CRM_Utils_Array::value('total_amount',
1317 $existingContribution
1318 );
1319
1320 if ($creditCardMode) {
1321 $this->_mode = $creditCardMode;
1322 }
1323
1324 // Required because processCreditCard calls set method on this.
1325 $_SERVER['REQUEST_METHOD'] = 'GET';
1326 $this->controller = new CRM_Core_Controller();
1327
1328 CRM_Contribute_Form_AdditionalInfo::buildPremium($this);
1329
1330 $this->_fields = [];
1331 return $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array::value('pledge_payment_id', $params));
1332
1333 }
1334
1335 /**
1336 * @param array $submittedValues
1337 *
1338 * @param int $action
1339 * Action constant
1340 * - CRM_Core_Action::UPDATE
1341 *
1342 * @param $pledgePaymentID
1343 *
1344 * @return array
1345 * @throws \Exception
1346 */
1347 protected function submit($submittedValues, $action, $pledgePaymentID) {
1348 $pId = $contribution = $isRelatedId = FALSE;
1349 $this->_params = $submittedValues;
1350 $this->beginPostProcess();
1351 // reassign submitted form values if the any information is formatted via beginPostProcess
1352 $submittedValues = $this->_params;
1353
1354 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action::UPDATE) {
1355 $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
1356 $lineID = key($line);
1357 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
1358 $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1359 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1360 // config should be treated the same.
1361 if ($quickConfig) {
1362 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
1363 }
1364 }
1365
1366 // Process price set and get total amount and line items.
1367 $lineItem = [];
1368 $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
1369 if (empty($priceSetId) && !$this->_id) {
1370 $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1371 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
1372 $fieldID = key($this->_priceSet['fields']);
1373 $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
1374 $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1375 $submittedValues['price_' . $fieldID] = 1;
1376 }
1377
1378 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1379 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1380 // as a point of fragility rather than a logical 'if' clause.
1381 if ($priceSetId) {
1382 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
1383 $submittedValues, $lineItem[$priceSetId], NULL, $priceSetId);
1384 // Unset tax amount for offline 'is_quick_config' contribution.
1385 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1386 // this is an example of 'other' functionality being hung off it.
1387 if ($this->_priceSet['is_quick_config'] &&
1388 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())
1389 ) {
1390 unset($submittedValues['tax_amount']);
1391 }
1392 $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
1393 }
1394
1395 if ($this->_id) {
1396 if ($this->_compId) {
1397 if ($this->_context == 'participant') {
1398 $pId = $this->_compId;
1399 }
1400 elseif ($this->_context == 'membership') {
1401 $isRelatedId = TRUE;
1402 }
1403 else {
1404 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
1405 }
1406 }
1407 else {
1408 $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1409 if (array_key_exists('membership', $contributionDetails)) {
1410 $isRelatedId = TRUE;
1411 }
1412 elseif (array_key_exists('participant', $contributionDetails)) {
1413 $pId = $contributionDetails['participant'];
1414 }
1415 }
1416 if (!empty($this->_payNow)) {
1417 $this->_params['contribution_id'] = $this->_id;
1418 }
1419 }
1420
1421 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
1422 // CRM-10117 update the line items for participants.
1423 // @todo - if we are completing a contribution then the api call
1424 // civicrm_api3('Contribution', 'completetransaction') should take care of
1425 // all associated updates rather than replicating them on the form layer.
1426 if ($pId) {
1427 $entityTable = 'participant';
1428 $entityID = $pId;
1429 $isRelatedId = FALSE;
1430 $participantParams = [
1431 'fee_amount' => $submittedValues['total_amount'],
1432 'id' => $entityID,
1433 ];
1434 CRM_Event_BAO_Participant::add($participantParams);
1435 if (empty($this->_lineItems)) {
1436 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', TRUE);
1437 }
1438 }
1439 else {
1440 $entityTable = 'contribution';
1441 $entityID = $this->_id;
1442 }
1443
1444 $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
1445 foreach (array_keys($lineItems) as $id) {
1446 $lineItems[$id]['id'] = $id;
1447 }
1448 $itemId = key($lineItems);
1449 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1450 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1451 }
1452
1453 // @todo see above - new functionality has been inappropriately added to the quick config concept
1454 // and new functionality has been added onto the form layer rather than the BAO :-(
1455 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1456 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1457 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1458 if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
1459 if (!($this->_action & CRM_Core_Action::UPDATE && (($this->_defaults['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1460 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
1461 }
1462 }
1463
1464 // Update line total and total amount with tax on edit.
1465 $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
1466 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1467 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1468 }
1469 else {
1470 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1471 $submittedValues['tax_amount'] = 'null';
1472 }
1473 if ($lineItems[$itemId]['tax_rate']) {
1474 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1475 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
1476 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1477 }
1478 }
1479 // CRM-10117 update the line items for participants.
1480 if (!empty($lineItems[$itemId]['price_field_id'])) {
1481 $lineItem[$this->_priceSetId] = $lineItems;
1482 }
1483 }
1484
1485 $isQuickConfig = 0;
1486 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1487 $isQuickConfig = 1;
1488 }
1489 //CRM-11529 for quick config back office transactions
1490 //when financial_type_id is passed in form, update the
1491 //line items with the financial type selected in form
1492 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1493 // we should look at having a price field per contribution type & then there would be little reason
1494 // for the back-office contribution form postProcess to know if it is a quick-config form.
1495 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)
1496 ) {
1497 foreach ($lineItem[$this->_priceSetId] as &$values) {
1498 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1499 }
1500 }
1501
1502 if (!isset($submittedValues['total_amount'])) {
1503 $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
1504 // Avoid tax amount deduction on edit form and keep it original, because this will lead to error described in CRM-20676
1505 if (!$this->_id) {
1506 $submittedValues['total_amount'] -= CRM_Utils_Array::value('tax_amount', $this->_values, 0);
1507 }
1508 }
1509 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1510
1511 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1512 if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
1513 civicrm_api3('ContributionSoft', 'get', ['contribution_id' => $this->_id, 'pcp_id' => NULL, 'api.ContributionSoft.delete' => 1]);
1514 }
1515
1516 // set the contact, when contact is selected
1517 if (!empty($submittedValues['contact_id'])) {
1518 $this->_contactID = $submittedValues['contact_id'];
1519 }
1520
1521 $formValues = $submittedValues;
1522
1523 // Credit Card Contribution.
1524 if ($this->_mode) {
1525 $paramsSetByPaymentProcessingSubsystem = [
1526 'trxn_id',
1527 'payment_instrument_id',
1528 'contribution_status_id',
1529 'cancel_date',
1530 'cancel_reason',
1531 ];
1532 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1533 if (isset($formValues[$key])) {
1534 unset($formValues[$key]);
1535 }
1536 }
1537 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID);
1538 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1539 $formValues[$key] = $contribution->$key;
1540 }
1541 }
1542 else {
1543 // Offline Contribution.
1544 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1545
1546 // get the required field value only.
1547
1548 $params = [
1549 'contact_id' => $this->_contactID,
1550 'currency' => $this->getCurrency($submittedValues),
1551 'skipCleanMoney' => TRUE,
1552 'id' => $this->_id,
1553 ];
1554
1555 //format soft-credit/pcp param first
1556 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($submittedValues, $this);
1557 $params = array_merge($params, $submittedValues);
1558
1559 $fields = [
1560 'financial_type_id',
1561 'contribution_status_id',
1562 'payment_instrument_id',
1563 'cancel_reason',
1564 'source',
1565 'check_number',
1566 'card_type_id',
1567 'pan_truncation',
1568 ];
1569 foreach ($fields as $f) {
1570 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1571 }
1572
1573 $params['revenue_recognition_date'] = NULL;
1574 if (!empty($formValues['revenue_recognition_date'])
1575 && count(array_filter($formValues['revenue_recognition_date'])) == 2
1576 ) {
1577 $params['revenue_recognition_date'] = CRM_Utils_Date::processDate(
1578 '01-' . implode('-', $formValues['revenue_recognition_date'])
1579 );
1580 }
1581
1582 if (!empty($formValues['is_email_receipt'])) {
1583 $params['receipt_date'] = date("Y-m-d");
1584 }
1585
1586 if (CRM_Contribute_BAO_Contribution::isContributionStatusNegative($params['contribution_status_id'])
1587 ) {
1588 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
1589 $params['cancel_date'] = date('YmdHis');
1590 }
1591 }
1592 else {
1593 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1594 }
1595
1596 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1597 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1598 if ($params['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
1599 $params['is_pay_later'] = 1;
1600 }
1601 elseif ($params['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
1602 $params['is_pay_later'] = 0;
1603 }
1604
1605 // Add Additional common information to formatted params.
1606 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
1607 if ($pId) {
1608 $params['contribution_mode'] = 'participant';
1609 $params['participant_id'] = $pId;
1610 $params['skipLineItem'] = 1;
1611 }
1612 elseif ($isRelatedId) {
1613 $params['contribution_mode'] = 'membership';
1614 }
1615 $params['line_item'] = $lineItem;
1616 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
1617 $params['tax_amount'] = CRM_Utils_Array::value('tax_amount', $submittedValues, CRM_Utils_Array::value('tax_amount', $this->_values));
1618 //create contribution.
1619 if ($isQuickConfig) {
1620 $params['is_quick_config'] = 1;
1621 }
1622 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1623
1624 // we are already handling note below, so to avoid duplicate notes against $contribution
1625 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1626 unset($params['note']);
1627 }
1628 $contribution = CRM_Contribute_BAO_Contribution::create($params);
1629
1630 // process associated membership / participant, CRM-4395
1631 if ($contribution->id && $action & CRM_Core_Action::UPDATE) {
1632 $this->statusMessage[] = CRM_Contribute_BAO_Contribution::transitionComponentWithReturnMessage($contribution->id,
1633 $contribution->contribution_status_id,
1634 CRM_Utils_Array::value('contribution_status_id',
1635 $this->_values
1636 ),
1637 $contribution->receive_date
1638 );
1639 }
1640
1641 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
1642
1643 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1644
1645 //send receipt mail.
1646 if ($contribution->id && !empty($formValues['is_email_receipt'])) {
1647 $formValues['contact_id'] = $this->_contactID;
1648 $formValues['contribution_id'] = $contribution->id;
1649
1650 $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
1651
1652 // to get 'from email id' for send receipt
1653 $this->fromEmailId = CRM_Utils_Array::value('from_email_address', $formValues);
1654 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues)) {
1655 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
1656 }
1657 }
1658
1659 $this->statusMessageTitle = ts('Saved');
1660
1661 }
1662
1663 if ($contribution->id && isset($formValues['product_name'][0])) {
1664 CRM_Contribute_Form_AdditionalInfo::processPremium($submittedValues, $contribution->id,
1665 $this->_premiumID, $this->_options
1666 );
1667 }
1668
1669 if ($contribution->id && array_key_exists('note', $submittedValues)) {
1670 CRM_Contribute_Form_AdditionalInfo::processNote($submittedValues, $this->_contactID, $contribution->id, $this->_noteID);
1671 }
1672
1673 CRM_Core_Session::setStatus(implode(' ', $this->statusMessage), $this->statusMessageTitle, 'success');
1674
1675 CRM_Contribute_BAO_Contribution::updateRelatedPledge(
1676 $action,
1677 $pledgePaymentID,
1678 $contribution->id,
1679 (CRM_Utils_Array::value('option_type', $formValues) == 2) ? TRUE : FALSE,
1680 $formValues['total_amount'],
1681 CRM_Utils_Array::value('total_amount', $this->_defaults),
1682 $formValues['contribution_status_id'],
1683 CRM_Utils_Array::value('contribution_status_id', $this->_defaults)
1684 );
1685 return $contribution;
1686 }
1687
1688 /**
1689 * Assign tax calculations to contribution receipts.
1690 *
1691 * @param array $submittedValues
1692 * @param int $action
1693 * @param array $lineItem
1694 */
1695 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1696
1697 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
1698 if (!CRM_Utils_Array::value('invoicing', $invoiceSettings)) {
1699 return;
1700 }
1701 $taxRate = [];
1702 $getTaxDetails = FALSE;
1703
1704 foreach ($lineItem as $key => $value) {
1705 foreach ($value as $v) {
1706 if (isset($taxRate[(string) CRM_Utils_Array::value('tax_rate', $v)])) {
1707 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array::value('tax_amount', $v);
1708 }
1709 else {
1710 if (isset($v['tax_rate'])) {
1711 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array::value('tax_amount', $v);
1712 $getTaxDetails = TRUE;
1713 }
1714 }
1715 }
1716 }
1717
1718 if ($action & CRM_Core_Action::UPDATE) {
1719 if (isset($submittedValues['tax_amount'])) {
1720 $totalTaxAmount = $submittedValues['tax_amount'];
1721 }
1722 else {
1723 $totalTaxAmount = $this->_values['tax_amount'];
1724 }
1725 $this->assign('totalTaxAmount', $totalTaxAmount);
1726 $this->assign('dataArray', $taxRate);
1727 }
1728 else {
1729 if (!empty($submittedValues['price_set_id'])) {
1730 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1731 $this->assign('getTaxDetails', $getTaxDetails);
1732 $this->assign('dataArray', $taxRate);
1733 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
1734 }
1735 else {
1736 $this->assign('totalTaxAmount', CRM_Utils_Array::value('tax_amount', $submittedValues));
1737 }
1738 }
1739 }
1740
1741 /**
1742 * Calculate non deductible amount.
1743 *
1744 * CRM-11956
1745 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1746 * if non_deductible_amount does NOT exist - then calculate it depending on:
1747 * $financialType->is_deductible and whether there is a product (premium).
1748 *
1749 * @param $params
1750 * @param $formValues
1751 *
1752 * @return array
1753 */
1754 protected function calculateNonDeductibleAmount($params, $formValues) {
1755 if (!empty($params['non_deductible_amount'])) {
1756 return $params['non_deductible_amount'];
1757 }
1758
1759 $priceSetId = CRM_Utils_Array::value('price_set_id', $params);
1760 // return non-deductible amount if it is set at the price field option level
1761 if ($priceSetId && !empty($params['line_item'])) {
1762 $nonDeductibleAmount = CRM_Price_BAO_PriceSet::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1763 if (!empty($nonDeductibleAmount)) {
1764 return $nonDeductibleAmount;
1765 }
1766 }
1767
1768 $financialType = new CRM_Financial_DAO_FinancialType();
1769 $financialType->id = $params['financial_type_id'];
1770 $financialType->find(TRUE);
1771
1772 if ($financialType->is_deductible) {
1773
1774 if (isset($formValues['product_name'][0])) {
1775 $selectProduct = $formValues['product_name'][0];
1776 }
1777 // if there is a product - compare the value to the contribution amount
1778 if (isset($selectProduct)) {
1779 $productDAO = new CRM_Contribute_DAO_Product();
1780 $productDAO->id = $selectProduct;
1781 $productDAO->find(TRUE);
1782 // product value exceeds contribution amount
1783 if ($params['total_amount'] < $productDAO->price) {
1784 return $params['total_amount'];
1785 }
1786 // product value does NOT exceed contribution amount
1787 else {
1788 return $productDAO->price;
1789 }
1790 }
1791 // contribution is deductible - but there is no product
1792 else {
1793 return '0.00';
1794 }
1795 }
1796 // contribution is NOT deductible
1797 else {
1798 return $params['total_amount'];
1799 }
1800
1801 return 0;
1802 }
1803
1804 }