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