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