| 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\Api4\Activity; |
| 13 | use Civi\Api4\ContributionPage; |
| 14 | use Civi\Api4\ContributionRecur; |
| 15 | use Civi\Api4\Participant; |
| 16 | use Civi\Api4\PaymentProcessor; |
| 17 | |
| 18 | /** |
| 19 | * |
| 20 | * @package CRM |
| 21 | * @copyright CiviCRM LLC https://civicrm.org/licensing |
| 22 | */ |
| 23 | class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution { |
| 24 | |
| 25 | /** |
| 26 | * Static field for all the contribution information that we can potentially import |
| 27 | * |
| 28 | * @var array |
| 29 | */ |
| 30 | public static $_importableFields = NULL; |
| 31 | |
| 32 | /** |
| 33 | * Static field for all the contribution information that we can potentially export |
| 34 | * |
| 35 | * @var array |
| 36 | */ |
| 37 | public static $_exportableFields = NULL; |
| 38 | |
| 39 | /** |
| 40 | * Static field to hold financial trxn id's. |
| 41 | * |
| 42 | * @var array |
| 43 | */ |
| 44 | public static $_trxnIDs = NULL; |
| 45 | |
| 46 | /** |
| 47 | * Field for all the objects related to this contribution |
| 48 | * |
| 49 | * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[] |
| 50 | */ |
| 51 | public $_relatedObjects = []; |
| 52 | |
| 53 | /** |
| 54 | * Field for the component - either 'event' (participant) or 'contribute' |
| 55 | * (any item related to a contribution page e.g. membership, pledge, contribution) |
| 56 | * This is used for composing messages because they have dependency on the |
| 57 | * contribution_page or event page - although over time we may eliminate that |
| 58 | * |
| 59 | * @var string |
| 60 | * "contribution"\"event" |
| 61 | */ |
| 62 | public $_component = NULL; |
| 63 | |
| 64 | /** |
| 65 | * Possibly obsolete variable. |
| 66 | * |
| 67 | * If you use it please explain why it is set in the create function here. |
| 68 | * |
| 69 | * @var string |
| 70 | */ |
| 71 | public $trxn_result_code; |
| 72 | |
| 73 | /** |
| 74 | * Class constructor. |
| 75 | */ |
| 76 | public function __construct() { |
| 77 | parent::__construct(); |
| 78 | } |
| 79 | |
| 80 | /** |
| 81 | * Takes an associative array and creates a contribution object. |
| 82 | * |
| 83 | * the function extract all the params it needs to initialize the create a |
| 84 | * contribution object. the params array could contain additional unused name/value |
| 85 | * pairs |
| 86 | * |
| 87 | * @param array $params |
| 88 | * (reference ) an assoc array of name/value pairs. |
| 89 | * |
| 90 | * @return \CRM_Contribute_BAO_Contribution |
| 91 | * @throws \CRM_Core_Exception |
| 92 | * @throws \CiviCRM_API3_Exception |
| 93 | */ |
| 94 | public static function add(&$params) { |
| 95 | if (empty($params)) { |
| 96 | return NULL; |
| 97 | } |
| 98 | |
| 99 | $contributionID = $params['id'] ?? NULL; |
| 100 | $action = $contributionID ? 'edit' : 'create'; |
| 101 | $duplicates = []; |
| 102 | if (self::checkDuplicate($params, $duplicates, $contributionID)) { |
| 103 | $message = ts("Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: %1", [1 => implode(', ', $duplicates)]); |
| 104 | throw new CRM_Core_Exception($message); |
| 105 | } |
| 106 | |
| 107 | //set defaults in create mode |
| 108 | if (!$contributionID) { |
| 109 | CRM_Core_DAO::setCreateDefaults($params, self::getDefaults()); |
| 110 | if (empty($params['invoice_number']) && CRM_Invoicing_Utils::isInvoicingEnabled()) { |
| 111 | $nextContributionID = CRM_Core_DAO::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution"); |
| 112 | $params['invoice_number'] = self::getInvoiceNumber($nextContributionID); |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | $contributionStatusID = $params['contribution_status_id'] ?? NULL; |
| 117 | if (CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $contributionStatusID) === 'Partially paid' && empty($params['is_post_payment_create'])) { |
| 118 | CRM_Core_Error::deprecatedFunctionWarning('Setting status to partially paid other than by using Payment.create is deprecated and unreliable'); |
| 119 | } |
| 120 | if (!$contributionStatusID) { |
| 121 | // Since the fee amount is expecting this (later on) ensure it is always set. |
| 122 | // It would only not be set for an update where it is unchanged. |
| 123 | $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [ |
| 124 | 'id' => $contributionID, |
| 125 | 'return' => 'contribution_status_id', |
| 126 | ]); |
| 127 | } |
| 128 | $contributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']); |
| 129 | |
| 130 | if (!$contributionID |
| 131 | && !empty($params['membership_id']) |
| 132 | && Civi::settings()->get('deferred_revenue_enabled') |
| 133 | ) { |
| 134 | $memberStartDate = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date'); |
| 135 | if ($memberStartDate) { |
| 136 | $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate)); |
| 137 | } |
| 138 | } |
| 139 | self::calculateMissingAmountParams($params, $contributionID); |
| 140 | |
| 141 | if (!empty($params['payment_instrument_id'])) { |
| 142 | $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name'); |
| 143 | if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) { |
| 144 | $params['check_number'] = 'null'; |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | $setPrevContribution = TRUE; |
| 149 | if ($contributionID && $setPrevContribution) { |
| 150 | $params['prevContribution'] = self::getOriginalContribution($contributionID); |
| 151 | } |
| 152 | $previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id) : NULL; |
| 153 | |
| 154 | if ($contributionID && !empty($params['revenue_recognition_date']) |
| 155 | && !($previousContributionStatus === 'Pending') |
| 156 | && !self::allowUpdateRevenueRecognitionDate($contributionID) |
| 157 | ) { |
| 158 | unset($params['revenue_recognition_date']); |
| 159 | } |
| 160 | |
| 161 | if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) || |
| 162 | isset($params['financial_type_id']))) { |
| 163 | $params = CRM_Contribute_BAO_Contribution::checkTaxAmount($params); |
| 164 | } |
| 165 | |
| 166 | CRM_Utils_Hook::pre($action, 'Contribution', $contributionID, $params); |
| 167 | |
| 168 | $contribution = new CRM_Contribute_BAO_Contribution(); |
| 169 | $contribution->copyValues($params); |
| 170 | |
| 171 | $contribution->id = $contributionID; |
| 172 | |
| 173 | if (empty($contribution->id)) { |
| 174 | // (only) on 'create', make sure that a valid currency is set (CRM-16845) |
| 175 | if (!CRM_Utils_Rule::currencyCode($contribution->currency)) { |
| 176 | $contribution->currency = CRM_Core_Config::singleton()->defaultCurrency; |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | $result = $contribution->save(); |
| 181 | |
| 182 | // Add financial_trxn details as part of fix for CRM-4724 |
| 183 | $contribution->trxn_result_code = $params['trxn_result_code'] ?? NULL; |
| 184 | $contribution->payment_processor = $params['payment_processor'] ?? NULL; |
| 185 | |
| 186 | //add Account details |
| 187 | $params['contribution'] = $contribution; |
| 188 | if (empty($params['is_post_payment_create'])) { |
| 189 | // If this is being called from the Payment.create api/ BAO then that Entity |
| 190 | // takes responsibility for the financial transactions. In fact calling Payment.create |
| 191 | // to add payments & having it call completetransaction and / or contribution.create |
| 192 | // to update related entities is the preferred flow. |
| 193 | // Note that leveraging this parameter for any other code flow is not supported and |
| 194 | // is likely to break in future and / or cause serious problems in your data. |
| 195 | // https://github.com/civicrm/civicrm-core/pull/14673 |
| 196 | self::recordFinancialAccounts($params); |
| 197 | } |
| 198 | |
| 199 | if (self::isUpdateToRecurringContribution($params)) { |
| 200 | CRM_Contribute_BAO_ContributionRecur::updateOnNewPayment( |
| 201 | (!empty($params['contribution_recur_id']) ? $params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id), |
| 202 | $contributionStatus, |
| 203 | $params['receive_date'] ?? NULL |
| 204 | ); |
| 205 | } |
| 206 | |
| 207 | $params['contribution_id'] = $contribution->id; |
| 208 | |
| 209 | if (!empty($params['custom']) && |
| 210 | is_array($params['custom']) |
| 211 | ) { |
| 212 | CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id, $action); |
| 213 | } |
| 214 | |
| 215 | CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush(); |
| 216 | |
| 217 | CRM_Utils_Hook::post($action, 'Contribution', $contribution->id, $contribution); |
| 218 | return $result; |
| 219 | } |
| 220 | |
| 221 | /** |
| 222 | * Is this contribution updating an existing recurring contribution. |
| 223 | * |
| 224 | * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial |
| 225 | * pending payment is being confirmed (or failing). |
| 226 | * |
| 227 | * @param array $params |
| 228 | * |
| 229 | * @return bool |
| 230 | */ |
| 231 | public static function isUpdateToRecurringContribution($params) { |
| 232 | if (!empty($params['contribution_recur_id']) && empty($params['id'])) { |
| 233 | return TRUE; |
| 234 | } |
| 235 | if (empty($params['prevContribution']) || empty($params['contribution_status_id'])) { |
| 236 | return FALSE; |
| 237 | } |
| 238 | if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id)) { |
| 239 | return FALSE; |
| 240 | } |
| 241 | $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
| 242 | if ($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)) { |
| 243 | return TRUE; |
| 244 | } |
| 245 | return FALSE; |
| 246 | } |
| 247 | |
| 248 | /** |
| 249 | * Get defaults for new entity. |
| 250 | * |
| 251 | * @return array |
| 252 | */ |
| 253 | public static function getDefaults() { |
| 254 | return [ |
| 255 | 'payment_instrument_id' => key(CRM_Core_OptionGroup::values('payment_instrument', |
| 256 | FALSE, FALSE, FALSE, 'AND is_default = 1') |
| 257 | ), |
| 258 | 'contribution_status_id' => CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'), |
| 259 | 'receive_date' => date('Y-m-d H:i:s'), |
| 260 | ]; |
| 261 | } |
| 262 | |
| 263 | /** |
| 264 | * Fetch the object and store the values in the values array. |
| 265 | * |
| 266 | * @param array $params |
| 267 | * Input parameters to find object. |
| 268 | * @param array $values |
| 269 | * Output values of the object. |
| 270 | * @param array $ids |
| 271 | * The array that holds all the db ids. |
| 272 | * |
| 273 | * @return CRM_Contribute_BAO_Contribution|null |
| 274 | * The found object or null |
| 275 | */ |
| 276 | public static function getValues($params, &$values = [], &$ids = []) { |
| 277 | if (empty($params)) { |
| 278 | return NULL; |
| 279 | } |
| 280 | $contribution = new CRM_Contribute_BAO_Contribution(); |
| 281 | |
| 282 | $contribution->copyValues($params); |
| 283 | |
| 284 | if ($contribution->find(TRUE)) { |
| 285 | $ids['contribution'] = $contribution->id; |
| 286 | |
| 287 | CRM_Core_DAO::storeValues($contribution, $values); |
| 288 | |
| 289 | return $contribution; |
| 290 | } |
| 291 | // return by reference |
| 292 | $null = NULL; |
| 293 | return $null; |
| 294 | } |
| 295 | |
| 296 | /** |
| 297 | * Get the values and resolve the most common mappings. |
| 298 | * |
| 299 | * Since contribution status is resolved in almost every function that calls getValues it makes |
| 300 | * sense to have an extra function to resolve it rather than repeat the code. |
| 301 | * |
| 302 | * Think carefully before adding more mappings to be resolved as there could be performance implications |
| 303 | * if this function starts to be called from more iterative functions. |
| 304 | * |
| 305 | * @param array $params |
| 306 | * Input parameters to find object. |
| 307 | * |
| 308 | * @return array |
| 309 | * Array of the found contribution. |
| 310 | * @throws CRM_Core_Exception |
| 311 | */ |
| 312 | public static function getValuesWithMappings($params) { |
| 313 | $values = $ids = []; |
| 314 | $contribution = self::getValues($params, $values, $ids); |
| 315 | if (is_null($contribution)) { |
| 316 | throw new CRM_Core_Exception('No contribution found'); |
| 317 | } |
| 318 | $values['contribution_status'] = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']); |
| 319 | return $values; |
| 320 | } |
| 321 | |
| 322 | /** |
| 323 | * Calculate net_amount & fee_amount if they are not set. |
| 324 | * |
| 325 | * Net amount should be total - fee. |
| 326 | * This should only be called for new contributions. |
| 327 | * |
| 328 | * @param array $params |
| 329 | * Params for a new contribution before they are saved. |
| 330 | * @param int|null $contributionID |
| 331 | * Contribution ID if we are dealing with an update. |
| 332 | * |
| 333 | * @throws \CiviCRM_API3_Exception |
| 334 | */ |
| 335 | public static function calculateMissingAmountParams(&$params, $contributionID) { |
| 336 | if (!$contributionID && !isset($params['fee_amount'])) { |
| 337 | if (isset($params['total_amount']) && isset($params['net_amount'])) { |
| 338 | $params['fee_amount'] = $params['total_amount'] - $params['net_amount']; |
| 339 | } |
| 340 | else { |
| 341 | $params['fee_amount'] = 0; |
| 342 | } |
| 343 | } |
| 344 | if (!isset($params['net_amount'])) { |
| 345 | if (!$contributionID) { |
| 346 | $params['net_amount'] = $params['total_amount'] - $params['fee_amount']; |
| 347 | } |
| 348 | else { |
| 349 | if (isset($params['fee_amount']) || isset($params['total_amount'])) { |
| 350 | // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount. |
| 351 | // net_amount may need adjusting. |
| 352 | $contribution = civicrm_api3('Contribution', 'getsingle', [ |
| 353 | 'id' => $contributionID, |
| 354 | 'return' => ['total_amount', 'net_amount', 'fee_amount'], |
| 355 | ]); |
| 356 | $totalAmount = (isset($params['total_amount']) ? (float) $params['total_amount'] : (float) CRM_Utils_Array::value('total_amount', $contribution)); |
| 357 | $feeAmount = (isset($params['fee_amount']) ? (float) $params['fee_amount'] : (float) CRM_Utils_Array::value('fee_amount', $contribution)); |
| 358 | $params['net_amount'] = $totalAmount - $feeAmount; |
| 359 | } |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | /** |
| 365 | * @param $params |
| 366 | * @param $billingLocationTypeID |
| 367 | * |
| 368 | * @return array |
| 369 | */ |
| 370 | protected static function getBillingAddressParams($params, $billingLocationTypeID) { |
| 371 | $hasBillingField = FALSE; |
| 372 | $billingFields = [ |
| 373 | 'street_address', |
| 374 | 'city', |
| 375 | 'state_province_id', |
| 376 | 'postal_code', |
| 377 | 'country_id', |
| 378 | ]; |
| 379 | |
| 380 | //build address array |
| 381 | $addressParams = []; |
| 382 | $addressParams['location_type_id'] = $billingLocationTypeID; |
| 383 | $addressParams['is_billing'] = 1; |
| 384 | |
| 385 | $billingFirstName = $params['billing_first_name'] ?? NULL; |
| 386 | $billingMiddleName = $params['billing_middle_name'] ?? NULL; |
| 387 | $billingLastName = $params['billing_last_name'] ?? NULL; |
| 388 | $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingMiddleName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingLastName}"; |
| 389 | |
| 390 | foreach ($billingFields as $value) { |
| 391 | $addressParams[$value] = $params["billing_{$value}-{$billingLocationTypeID}"] ?? NULL; |
| 392 | if (!empty($addressParams[$value])) { |
| 393 | $hasBillingField = TRUE; |
| 394 | } |
| 395 | } |
| 396 | return [$hasBillingField, $addressParams]; |
| 397 | } |
| 398 | |
| 399 | /** |
| 400 | * Get address params ready to be passed to the payment processor. |
| 401 | * |
| 402 | * We need address params in a couple of formats. For the payment processor we wan state_province_id-5. |
| 403 | * To create an address we need state_province_id. |
| 404 | * |
| 405 | * @param array $params |
| 406 | * @param int $billingLocationTypeID |
| 407 | * |
| 408 | * @return array |
| 409 | */ |
| 410 | public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) { |
| 411 | list($hasBillingField, $addressParams) = self::getBillingAddressParams($params, $billingLocationTypeID); |
| 412 | foreach ($addressParams as $name => $field) { |
| 413 | if (substr($name, 0, 8) == 'billing_') { |
| 414 | $addressParams[substr($name, 9)] = $addressParams[$field]; |
| 415 | } |
| 416 | } |
| 417 | return [$hasBillingField, $addressParams]; |
| 418 | } |
| 419 | |
| 420 | /** |
| 421 | * Get the number of terms for this contribution for a given membership type |
| 422 | * based on querying the line item table and relevant price field values |
| 423 | * Note that any one contribution should only be able to have one line item relating to a particular membership |
| 424 | * type |
| 425 | * |
| 426 | * @param int $membershipTypeID |
| 427 | * |
| 428 | * @param int $contributionID |
| 429 | * |
| 430 | * @return int |
| 431 | */ |
| 432 | public static function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) { |
| 433 | $numTerms = CRM_Core_DAO::singleValueQuery(" |
| 434 | SELECT membership_num_terms FROM civicrm_line_item li |
| 435 | LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id |
| 436 | WHERE contribution_id = %1 AND membership_type_id = %2", |
| 437 | [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']] |
| 438 | ); |
| 439 | // default of 1 is precautionary |
| 440 | return empty($numTerms) ? 1 : $numTerms; |
| 441 | } |
| 442 | |
| 443 | /** |
| 444 | * Takes an associative array and creates a contribution object. |
| 445 | * |
| 446 | * @param array $params |
| 447 | * (reference ) an assoc array of name/value pairs. |
| 448 | * @param array $ids |
| 449 | * The array that holds all the db ids. |
| 450 | * |
| 451 | * @return CRM_Contribute_BAO_Contribution |
| 452 | * |
| 453 | * @throws \API_Exception |
| 454 | * @throws \CRM_Core_Exception |
| 455 | * @throws \CiviCRM_API3_Exception |
| 456 | */ |
| 457 | public static function create(&$params, $ids = []) { |
| 458 | |
| 459 | $transaction = new CRM_Core_Transaction(); |
| 460 | |
| 461 | try { |
| 462 | if (!isset($params['id']) && isset($ids['contribution'])) { |
| 463 | CRM_Core_Error::deprecatedFunctionWarning('ids should not be used for contribution create'); |
| 464 | $params['id'] = $ids['contribution']; |
| 465 | } |
| 466 | $contribution = self::add($params); |
| 467 | } |
| 468 | catch (CRM_Core_Exception $e) { |
| 469 | $transaction->rollback(); |
| 470 | throw $e; |
| 471 | } |
| 472 | |
| 473 | $params['contribution_id'] = $contribution->id; |
| 474 | $session = CRM_Core_Session::singleton(); |
| 475 | |
| 476 | if (!empty($params['note'])) { |
| 477 | $noteParams = [ |
| 478 | 'entity_table' => 'civicrm_contribution', |
| 479 | 'note' => $params['note'], |
| 480 | 'entity_id' => $contribution->id, |
| 481 | 'contact_id' => $session->get('userID'), |
| 482 | ]; |
| 483 | if (!$noteParams['contact_id']) { |
| 484 | $noteParams['contact_id'] = $params['contact_id']; |
| 485 | } |
| 486 | CRM_Core_BAO_Note::add($noteParams); |
| 487 | } |
| 488 | |
| 489 | CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution); |
| 490 | |
| 491 | $transaction->commit(); |
| 492 | |
| 493 | if (empty($contribution->contact_id)) { |
| 494 | $contribution->find(TRUE); |
| 495 | } |
| 496 | |
| 497 | $isCompleted = ('Completed' === CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id)); |
| 498 | if (!empty($params['on_behalf']) |
| 499 | || $isCompleted |
| 500 | ) { |
| 501 | $existingActivity = Activity::get(FALSE)->setWhere([ |
| 502 | ['source_record_id', '=', $contribution->id], |
| 503 | ['activity_type_id:name', '=', 'Contribution'], |
| 504 | ])->execute()->first(); |
| 505 | |
| 506 | $campaignParams = isset($params['campaign_id']) ? ['campaign_id' => ($params['campaign_id'] ?? NULL)] : []; |
| 507 | Activity::save(FALSE)->addRecord(array_merge([ |
| 508 | 'activity_type_id:name' => 'Contribution', |
| 509 | 'source_record_id' => $contribution->id, |
| 510 | 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ?: $contribution->contact_id, |
| 511 | 'target_contact_id' => CRM_Core_Session::getLoggedInContactID() ? [$contribution->contact_id] : [], |
| 512 | 'activity_date_time' => $contribution->receive_date, |
| 513 | 'is_test' => (bool) $contribution->is_test, |
| 514 | 'status_id:name' => $isCompleted ? 'Completed' : 'Scheduled', |
| 515 | 'skipRecentView' => TRUE, |
| 516 | 'subject' => CRM_Activity_BAO_Activity::getActivitySubject($contribution), |
| 517 | 'id' => $existingActivity['id'] ?? NULL, |
| 518 | ], $campaignParams))->execute(); |
| 519 | } |
| 520 | |
| 521 | // do not add to recent items for import, CRM-4399 |
| 522 | if (empty($params['skipRecentView'])) { |
| 523 | $url = CRM_Utils_System::url('civicrm/contact/view/contribution', |
| 524 | "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home" |
| 525 | ); |
| 526 | // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params |
| 527 | $titleFields = [ |
| 528 | 'contact_id', |
| 529 | 'total_amount', |
| 530 | 'currency', |
| 531 | 'financial_type_id', |
| 532 | ]; |
| 533 | $retrieveRequired = 0; |
| 534 | foreach ($titleFields as $titleField) { |
| 535 | if (!isset($contribution->$titleField)) { |
| 536 | $retrieveRequired = 1; |
| 537 | break; |
| 538 | } |
| 539 | } |
| 540 | if ($retrieveRequired == 1) { |
| 541 | $contribution->find(TRUE); |
| 542 | } |
| 543 | $financialType = CRM_Contribute_PseudoConstant::financialType($contribution->financial_type_id); |
| 544 | $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $financialType . ')'; |
| 545 | |
| 546 | $recentOther = []; |
| 547 | if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) { |
| 548 | $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', |
| 549 | "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home" |
| 550 | ); |
| 551 | } |
| 552 | |
| 553 | if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) { |
| 554 | $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', |
| 555 | "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home" |
| 556 | ); |
| 557 | } |
| 558 | |
| 559 | // add the recently created Contribution |
| 560 | CRM_Utils_Recent::add($title, |
| 561 | $url, |
| 562 | $contribution->id, |
| 563 | 'Contribution', |
| 564 | $contribution->contact_id, |
| 565 | NULL, |
| 566 | $recentOther |
| 567 | ); |
| 568 | } |
| 569 | |
| 570 | return $contribution; |
| 571 | } |
| 572 | |
| 573 | /** |
| 574 | * Get the values for pseudoconstants for name->value and reverse. |
| 575 | * |
| 576 | * @param array $defaults |
| 577 | * (reference) the default values, some of which need to be resolved. |
| 578 | * @param bool $reverse |
| 579 | * True if we want to resolve the values in the reverse direction (value -> name). |
| 580 | */ |
| 581 | public static function resolveDefaults(&$defaults, $reverse = FALSE) { |
| 582 | self::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant::financialType(), $reverse); |
| 583 | self::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant::paymentInstrument(), $reverse); |
| 584 | self::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'label'), $reverse); |
| 585 | self::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant::pcPage(), $reverse); |
| 586 | } |
| 587 | |
| 588 | /** |
| 589 | * Convert associative array names to values and vice-versa. |
| 590 | * |
| 591 | * This function is used by both the web form layer and the api. Note that |
| 592 | * the api needs the name => value conversion, also the view layer typically |
| 593 | * requires value => name conversion |
| 594 | * |
| 595 | * @param array $defaults |
| 596 | * @param string $property |
| 597 | * @param array $lookup |
| 598 | * @param bool $reverse |
| 599 | * |
| 600 | * @return bool |
| 601 | */ |
| 602 | public static function lookupValue(&$defaults, $property, &$lookup, $reverse) { |
| 603 | $id = $property . '_id'; |
| 604 | |
| 605 | $src = $reverse ? $property : $id; |
| 606 | $dst = $reverse ? $id : $property; |
| 607 | |
| 608 | if (!array_key_exists($src, $defaults)) { |
| 609 | return FALSE; |
| 610 | } |
| 611 | |
| 612 | $look = $reverse ? array_flip($lookup) : $lookup; |
| 613 | |
| 614 | if (is_array($look)) { |
| 615 | if (!array_key_exists($defaults[$src], $look)) { |
| 616 | return FALSE; |
| 617 | } |
| 618 | } |
| 619 | $defaults[$dst] = $look[$defaults[$src]]; |
| 620 | return TRUE; |
| 621 | } |
| 622 | |
| 623 | /** |
| 624 | * Retrieve DB object based on input parameters. |
| 625 | * |
| 626 | * It also stores all the retrieved values in the default array. |
| 627 | * |
| 628 | * @param array $params |
| 629 | * (reference ) an assoc array of name/value pairs. |
| 630 | * @param array $defaults |
| 631 | * (reference ) an assoc array to hold the name / value pairs. |
| 632 | * in a hierarchical manner |
| 633 | * @param array $ids |
| 634 | * (reference) the array that holds all the db ids. |
| 635 | * |
| 636 | * @return CRM_Contribute_BAO_Contribution |
| 637 | */ |
| 638 | public static function retrieve(&$params, &$defaults = [], &$ids = []) { |
| 639 | $contribution = CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids); |
| 640 | return $contribution; |
| 641 | } |
| 642 | |
| 643 | /** |
| 644 | * Combine all the importable fields from the lower levels object. |
| 645 | * |
| 646 | * The ordering is important, since currently we do not have a weight |
| 647 | * scheme. Adding weight is super important and should be done in the |
| 648 | * next week or so, before this can be called complete. |
| 649 | * |
| 650 | * @param string $contactType |
| 651 | * @param bool $status |
| 652 | * |
| 653 | * @return array |
| 654 | * array of importable Fields |
| 655 | */ |
| 656 | public static function &importableFields($contactType = 'Individual', $status = TRUE) { |
| 657 | if (!self::$_importableFields) { |
| 658 | if (!self::$_importableFields) { |
| 659 | self::$_importableFields = []; |
| 660 | } |
| 661 | |
| 662 | if (!$status) { |
| 663 | $fields = ['' => ['title' => ts('- do not import -')]]; |
| 664 | } |
| 665 | else { |
| 666 | $fields = ['' => ['title' => ts('- Contribution Fields -')]]; |
| 667 | } |
| 668 | |
| 669 | $note = CRM_Core_DAO_Note::import(); |
| 670 | $tmpFields = CRM_Contribute_DAO_Contribution::import(); |
| 671 | unset($tmpFields['option_value']); |
| 672 | $optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute'); |
| 673 | $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL); |
| 674 | |
| 675 | // Using new Dedupe rule. |
| 676 | $ruleParams = [ |
| 677 | 'contact_type' => $contactType, |
| 678 | 'used' => 'Unsupervised', |
| 679 | ]; |
| 680 | $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams); |
| 681 | $tmpContactField = []; |
| 682 | if (is_array($fieldsArray)) { |
| 683 | foreach ($fieldsArray as $value) { |
| 684 | //skip if there is no dupe rule |
| 685 | if ($value == 'none') { |
| 686 | continue; |
| 687 | } |
| 688 | $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', |
| 689 | $value, |
| 690 | 'id', |
| 691 | 'column_name' |
| 692 | ); |
| 693 | $value = $customFieldId ? 'custom_' . $customFieldId : $value; |
| 694 | $tmpContactField[trim($value)] = $contactFields[trim($value)]; |
| 695 | if (!$status) { |
| 696 | $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)'); |
| 697 | } |
| 698 | else { |
| 699 | $title = $tmpContactField[trim($value)]['title']; |
| 700 | } |
| 701 | $tmpContactField[trim($value)]['title'] = $title; |
| 702 | } |
| 703 | } |
| 704 | |
| 705 | $tmpContactField['external_identifier'] = $contactFields['external_identifier']; |
| 706 | $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)'); |
| 707 | $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)'); |
| 708 | $fields = array_merge($fields, $tmpContactField); |
| 709 | $fields = array_merge($fields, $tmpFields); |
| 710 | $fields = array_merge($fields, $note); |
| 711 | $fields = array_merge($fields, $optionFields); |
| 712 | $fields = array_merge($fields, CRM_Financial_DAO_FinancialType::export()); |
| 713 | $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution')); |
| 714 | self::$_importableFields = $fields; |
| 715 | } |
| 716 | return self::$_importableFields; |
| 717 | } |
| 718 | |
| 719 | /** |
| 720 | * Combine all the exportable fields from the lower level objects. |
| 721 | * |
| 722 | * @param bool $checkPermission |
| 723 | * |
| 724 | * @return array |
| 725 | * array of exportable Fields |
| 726 | */ |
| 727 | public static function &exportableFields($checkPermission = TRUE) { |
| 728 | if (!self::$_exportableFields) { |
| 729 | if (!self::$_exportableFields) { |
| 730 | self::$_exportableFields = []; |
| 731 | } |
| 732 | |
| 733 | $fields = CRM_Contribute_DAO_Contribution::export(); |
| 734 | if (CRM_Contribute_BAO_Query::isSiteHasProducts()) { |
| 735 | $fields = array_merge( |
| 736 | $fields, |
| 737 | CRM_Contribute_DAO_Product::export(), |
| 738 | CRM_Contribute_DAO_ContributionProduct::export(), |
| 739 | // CRM-16713 - contribution search by Premiums on 'Find Contribution' form. |
| 740 | [ |
| 741 | 'contribution_product_id' => [ |
| 742 | 'title' => ts('Premium'), |
| 743 | 'name' => 'contribution_product_id', |
| 744 | 'where' => 'civicrm_product.id', |
| 745 | 'data_type' => CRM_Utils_Type::T_INT, |
| 746 | ], |
| 747 | ] |
| 748 | ); |
| 749 | } |
| 750 | |
| 751 | $financialAccount = CRM_Financial_DAO_FinancialAccount::export(); |
| 752 | |
| 753 | $contributionPage = [ |
| 754 | 'contribution_page' => [ |
| 755 | 'title' => ts('Contribution Page'), |
| 756 | 'name' => 'contribution_page', |
| 757 | 'where' => 'civicrm_contribution_page.title', |
| 758 | 'data_type' => CRM_Utils_Type::T_STRING, |
| 759 | ], |
| 760 | ]; |
| 761 | |
| 762 | $contributionNote = [ |
| 763 | 'contribution_note' => [ |
| 764 | 'title' => ts('Contribution Note'), |
| 765 | 'name' => 'contribution_note', |
| 766 | 'data_type' => CRM_Utils_Type::T_TEXT, |
| 767 | ], |
| 768 | ]; |
| 769 | |
| 770 | $extraFields = [ |
| 771 | 'contribution_batch' => [ |
| 772 | 'title' => ts('Batch Name'), |
| 773 | ], |
| 774 | ]; |
| 775 | |
| 776 | // CRM-17787 |
| 777 | $campaignTitle = [ |
| 778 | 'contribution_campaign_title' => [ |
| 779 | 'title' => ts('Campaign Title'), |
| 780 | 'name' => 'campaign_title', |
| 781 | 'where' => 'civicrm_campaign.title', |
| 782 | 'data_type' => CRM_Utils_Type::T_STRING, |
| 783 | ], |
| 784 | ]; |
| 785 | $softCreditFields = [ |
| 786 | 'contribution_soft_credit_name' => [ |
| 787 | 'name' => 'contribution_soft_credit_name', |
| 788 | 'title' => ts('Soft Credit For'), |
| 789 | 'where' => 'civicrm_contact_d.display_name', |
| 790 | 'data_type' => CRM_Utils_Type::T_STRING, |
| 791 | ], |
| 792 | 'contribution_soft_credit_amount' => [ |
| 793 | 'name' => 'contribution_soft_credit_amount', |
| 794 | 'title' => ts('Soft Credit Amount'), |
| 795 | 'where' => 'civicrm_contribution_soft.amount', |
| 796 | 'data_type' => CRM_Utils_Type::T_MONEY, |
| 797 | ], |
| 798 | 'contribution_soft_credit_type' => [ |
| 799 | 'name' => 'contribution_soft_credit_type', |
| 800 | 'title' => ts('Soft Credit Type'), |
| 801 | 'where' => 'contribution_softcredit_type.label', |
| 802 | 'data_type' => CRM_Utils_Type::T_STRING, |
| 803 | ], |
| 804 | 'contribution_soft_credit_contribution_id' => [ |
| 805 | 'name' => 'contribution_soft_credit_contribution_id', |
| 806 | 'title' => ts('Soft Credit For Contribution ID'), |
| 807 | 'where' => 'civicrm_contribution_soft.contribution_id', |
| 808 | 'data_type' => CRM_Utils_Type::T_INT, |
| 809 | ], |
| 810 | 'contribution_soft_credit_contact_id' => [ |
| 811 | 'name' => 'contribution_soft_credit_contact_id', |
| 812 | 'title' => ts('Soft Credit For Contact ID'), |
| 813 | 'where' => 'civicrm_contact_d.id', |
| 814 | 'data_type' => CRM_Utils_Type::T_INT, |
| 815 | ], |
| 816 | ]; |
| 817 | |
| 818 | $fields = array_merge($fields, $contributionPage, |
| 819 | $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle, |
| 820 | CRM_Core_BAO_CustomField::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission) |
| 821 | ); |
| 822 | |
| 823 | self::$_exportableFields = $fields; |
| 824 | } |
| 825 | |
| 826 | return self::$_exportableFields; |
| 827 | } |
| 828 | |
| 829 | /** |
| 830 | * Record an activity when a payment is received. |
| 831 | * |
| 832 | * @todo this is intended to be moved to payment BAO class as a protected function |
| 833 | * on that class. Currently being cleaned up. The addActivityForPayment doesn't really |
| 834 | * merit it's own function as it makes the code less rather than more readable. |
| 835 | * |
| 836 | * @param int $contributionId |
| 837 | * @param int $participantId |
| 838 | * @param string $totalAmount |
| 839 | * @param string $currency |
| 840 | * @param string $trxnDate |
| 841 | * |
| 842 | * @throws \CRM_Core_Exception |
| 843 | * @throws \CiviCRM_API3_Exception |
| 844 | */ |
| 845 | public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) { |
| 846 | $activityType = ($totalAmount < 0) ? 'Refund' : 'Payment'; |
| 847 | |
| 848 | if ($participantId) { |
| 849 | $inputParams['id'] = $participantId; |
| 850 | $values = []; |
| 851 | $ids = []; |
| 852 | $entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids); |
| 853 | $entityObj = $entityObj[$participantId]; |
| 854 | $title = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id, 'title'); |
| 855 | } |
| 856 | else { |
| 857 | $entityObj = new CRM_Contribute_BAO_Contribution(); |
| 858 | $entityObj->id = $contributionId; |
| 859 | $entityObj->find(TRUE); |
| 860 | $title = ts('Contribution'); |
| 861 | } |
| 862 | // @todo per block above this is not a logical splitting off of functionality. |
| 863 | self::addActivityForPayment($entityObj->contact_id, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate); |
| 864 | } |
| 865 | |
| 866 | /** |
| 867 | * Get the value for the To Financial Account. |
| 868 | * |
| 869 | * @param $contribution |
| 870 | * @param $params |
| 871 | * |
| 872 | * @return int |
| 873 | */ |
| 874 | public static function getToFinancialAccount($contribution, $params) { |
| 875 | if (!empty($params['payment_processor_id'])) { |
| 876 | return CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor'); |
| 877 | } |
| 878 | if (!empty($params['payment_instrument_id'])) { |
| 879 | return CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contribution['payment_instrument_id']); |
| 880 | } |
| 881 | else { |
| 882 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' ")); |
| 883 | $queryParams = [1 => [$relationTypeId, 'Integer']]; |
| 884 | return CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams); |
| 885 | } |
| 886 | } |
| 887 | |
| 888 | /** |
| 889 | * Get memberships related to the contribution. |
| 890 | * |
| 891 | * @param int $contributionID |
| 892 | * |
| 893 | * @return array |
| 894 | */ |
| 895 | protected static function getRelatedMemberships($contributionID) { |
| 896 | $membershipPayments = civicrm_api3('MembershipPayment', 'get', [ |
| 897 | 'return' => 'membership_id', |
| 898 | 'contribution_id' => (int) $contributionID, |
| 899 | ])['values']; |
| 900 | $membershipIDs = []; |
| 901 | foreach ($membershipPayments as $membershipPayment) { |
| 902 | $membershipIDs[] = $membershipPayment['membership_id']; |
| 903 | } |
| 904 | if (empty($membershipIDs)) { |
| 905 | return []; |
| 906 | } |
| 907 | // We could combine this with the MembershipPayment.get - we'd |
| 908 | // need to re-wrangle the params (here or in the calling function) |
| 909 | // as they would then me membership.contact_id, membership.is_test etc |
| 910 | return civicrm_api3('Membership', 'get', [ |
| 911 | 'id' => ['IN' => $membershipIDs], |
| 912 | 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'], |
| 913 | ])['values']; |
| 914 | } |
| 915 | |
| 916 | /** |
| 917 | * Cancel contribution. |
| 918 | * |
| 919 | * This function should only be called from transitioncomponents - it is an interim step in refactoring. |
| 920 | * |
| 921 | * @param $processContributionObject |
| 922 | * @param $memberships |
| 923 | * @param $contributionId |
| 924 | * @param $membershipStatuses |
| 925 | * @param $updateResult |
| 926 | * @param $participant |
| 927 | * @param $oldStatus |
| 928 | * @param $pledgePayment |
| 929 | * @param $pledgeID |
| 930 | * @param $pledgePaymentIDs |
| 931 | * @param $contributionStatusId |
| 932 | * |
| 933 | * @return array |
| 934 | */ |
| 935 | protected static function cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId) { |
| 936 | // @fixme https://lab.civicrm.org/dev/core/issues/927 Cancelling membership etc is not desirable for all use-cases and we should be able to disable it |
| 937 | $processContribution = FALSE; |
| 938 | $participantStatuses = CRM_Event_PseudoConstant::participantStatus(); |
| 939 | if (is_array($memberships)) { |
| 940 | foreach ($memberships as $membership) { |
| 941 | $update = TRUE; |
| 942 | //Update Membership status if there is no other completed contribution associated with the membership. |
| 943 | $relatedContributions = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id, TRUE); |
| 944 | foreach ($relatedContributions as $contriId) { |
| 945 | if ($contriId == $contributionId) { |
| 946 | continue; |
| 947 | } |
| 948 | $statusId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id'); |
| 949 | if (CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') { |
| 950 | $update = FALSE; |
| 951 | } |
| 952 | } |
| 953 | if ($membership && $update) { |
| 954 | $newStatus = array_search('Cancelled', $membershipStatuses); |
| 955 | |
| 956 | // Create activity |
| 957 | $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'get'); |
| 958 | $activityParam = [ |
| 959 | 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}", |
| 960 | 'source_contact_id' => CRM_Core_Session::singleton()->get('userID'), |
| 961 | 'target_contact_id' => $membership->contact_id, |
| 962 | 'source_record_id' => $membership->id, |
| 963 | 'activity_type_id' => 'Change Membership Status', |
| 964 | 'status_id' => 'Completed', |
| 965 | 'priority_id' => 'Normal', |
| 966 | 'activity_date_time' => 'now', |
| 967 | ]; |
| 968 | |
| 969 | $membership->status_id = $newStatus; |
| 970 | $membership->is_override = TRUE; |
| 971 | $membership->status_override_end_date = 'null'; |
| 972 | $membership->save(); |
| 973 | civicrm_api3('activity', 'create', $activityParam); |
| 974 | |
| 975 | $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; |
| 976 | if ($processContributionObject) { |
| 977 | $processContribution = TRUE; |
| 978 | } |
| 979 | } |
| 980 | } |
| 981 | } |
| 982 | |
| 983 | if ($participant) { |
| 984 | $updatedStatusId = array_search('Cancelled', $participantStatuses); |
| 985 | CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE); |
| 986 | |
| 987 | $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; |
| 988 | if ($processContributionObject) { |
| 989 | $processContribution = TRUE; |
| 990 | } |
| 991 | } |
| 992 | |
| 993 | if ($pledgePayment) { |
| 994 | CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); |
| 995 | |
| 996 | $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; |
| 997 | if ($processContributionObject) { |
| 998 | $processContribution = TRUE; |
| 999 | } |
| 1000 | } |
| 1001 | return [$updateResult, $processContribution]; |
| 1002 | } |
| 1003 | |
| 1004 | /** |
| 1005 | * Do any accounting updates required as a result of a contribution status change. |
| 1006 | * |
| 1007 | * Currently we have a bit of a roundabout where adding a payment results in this being called & |
| 1008 | * this may attempt to add a payment. We need to resolve that.... |
| 1009 | * |
| 1010 | * The 'right' way to add payments or refunds is through the Payment.create api. That api |
| 1011 | * then updates the contribution but this process should not also record another financial trxn. |
| 1012 | * Currently we have weak detection fot that scenario & where it is detected the first returned |
| 1013 | * value is FALSE - meaning 'do not continue'. |
| 1014 | * |
| 1015 | * We should also look at the fact that the calling function - updateFinancialAccounts |
| 1016 | * bunches together some disparate processes rather than having separate appropriate |
| 1017 | * functions. |
| 1018 | * |
| 1019 | * @param array $params |
| 1020 | * |
| 1021 | * @return bool |
| 1022 | * Return indicates whether the updateFinancialAccounts function should continue. |
| 1023 | */ |
| 1024 | private static function updateFinancialAccountsOnContributionStatusChange(&$params) { |
| 1025 | $previousContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($params['prevContribution']->contribution_status_id, 'name'); |
| 1026 | $currentContributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id); |
| 1027 | |
| 1028 | if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed') |
| 1029 | || ($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed') |
| 1030 | // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear |
| 1031 | // why it is here or where it is handled instead. |
| 1032 | || ($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later == TRUE |
| 1033 | && $currentContributionStatus == 'Partially paid')) |
| 1034 | ) { |
| 1035 | return FALSE; |
| 1036 | } |
| 1037 | |
| 1038 | if (self::isContributionUpdateARefund($params['prevContribution']->contribution_status_id, $params['contribution']->contribution_status_id)) { |
| 1039 | // @todo we should stop passing $params by reference - splitting this out would be a step towards that. |
| 1040 | $params['trxnParams']['total_amount'] = -$params['total_amount']; |
| 1041 | } |
| 1042 | elseif (($previousContributionStatus == 'Pending' |
| 1043 | && $params['prevContribution']->is_pay_later) || $previousContributionStatus == 'In Progress' |
| 1044 | ) { |
| 1045 | $financialTypeID = !empty($params['financial_type_id']) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id; |
| 1046 | $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is'); |
| 1047 | |
| 1048 | if ($currentContributionStatus == 'Cancelled') { |
| 1049 | // @todo we should stop passing $params by reference - splitting this out would be a step towards that. |
| 1050 | $params['trxnParams']['to_financial_account_id'] = $arAccountId; |
| 1051 | $params['trxnParams']['total_amount'] = -$params['total_amount']; |
| 1052 | } |
| 1053 | else { |
| 1054 | // @todo we should stop passing $params by reference - splitting this out would be a step towards that. |
| 1055 | $params['trxnParams']['from_financial_account_id'] = $arAccountId; |
| 1056 | } |
| 1057 | } |
| 1058 | |
| 1059 | if (($previousContributionStatus == 'Pending' |
| 1060 | || $previousContributionStatus == 'In Progress') |
| 1061 | && ($currentContributionStatus == 'Completed') |
| 1062 | ) { |
| 1063 | if (empty($params['line_item'])) { |
| 1064 | //CRM-15296 |
| 1065 | //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items |
| 1066 | // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed |
| 1067 | // & this can be removed |
| 1068 | return FALSE; |
| 1069 | } |
| 1070 | // @todo we should stop passing $params by reference - splitting this out would be a step towards that. |
| 1071 | // This is an update so original currency if none passed in. |
| 1072 | $params['trxnParams']['currency'] = CRM_Utils_Array::value('currency', $params, $params['prevContribution']->currency); |
| 1073 | |
| 1074 | self::recordAlwaysAccountsReceivable($params['trxnParams'], $params); |
| 1075 | $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']); |
| 1076 | // @todo we should stop passing $params by reference - splitting this out would be a step towards that. |
| 1077 | $params['entity_id'] = self::$_trxnIDs[] = $trxn->id; |
| 1078 | |
| 1079 | $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'"; |
| 1080 | |
| 1081 | $entityParams = [ |
| 1082 | 'entity_table' => 'civicrm_financial_item', |
| 1083 | ]; |
| 1084 | foreach ($params['line_item'] as $fieldId => $fields) { |
| 1085 | foreach ($fields as $fieldValueId => $lineItemDetails) { |
| 1086 | self::updateFinancialItemForLineItemToPaid($lineItemDetails['id']); |
| 1087 | $fparams = [ |
| 1088 | 1 => [$lineItemDetails['id'], 'Integer'], |
| 1089 | ]; |
| 1090 | $financialItem = CRM_Core_DAO::executeQuery($sql, $fparams); |
| 1091 | while ($financialItem->fetch()) { |
| 1092 | $entityParams['entity_id'] = $financialItem->id; |
| 1093 | $entityParams['amount'] = $financialItem->amount; |
| 1094 | foreach (self::$_trxnIDs as $tID) { |
| 1095 | $entityParams['financial_trxn_id'] = $tID; |
| 1096 | CRM_Financial_BAO_FinancialItem::createEntityTrxn($entityParams); |
| 1097 | } |
| 1098 | } |
| 1099 | } |
| 1100 | } |
| 1101 | return FALSE; |
| 1102 | } |
| 1103 | return TRUE; |
| 1104 | } |
| 1105 | |
| 1106 | /** |
| 1107 | * It is possible to override the membership id that is updated from the payment processor. |
| 1108 | * |
| 1109 | * Historically Paypal does this & it still does if it determines data is messed up - see |
| 1110 | * https://lab.civicrm.org/dev/membership/issues/13 |
| 1111 | * |
| 1112 | * Read the comment block on repeattransaction for more information |
| 1113 | * about how things should work. |
| 1114 | * |
| 1115 | * @param int $contributionID |
| 1116 | * @param array $input |
| 1117 | * |
| 1118 | * @throws \CiviCRM_API3_Exception |
| 1119 | */ |
| 1120 | protected static function handleMembershipIDOverride($contributionID, $input) { |
| 1121 | if (!empty($input['membership_id'])) { |
| 1122 | Civi::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053'); |
| 1123 | civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]); |
| 1124 | } |
| 1125 | } |
| 1126 | |
| 1127 | /** |
| 1128 | * Update all financial items related to the line item tto have a status of paid. |
| 1129 | * |
| 1130 | * @param int $lineItemID |
| 1131 | */ |
| 1132 | private static function updateFinancialItemForLineItemToPaid($lineItemID) { |
| 1133 | $fparams = [ |
| 1134 | 1 => [ |
| 1135 | CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'), |
| 1136 | 'Integer', |
| 1137 | ], |
| 1138 | 2 => [$lineItemID, 'Integer'], |
| 1139 | ]; |
| 1140 | $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'"; |
| 1141 | CRM_Core_DAO::executeQuery($query, $fparams); |
| 1142 | } |
| 1143 | |
| 1144 | /** |
| 1145 | * Create the financial items for the line. |
| 1146 | * |
| 1147 | * @param array $params |
| 1148 | * @param string $context |
| 1149 | * @param array $fields |
| 1150 | * @param array $previousLineItems |
| 1151 | * @param array $inputParams |
| 1152 | * @param bool $isARefund |
| 1153 | * @param array $trxnIds |
| 1154 | * @param int $fieldId |
| 1155 | * |
| 1156 | * @return array |
| 1157 | */ |
| 1158 | private static function createFinancialItemsForLine($params, $context, $fields, array $previousLineItems, array $inputParams, bool $isARefund, $trxnIds, $fieldId): array { |
| 1159 | foreach ($fields as $fieldValueId => $lineItemDetails) { |
| 1160 | $prevFinancialItem = CRM_Financial_BAO_FinancialItem::getPreviousFinancialItem($lineItemDetails['id']); |
| 1161 | $receiveDate = CRM_Utils_Date::isoToMysql($params['prevContribution']->receive_date); |
| 1162 | if ($params['contribution']->receive_date) { |
| 1163 | $receiveDate = CRM_Utils_Date::isoToMysql($params['contribution']->receive_date); |
| 1164 | } |
| 1165 | |
| 1166 | $financialAccount = self::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array::value('financial_account_id', $prevFinancialItem)); |
| 1167 | |
| 1168 | $currency = $params['prevContribution']->currency; |
| 1169 | if ($params['contribution']->currency) { |
| 1170 | $currency = $params['contribution']->currency; |
| 1171 | } |
| 1172 | $previousLineItemTotal = CRM_Utils_Array::value('line_total', CRM_Utils_Array::value($fieldValueId, $previousLineItems), 0); |
| 1173 | $itemParams = [ |
| 1174 | 'transaction_date' => $receiveDate, |
| 1175 | 'contact_id' => $params['prevContribution']->contact_id, |
| 1176 | 'currency' => $currency, |
| 1177 | 'amount' => self::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal), |
| 1178 | 'description' => $prevFinancialItem['description'] ?? NULL, |
| 1179 | 'status_id' => $prevFinancialItem['status_id'], |
| 1180 | 'financial_account_id' => $financialAccount, |
| 1181 | 'entity_table' => 'civicrm_line_item', |
| 1182 | 'entity_id' => $lineItemDetails['id'], |
| 1183 | ]; |
| 1184 | $financialItem = CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds); |
| 1185 | $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount']; |
| 1186 | $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id; |
| 1187 | |
| 1188 | if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') || ($context == 'changeFinancialType')) { |
| 1189 | $taxAmount = (float) $lineItemDetails['tax_amount']; |
| 1190 | if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') { |
| 1191 | // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type |
| 1192 | $taxAmount = CRM_Utils_Array::value('tax_amount', CRM_Utils_Array::value($fieldValueId, $previousLineItems), 0); |
| 1193 | } |
| 1194 | elseif ($previousLineItemTotal != $lineItemDetails['line_total']) { |
| 1195 | $taxAmount -= CRM_Utils_Array::value('tax_amount', CRM_Utils_Array::value($fieldValueId, $previousLineItems), 0); |
| 1196 | } |
| 1197 | if ($taxAmount != 0) { |
| 1198 | $itemParams['amount'] = self::getMultiplier($params['contribution']->contribution_status_id, $context) * $taxAmount; |
| 1199 | $itemParams['description'] = CRM_Invoicing_Utils::getTaxTerm(); |
| 1200 | if ($lineItemDetails['financial_type_id']) { |
| 1201 | $itemParams['financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getSalesTaxFinancialAccount($lineItemDetails['financial_type_id']); |
| 1202 | } |
| 1203 | CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds); |
| 1204 | } |
| 1205 | } |
| 1206 | } |
| 1207 | return $params; |
| 1208 | } |
| 1209 | |
| 1210 | /** |
| 1211 | * Does this contributtion status update represent a refund. |
| 1212 | * |
| 1213 | * @param int $previousContributionStatusID |
| 1214 | * @param int $currentContributionStatusID |
| 1215 | * |
| 1216 | * @return bool |
| 1217 | */ |
| 1218 | private static function isContributionUpdateARefund($previousContributionStatusID, $currentContributionStatusID): bool { |
| 1219 | if ('Completed' !== CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $previousContributionStatusID)) { |
| 1220 | return FALSE; |
| 1221 | } |
| 1222 | return self::isContributionStatusNegative($currentContributionStatusID); |
| 1223 | } |
| 1224 | |
| 1225 | /** |
| 1226 | * Get transaction information about the contribution. |
| 1227 | * |
| 1228 | * @param int $contributionId |
| 1229 | * @param int $financialTypeID |
| 1230 | * |
| 1231 | * @return mixed |
| 1232 | */ |
| 1233 | protected static function getContributionTransactionInformation($contributionId, int $financialTypeID) { |
| 1234 | $rows = []; |
| 1235 | $feeFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeID, 'Expense Account is'); |
| 1236 | |
| 1237 | // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account |
| 1238 | $sql = " |
| 1239 | SELECT GROUP_CONCAT(fa.`name`) as financial_account, |
| 1240 | ft.total_amount, |
| 1241 | ft.payment_instrument_id, |
| 1242 | ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id |
| 1243 | |
| 1244 | FROM civicrm_contribution con |
| 1245 | LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution') |
| 1246 | INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id |
| 1247 | AND ft.to_financial_account_id != %2 |
| 1248 | LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item') |
| 1249 | LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id |
| 1250 | LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id |
| 1251 | |
| 1252 | WHERE con.id = %1 AND ft.is_payment = 1 |
| 1253 | GROUP BY ft.id"; |
| 1254 | $queryParams = [ |
| 1255 | 1 => [$contributionId, 'Integer'], |
| 1256 | 2 => [$feeFinancialAccount, 'Integer'], |
| 1257 | ]; |
| 1258 | $resultDAO = CRM_Core_DAO::executeQuery($sql, $queryParams); |
| 1259 | $statuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'label'); |
| 1260 | |
| 1261 | while ($resultDAO->fetch()) { |
| 1262 | $paidByLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id); |
| 1263 | $paidByName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id); |
| 1264 | if ($resultDAO->card_type_id) { |
| 1265 | $creditCardType = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id); |
| 1266 | $pantruncation = ''; |
| 1267 | if ($resultDAO->pan_truncation) { |
| 1268 | $pantruncation = ": {$resultDAO->pan_truncation}"; |
| 1269 | } |
| 1270 | $paidByLabel .= " ({$creditCardType}{$pantruncation})"; |
| 1271 | } |
| 1272 | |
| 1273 | // show payment edit link only for payments done via backoffice form |
| 1274 | $paymentEditLink = ''; |
| 1275 | if (empty($resultDAO->payment_processor_id) && CRM_Core_Permission::check('edit contributions')) { |
| 1276 | $links = [ |
| 1277 | CRM_Core_Action::UPDATE => [ |
| 1278 | 'name' => ts('Edit Payment'), |
| 1279 | 'icon' => 'fa-pencil', |
| 1280 | 'url' => 'civicrm/payment/edit', |
| 1281 | 'class' => 'medium-popup', |
| 1282 | 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%", |
| 1283 | 'title' => ts('Edit Payment'), |
| 1284 | ], |
| 1285 | ]; |
| 1286 | $paymentEditLink = CRM_Core_Action::formLink( |
| 1287 | $links, |
| 1288 | CRM_Core_Action::mask([CRM_Core_Permission::EDIT]), |
| 1289 | [ |
| 1290 | 'id' => $resultDAO->id, |
| 1291 | 'contribution_id' => $contributionId, |
| 1292 | ], |
| 1293 | ts('more'), |
| 1294 | FALSE, |
| 1295 | 'Payment.edit.action', |
| 1296 | 'Payment', |
| 1297 | $resultDAO->id, |
| 1298 | 'icon' |
| 1299 | ); |
| 1300 | } |
| 1301 | |
| 1302 | $val = [ |
| 1303 | 'id' => $resultDAO->id, |
| 1304 | 'total_amount' => $resultDAO->total_amount, |
| 1305 | 'financial_type' => $resultDAO->financial_account, |
| 1306 | 'payment_instrument' => $paidByLabel, |
| 1307 | 'receive_date' => $resultDAO->trxn_date, |
| 1308 | 'trxn_id' => $resultDAO->trxn_id, |
| 1309 | 'status' => $statuses[$resultDAO->status_id], |
| 1310 | 'currency' => $resultDAO->currency, |
| 1311 | 'action' => $paymentEditLink, |
| 1312 | ]; |
| 1313 | if ($paidByName == 'Check') { |
| 1314 | $val['check_number'] = $resultDAO->check_number; |
| 1315 | } |
| 1316 | $rows[] = $val; |
| 1317 | } |
| 1318 | return $rows; |
| 1319 | } |
| 1320 | |
| 1321 | /** |
| 1322 | * Should an email receipt be sent for this contribution on completion. |
| 1323 | * |
| 1324 | * @param array $input |
| 1325 | * @param int $contributionPageID |
| 1326 | * @param int $recurringContributionID |
| 1327 | * |
| 1328 | * @return bool |
| 1329 | * @throws \API_Exception |
| 1330 | * @throws \Civi\API\Exception\UnauthorizedException |
| 1331 | */ |
| 1332 | protected static function isEmailReceipt(array $input, $contributionPageID, $recurringContributionID): bool { |
| 1333 | if (isset($input['is_email_receipt'])) { |
| 1334 | return (bool) $input['is_email_receipt']; |
| 1335 | } |
| 1336 | if ($recurringContributionID) { |
| 1337 | //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting |
| 1338 | // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden. |
| 1339 | // dev/core#1245 this maybe not the desired effect because the default value for is_email_receipt is set to 0 rather than 1 in |
| 1340 | // Instance that had the table added via an upgrade in 4.1 |
| 1341 | // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354 |
| 1342 | // https://lab.civicrm.org/dev/core/issues/1245 |
| 1343 | return (bool) ContributionRecur::get(FALSE)->addWhere('id', '=', $recurringContributionID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt']; |
| 1344 | } |
| 1345 | if ($contributionPageID) { |
| 1346 | return (bool) ContributionPage::get(FALSE)->addWhere('id', '=', $contributionPageID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt']; |
| 1347 | } |
| 1348 | // This would be the case for backoffice (where is_email_receipt is not passed in) or events, where Event::sendMail will filter |
| 1349 | // again anyway. |
| 1350 | return TRUE; |
| 1351 | } |
| 1352 | |
| 1353 | /** |
| 1354 | * @inheritDoc |
| 1355 | */ |
| 1356 | public function addSelectWhereClause() { |
| 1357 | $whereClauses = parent::addSelectWhereClause(); |
| 1358 | if ($whereClauses !== []) { |
| 1359 | // In this case permisssions have been applied & we assume the |
| 1360 | // financialaclreport is applying these |
| 1361 | // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107 |
| 1362 | return $whereClauses; |
| 1363 | } |
| 1364 | |
| 1365 | if (!CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) { |
| 1366 | return $whereClauses; |
| 1367 | } |
| 1368 | $types = CRM_Financial_BAO_FinancialType::getAllEnabledAvailableFinancialTypes(); |
| 1369 | if (empty($types)) { |
| 1370 | $whereClauses['financial_type_id'] = 'IN (0)'; |
| 1371 | } |
| 1372 | else { |
| 1373 | $whereClauses['financial_type_id'] = [ |
| 1374 | 'IN (' . implode(',', array_keys($types)) . ')', |
| 1375 | ]; |
| 1376 | } |
| 1377 | return $whereClauses; |
| 1378 | } |
| 1379 | |
| 1380 | /** |
| 1381 | * @param null $status |
| 1382 | * @param null $startDate |
| 1383 | * @param null $endDate |
| 1384 | * |
| 1385 | * @return array|null |
| 1386 | */ |
| 1387 | public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) { |
| 1388 | $where = []; |
| 1389 | switch ($status) { |
| 1390 | case 'Valid': |
| 1391 | $where[] = 'contribution_status_id = 1'; |
| 1392 | break; |
| 1393 | |
| 1394 | case 'Cancelled': |
| 1395 | $where[] = 'contribution_status_id = 3'; |
| 1396 | break; |
| 1397 | } |
| 1398 | |
| 1399 | if ($startDate) { |
| 1400 | $where[] = "receive_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'"; |
| 1401 | } |
| 1402 | if ($endDate) { |
| 1403 | $where[] = "receive_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'"; |
| 1404 | } |
| 1405 | $financialTypeACLJoin = ''; |
| 1406 | if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) { |
| 1407 | $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') "; |
| 1408 | $financialTypes = CRM_Contribute_PseudoConstant::financialType(); |
| 1409 | CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes); |
| 1410 | if ($financialTypes) { |
| 1411 | $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")"; |
| 1412 | $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")"; |
| 1413 | } |
| 1414 | else { |
| 1415 | $where[] = "c.financial_type_id IN (0)"; |
| 1416 | } |
| 1417 | } |
| 1418 | |
| 1419 | $whereCond = implode(' AND ', $where); |
| 1420 | |
| 1421 | $query = " |
| 1422 | SELECT sum( total_amount ) as total_amount, |
| 1423 | count( c.id ) as total_count, |
| 1424 | currency |
| 1425 | FROM civicrm_contribution c |
| 1426 | INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id ) |
| 1427 | $financialTypeACLJoin |
| 1428 | WHERE $whereCond |
| 1429 | AND ( is_test = 0 OR is_test IS NULL ) |
| 1430 | AND contact.is_deleted = 0 |
| 1431 | GROUP BY currency |
| 1432 | "; |
| 1433 | |
| 1434 | $dao = CRM_Core_DAO::executeQuery($query); |
| 1435 | $amount = []; |
| 1436 | $count = 0; |
| 1437 | while ($dao->fetch()) { |
| 1438 | $count += $dao->total_count; |
| 1439 | $amount[] = CRM_Utils_Money::format($dao->total_amount, $dao->currency); |
| 1440 | } |
| 1441 | if ($count) { |
| 1442 | return [ |
| 1443 | 'amount' => implode(', ', $amount), |
| 1444 | 'count' => $count, |
| 1445 | ]; |
| 1446 | } |
| 1447 | return NULL; |
| 1448 | } |
| 1449 | |
| 1450 | /** |
| 1451 | * Delete the indirect records associated with this contribution first. |
| 1452 | * |
| 1453 | * @param int $id |
| 1454 | * |
| 1455 | * @return mixed|null |
| 1456 | * $results no of deleted Contribution on success, false otherwise |
| 1457 | */ |
| 1458 | public static function deleteContribution($id) { |
| 1459 | CRM_Utils_Hook::pre('delete', 'Contribution', $id, CRM_Core_DAO::$_nullArray); |
| 1460 | |
| 1461 | $transaction = new CRM_Core_Transaction(); |
| 1462 | |
| 1463 | $results = NULL; |
| 1464 | //delete activity record |
| 1465 | $params = [ |
| 1466 | 'source_record_id' => $id, |
| 1467 | // activity type id for contribution |
| 1468 | 'activity_type_id' => 6, |
| 1469 | ]; |
| 1470 | |
| 1471 | CRM_Activity_BAO_Activity::deleteActivity($params); |
| 1472 | |
| 1473 | //delete billing address if exists for this contribution. |
| 1474 | self::deleteAddress($id); |
| 1475 | |
| 1476 | //update pledge and pledge payment, CRM-3961 |
| 1477 | CRM_Pledge_BAO_PledgePayment::resetPledgePayment($id); |
| 1478 | |
| 1479 | // remove entry from civicrm_price_set_entity, CRM-5095 |
| 1480 | if (CRM_Price_BAO_PriceSet::getFor('civicrm_contribution', $id)) { |
| 1481 | CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution', $id); |
| 1482 | } |
| 1483 | // cleanup line items. |
| 1484 | $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id'); |
| 1485 | |
| 1486 | // delete any related entity_financial_trxn, financial_trxn and financial_item records. |
| 1487 | CRM_Core_BAO_FinancialTrxn::deleteFinancialTrxn($id); |
| 1488 | |
| 1489 | if ($participantId) { |
| 1490 | CRM_Price_BAO_LineItem::deleteLineItems($participantId, 'civicrm_participant'); |
| 1491 | } |
| 1492 | else { |
| 1493 | CRM_Price_BAO_LineItem::deleteLineItems($id, 'civicrm_contribution'); |
| 1494 | } |
| 1495 | |
| 1496 | //delete note. |
| 1497 | $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_contribution'); |
| 1498 | $noteId = key($note); |
| 1499 | if ($noteId) { |
| 1500 | CRM_Core_BAO_Note::del($noteId, FALSE); |
| 1501 | } |
| 1502 | |
| 1503 | $dao = new CRM_Contribute_DAO_Contribution(); |
| 1504 | $dao->id = $id; |
| 1505 | |
| 1506 | $results = $dao->delete(); |
| 1507 | |
| 1508 | $transaction->commit(); |
| 1509 | |
| 1510 | CRM_Utils_Hook::post('delete', 'Contribution', $dao->id, $dao); |
| 1511 | |
| 1512 | // delete the recently created Contribution |
| 1513 | $contributionRecent = [ |
| 1514 | 'id' => $id, |
| 1515 | 'type' => 'Contribution', |
| 1516 | ]; |
| 1517 | CRM_Utils_Recent::del($contributionRecent); |
| 1518 | |
| 1519 | return $results; |
| 1520 | } |
| 1521 | |
| 1522 | /** |
| 1523 | * React to a financial transaction (payment) failure. |
| 1524 | * |
| 1525 | * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted |
| 1526 | * payments is important for forensic and outreach reasons. |
| 1527 | * |
| 1528 | * @param int $contributionID |
| 1529 | * @param int $contactID |
| 1530 | * @param string $message |
| 1531 | * |
| 1532 | * @throws \CiviCRM_API3_Exception |
| 1533 | */ |
| 1534 | public static function failPayment($contributionID, $contactID, $message) { |
| 1535 | civicrm_api3('activity', 'create', [ |
| 1536 | 'activity_type_id' => 'Failed Payment', |
| 1537 | 'details' => $message, |
| 1538 | 'subject' => ts('Payment failed at payment processor'), |
| 1539 | 'source_record_id' => $contributionID, |
| 1540 | 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() : $contactID, |
| 1541 | ]); |
| 1542 | |
| 1543 | // CRM-20336 Make sure that the contribution status is Failed, not Pending. |
| 1544 | civicrm_api3('contribution', 'create', [ |
| 1545 | 'id' => $contributionID, |
| 1546 | 'contribution_status_id' => 'Failed', |
| 1547 | ]); |
| 1548 | } |
| 1549 | |
| 1550 | /** |
| 1551 | * Check if there is a contribution with the same trxn_id or invoice_id. |
| 1552 | * |
| 1553 | * @param array $input |
| 1554 | * An assoc array of name/value pairs. |
| 1555 | * @param array $duplicates |
| 1556 | * (reference) store ids of duplicate contribs. |
| 1557 | * @param int $id |
| 1558 | * |
| 1559 | * @return bool |
| 1560 | * true if duplicate, false otherwise |
| 1561 | */ |
| 1562 | public static function checkDuplicate($input, &$duplicates, $id = NULL) { |
| 1563 | if (!$id) { |
| 1564 | $id = $input['id'] ?? NULL; |
| 1565 | } |
| 1566 | $trxn_id = $input['trxn_id'] ?? NULL; |
| 1567 | $invoice_id = $input['invoice_id'] ?? NULL; |
| 1568 | |
| 1569 | $clause = []; |
| 1570 | $input = []; |
| 1571 | |
| 1572 | if ($trxn_id) { |
| 1573 | $clause[] = "trxn_id = %1"; |
| 1574 | $input[1] = [$trxn_id, 'String']; |
| 1575 | } |
| 1576 | |
| 1577 | if ($invoice_id) { |
| 1578 | $clause[] = "invoice_id = %2"; |
| 1579 | $input[2] = [$invoice_id, 'String']; |
| 1580 | } |
| 1581 | |
| 1582 | if (empty($clause)) { |
| 1583 | return FALSE; |
| 1584 | } |
| 1585 | |
| 1586 | $clause = implode(' OR ', $clause); |
| 1587 | if ($id) { |
| 1588 | $clause = "( $clause ) AND id != %3"; |
| 1589 | $input[3] = [$id, 'Integer']; |
| 1590 | } |
| 1591 | |
| 1592 | $query = "SELECT id FROM civicrm_contribution WHERE $clause"; |
| 1593 | $dao = CRM_Core_DAO::executeQuery($query, $input); |
| 1594 | $result = FALSE; |
| 1595 | while ($dao->fetch()) { |
| 1596 | $duplicates[] = $dao->id; |
| 1597 | $result = TRUE; |
| 1598 | } |
| 1599 | return $result; |
| 1600 | } |
| 1601 | |
| 1602 | /** |
| 1603 | * Takes an associative array and creates a contribution_product object. |
| 1604 | * |
| 1605 | * the function extract all the params it needs to initialize the create a |
| 1606 | * contribution_product object. the params array could contain additional unused name/value |
| 1607 | * pairs |
| 1608 | * |
| 1609 | * @param array $params |
| 1610 | * (reference) an assoc array of name/value pairs. |
| 1611 | * |
| 1612 | * @return CRM_Contribute_DAO_ContributionProduct |
| 1613 | */ |
| 1614 | public static function addPremium(&$params) { |
| 1615 | $contributionProduct = new CRM_Contribute_DAO_ContributionProduct(); |
| 1616 | $contributionProduct->copyValues($params); |
| 1617 | return $contributionProduct->save(); |
| 1618 | } |
| 1619 | |
| 1620 | /** |
| 1621 | * Get list of contribution fields for profile. |
| 1622 | * For now we only allow custom contribution fields to be in |
| 1623 | * profile |
| 1624 | * |
| 1625 | * @param bool $addExtraFields |
| 1626 | * True if special fields needs to be added. |
| 1627 | * |
| 1628 | * @return array |
| 1629 | * the list of contribution fields |
| 1630 | */ |
| 1631 | public static function getContributionFields($addExtraFields = TRUE) { |
| 1632 | $contributionFields = CRM_Contribute_DAO_Contribution::export(); |
| 1633 | // @todo remove this - this line was added because payment_instrument_id was not |
| 1634 | // set to exportable - but now it is. |
| 1635 | $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue::getFields($mode = 'contribute')); |
| 1636 | |
| 1637 | if ($addExtraFields) { |
| 1638 | $contributionFields = array_merge($contributionFields, self::getSpecialContributionFields()); |
| 1639 | } |
| 1640 | |
| 1641 | $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType::export()); |
| 1642 | |
| 1643 | foreach ($contributionFields as $key => $var) { |
| 1644 | if ($key == 'contribution_contact_id') { |
| 1645 | continue; |
| 1646 | } |
| 1647 | elseif ($key == 'contribution_campaign_id') { |
| 1648 | $var['title'] = ts('Campaign'); |
| 1649 | } |
| 1650 | $fields[$key] = $var; |
| 1651 | } |
| 1652 | |
| 1653 | $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution')); |
| 1654 | return $fields; |
| 1655 | } |
| 1656 | |
| 1657 | /** |
| 1658 | * Add extra fields specific to contribution. |
| 1659 | */ |
| 1660 | public static function getSpecialContributionFields() { |
| 1661 | $extraFields = [ |
| 1662 | 'contribution_soft_credit_name' => [ |
| 1663 | 'name' => 'contribution_soft_credit_name', |
| 1664 | 'title' => ts('Soft Credit Name'), |
| 1665 | 'headerPattern' => '/^soft_credit_name$/i', |
| 1666 | 'where' => 'civicrm_contact_d.display_name', |
| 1667 | ], |
| 1668 | 'contribution_soft_credit_email' => [ |
| 1669 | 'name' => 'contribution_soft_credit_email', |
| 1670 | 'title' => ts('Soft Credit Email'), |
| 1671 | 'headerPattern' => '/^soft_credit_email$/i', |
| 1672 | 'where' => 'soft_email.email', |
| 1673 | ], |
| 1674 | 'contribution_soft_credit_phone' => [ |
| 1675 | 'name' => 'contribution_soft_credit_phone', |
| 1676 | 'title' => ts('Soft Credit Phone'), |
| 1677 | 'headerPattern' => '/^soft_credit_phone$/i', |
| 1678 | 'where' => 'soft_phone.phone', |
| 1679 | ], |
| 1680 | 'contribution_soft_credit_contact_id' => [ |
| 1681 | 'name' => 'contribution_soft_credit_contact_id', |
| 1682 | 'title' => ts('Soft Credit Contact ID'), |
| 1683 | 'headerPattern' => '/^soft_credit_contact_id$/i', |
| 1684 | 'where' => 'civicrm_contribution_soft.contact_id', |
| 1685 | ], |
| 1686 | 'contribution_pcp_title' => [ |
| 1687 | 'name' => 'contribution_pcp_title', |
| 1688 | 'title' => ts('Personal Campaign Page Title'), |
| 1689 | 'headerPattern' => '/^contribution_pcp_title$/i', |
| 1690 | 'where' => 'contribution_pcp.title', |
| 1691 | ], |
| 1692 | ]; |
| 1693 | |
| 1694 | return $extraFields; |
| 1695 | } |
| 1696 | |
| 1697 | /** |
| 1698 | * @param int $pageID |
| 1699 | * |
| 1700 | * @return array |
| 1701 | */ |
| 1702 | public static function getCurrentandGoalAmount($pageID) { |
| 1703 | $query = " |
| 1704 | SELECT p.goal_amount as goal, sum( c.total_amount ) as total |
| 1705 | FROM civicrm_contribution_page p, |
| 1706 | civicrm_contribution c |
| 1707 | WHERE p.id = c.contribution_page_id |
| 1708 | AND p.id = %1 |
| 1709 | AND c.cancel_date is null |
| 1710 | GROUP BY p.id |
| 1711 | "; |
| 1712 | |
| 1713 | $config = CRM_Core_Config::singleton(); |
| 1714 | $params = [1 => [$pageID, 'Integer']]; |
| 1715 | $dao = CRM_Core_DAO::executeQuery($query, $params); |
| 1716 | |
| 1717 | if ($dao->fetch()) { |
| 1718 | return [$dao->goal, $dao->total]; |
| 1719 | } |
| 1720 | else { |
| 1721 | return [NULL, NULL]; |
| 1722 | } |
| 1723 | } |
| 1724 | |
| 1725 | /** |
| 1726 | * Get list of contributions which credit the passed in contact ID. |
| 1727 | * |
| 1728 | * The returned array provides details about the original contribution & donor. |
| 1729 | * |
| 1730 | * @param int $honorId |
| 1731 | * In Honor of Contact ID. |
| 1732 | * |
| 1733 | * @return array |
| 1734 | * list of contribution fields |
| 1735 | * @todo - this is a confusing function called from one place. It has a test. It would be |
| 1736 | * nice to deprecate it. |
| 1737 | * |
| 1738 | */ |
| 1739 | public static function getHonorContacts($honorId) { |
| 1740 | $params = []; |
| 1741 | $honorDAO = new CRM_Contribute_DAO_ContributionSoft(); |
| 1742 | $honorDAO->contact_id = $honorId; |
| 1743 | $honorDAO->find(); |
| 1744 | |
| 1745 | $type = CRM_Contribute_PseudoConstant::financialType(); |
| 1746 | |
| 1747 | while ($honorDAO->fetch()) { |
| 1748 | $contributionDAO = new CRM_Contribute_DAO_Contribution(); |
| 1749 | $contributionDAO->id = $honorDAO->contribution_id; |
| 1750 | |
| 1751 | if ($contributionDAO->find(TRUE)) { |
| 1752 | $params[$contributionDAO->id]['honor_type'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id); |
| 1753 | $params[$contributionDAO->id]['honorId'] = $contributionDAO->contact_id; |
| 1754 | $params[$contributionDAO->id]['display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id, 'display_name'); |
| 1755 | $params[$contributionDAO->id]['type'] = $type[$contributionDAO->financial_type_id]; |
| 1756 | $params[$contributionDAO->id]['type_id'] = $contributionDAO->financial_type_id; |
| 1757 | $params[$contributionDAO->id]['amount'] = CRM_Utils_Money::format($contributionDAO->total_amount, $contributionDAO->currency); |
| 1758 | $params[$contributionDAO->id]['source'] = $contributionDAO->source; |
| 1759 | $params[$contributionDAO->id]['receive_date'] = $contributionDAO->receive_date; |
| 1760 | $params[$contributionDAO->id]['contribution_status'] = CRM_Contribute_PseudoConstant::contributionStatus($contributionDAO->contribution_status_id, 'label'); |
| 1761 | } |
| 1762 | } |
| 1763 | |
| 1764 | return $params; |
| 1765 | } |
| 1766 | |
| 1767 | /** |
| 1768 | * Get the sort name of a contact for a particular contribution. |
| 1769 | * |
| 1770 | * @param int $id |
| 1771 | * Id of the contribution. |
| 1772 | * |
| 1773 | * @return null|string |
| 1774 | * sort name of the contact if found |
| 1775 | */ |
| 1776 | public static function sortName($id) { |
| 1777 | $id = CRM_Utils_Type::escape($id, 'Integer'); |
| 1778 | |
| 1779 | $query = " |
| 1780 | SELECT civicrm_contact.sort_name |
| 1781 | FROM civicrm_contribution, civicrm_contact |
| 1782 | WHERE civicrm_contribution.contact_id = civicrm_contact.id |
| 1783 | AND civicrm_contribution.id = {$id} |
| 1784 | "; |
| 1785 | return CRM_Core_DAO::singleValueQuery($query); |
| 1786 | } |
| 1787 | |
| 1788 | /** |
| 1789 | * Generate summary of amount received in the current fiscal year to date from the contact or contacts. |
| 1790 | * |
| 1791 | * @param int|array $contactIDs |
| 1792 | * |
| 1793 | * @return array |
| 1794 | */ |
| 1795 | public static function annual($contactIDs) { |
| 1796 | if (!is_array($contactIDs)) { |
| 1797 | // In practice I can't fine any evidence that this function is ever called with |
| 1798 | // anything other than a single contact id, but left like this due to .... fear. |
| 1799 | $contactIDs = explode(',', $contactIDs); |
| 1800 | } |
| 1801 | |
| 1802 | $query = self::getAnnualQuery($contactIDs); |
| 1803 | $dao = CRM_Core_DAO::executeQuery($query); |
| 1804 | $count = 0; |
| 1805 | $amount = $average = []; |
| 1806 | while ($dao->fetch()) { |
| 1807 | if ($dao->count > 0 && $dao->amount > 0) { |
| 1808 | $count += $dao->count; |
| 1809 | $amount[] = CRM_Utils_Money::format($dao->amount, $dao->currency); |
| 1810 | $average[] = CRM_Utils_Money::format($dao->average, $dao->currency); |
| 1811 | } |
| 1812 | } |
| 1813 | if ($count > 0) { |
| 1814 | return [ |
| 1815 | $count, |
| 1816 | implode(', ', $amount), |
| 1817 | implode(', ', $average), |
| 1818 | ]; |
| 1819 | } |
| 1820 | return [0, 0, 0]; |
| 1821 | } |
| 1822 | |
| 1823 | /** |
| 1824 | * Check if there is a contribution with the params passed in. |
| 1825 | * |
| 1826 | * Used for trxn_id,invoice_id and contribution_id |
| 1827 | * |
| 1828 | * @param array $params |
| 1829 | * An assoc array of name/value pairs. |
| 1830 | * |
| 1831 | * @return array |
| 1832 | * contribution id if success else NULL |
| 1833 | */ |
| 1834 | public static function checkDuplicateIds($params) { |
| 1835 | $dao = new CRM_Contribute_DAO_Contribution(); |
| 1836 | |
| 1837 | $clause = []; |
| 1838 | $input = []; |
| 1839 | foreach ($params as $k => $v) { |
| 1840 | if ($v) { |
| 1841 | $clause[] = "$k = '$v'"; |
| 1842 | } |
| 1843 | } |
| 1844 | $clause = implode(' AND ', $clause); |
| 1845 | $query = "SELECT id FROM civicrm_contribution WHERE $clause"; |
| 1846 | $dao = CRM_Core_DAO::executeQuery($query, $input); |
| 1847 | |
| 1848 | while ($dao->fetch()) { |
| 1849 | $result = $dao->id; |
| 1850 | return $result; |
| 1851 | } |
| 1852 | return NULL; |
| 1853 | } |
| 1854 | |
| 1855 | /** |
| 1856 | * Get the contribution details for component export. |
| 1857 | * |
| 1858 | * @param int $exportMode |
| 1859 | * Export mode. |
| 1860 | * @param array $componentIds |
| 1861 | * Component ids. |
| 1862 | * |
| 1863 | * @return array |
| 1864 | * associated array |
| 1865 | */ |
| 1866 | public static function getContributionDetails($exportMode, $componentIds) { |
| 1867 | $paymentDetails = []; |
| 1868 | $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) '; |
| 1869 | |
| 1870 | if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) { |
| 1871 | $componentSelect = " civicrm_participant_payment.participant_id id"; |
| 1872 | $additionalClause = " |
| 1873 | INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id |
| 1874 | AND civicrm_participant_payment.participant_id {$componentClause} ) |
| 1875 | "; |
| 1876 | } |
| 1877 | elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) { |
| 1878 | $componentSelect = " civicrm_membership_payment.membership_id id"; |
| 1879 | $additionalClause = " |
| 1880 | INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id |
| 1881 | AND civicrm_membership_payment.membership_id {$componentClause} ) |
| 1882 | "; |
| 1883 | } |
| 1884 | elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) { |
| 1885 | $componentSelect = " civicrm_pledge_payment.id id"; |
| 1886 | $additionalClause = " |
| 1887 | INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id |
| 1888 | AND civicrm_pledge_payment.pledge_id {$componentClause} ) |
| 1889 | "; |
| 1890 | } |
| 1891 | |
| 1892 | $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date, |
| 1893 | trxn_id, {$componentSelect} |
| 1894 | FROM civicrm_contribution |
| 1895 | LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument') |
| 1896 | LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value |
| 1897 | AND option_group_payment_instrument.id = payment_instrument.option_group_id ) |
| 1898 | LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status') |
| 1899 | LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value |
| 1900 | AND option_group_contribution_status.id = contribution_status.option_group_id ) |
| 1901 | {$additionalClause} |
| 1902 | "; |
| 1903 | |
| 1904 | $dao = CRM_Core_DAO::executeQuery($query); |
| 1905 | |
| 1906 | while ($dao->fetch()) { |
| 1907 | $paymentDetails[$dao->id] = [ |
| 1908 | 'total_amount' => $dao->total_amount, |
| 1909 | 'contribution_status' => $dao->status, |
| 1910 | 'receive_date' => $dao->receive_date, |
| 1911 | 'pay_instru' => $dao->payment_instrument, |
| 1912 | 'trxn_id' => $dao->trxn_id, |
| 1913 | ]; |
| 1914 | } |
| 1915 | |
| 1916 | return $paymentDetails; |
| 1917 | } |
| 1918 | |
| 1919 | /** |
| 1920 | * Create address associated with contribution record. |
| 1921 | * |
| 1922 | * As long as there is one or more billing field in the parameters we will create the address. |
| 1923 | * |
| 1924 | * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once |
| 1925 | * thought). |
| 1926 | * |
| 1927 | * @param array $params |
| 1928 | * @param int $billingLocationTypeID |
| 1929 | * |
| 1930 | * @return int |
| 1931 | * address id |
| 1932 | */ |
| 1933 | public static function createAddress($params, $billingLocationTypeID) { |
| 1934 | list($hasBillingField, $addressParams) = self::getBillingAddressParams($params, $billingLocationTypeID); |
| 1935 | if ($hasBillingField) { |
| 1936 | $address = CRM_Core_BAO_Address::add($addressParams, FALSE); |
| 1937 | return $address->id; |
| 1938 | } |
| 1939 | return NULL; |
| 1940 | |
| 1941 | } |
| 1942 | |
| 1943 | /** |
| 1944 | * Delete billing address record related contribution. |
| 1945 | * |
| 1946 | * @param int $contributionId |
| 1947 | * @param int $contactId |
| 1948 | */ |
| 1949 | public static function deleteAddress($contributionId = NULL, $contactId = NULL) { |
| 1950 | $clauses = []; |
| 1951 | $contactJoin = NULL; |
| 1952 | |
| 1953 | if ($contributionId) { |
| 1954 | $clauses[] = "cc.id = {$contributionId}"; |
| 1955 | } |
| 1956 | |
| 1957 | if ($contactId) { |
| 1958 | $clauses[] = "cco.id = {$contactId}"; |
| 1959 | $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id"; |
| 1960 | } |
| 1961 | |
| 1962 | if (empty($clauses)) { |
| 1963 | throw new CRM_Core_Exception('No Where clauses defined when deleting address'); |
| 1964 | } |
| 1965 | |
| 1966 | $condition = implode(' OR ', $clauses); |
| 1967 | |
| 1968 | $query = " |
| 1969 | SELECT ca.id |
| 1970 | FROM civicrm_address ca |
| 1971 | INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id |
| 1972 | $contactJoin |
| 1973 | WHERE $condition |
| 1974 | "; |
| 1975 | $dao = CRM_Core_DAO::executeQuery($query); |
| 1976 | |
| 1977 | while ($dao->fetch()) { |
| 1978 | $params = ['id' => $dao->id]; |
| 1979 | CRM_Core_BAO_Block::blockDelete('Address', $params); |
| 1980 | } |
| 1981 | } |
| 1982 | |
| 1983 | /** |
| 1984 | * This function check online pending contribution associated w/ |
| 1985 | * Online Event Registration or Online Membership signup. |
| 1986 | * |
| 1987 | * @param int $componentId |
| 1988 | * Participant/membership id. |
| 1989 | * @param string $componentName |
| 1990 | * Event/Membership. |
| 1991 | * |
| 1992 | * @return int |
| 1993 | * pending contribution id. |
| 1994 | */ |
| 1995 | public static function checkOnlinePendingContribution($componentId, $componentName) { |
| 1996 | $contributionId = NULL; |
| 1997 | if (!$componentId || |
| 1998 | !in_array($componentName, ['Event', 'Membership']) |
| 1999 | ) { |
| 2000 | return $contributionId; |
| 2001 | } |
| 2002 | |
| 2003 | if ($componentName == 'Event') { |
| 2004 | $idName = 'participant_id'; |
| 2005 | $componentTable = 'civicrm_participant'; |
| 2006 | $paymentTable = 'civicrm_participant_payment'; |
| 2007 | $source = ts('Online Event Registration'); |
| 2008 | } |
| 2009 | |
| 2010 | if ($componentName == 'Membership') { |
| 2011 | $idName = 'membership_id'; |
| 2012 | $componentTable = 'civicrm_membership'; |
| 2013 | $paymentTable = 'civicrm_membership_payment'; |
| 2014 | $source = ts('Online Contribution'); |
| 2015 | } |
| 2016 | |
| 2017 | $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')); |
| 2018 | |
| 2019 | $query = " |
| 2020 | SELECT component.id as {$idName}, |
| 2021 | componentPayment.contribution_id as contribution_id, |
| 2022 | contribution.source source, |
| 2023 | contribution.contribution_status_id as contribution_status_id, |
| 2024 | contribution.is_pay_later as is_pay_later |
| 2025 | FROM $componentTable component |
| 2026 | LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id ) |
| 2027 | LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id ) |
| 2028 | WHERE component.id = {$componentId}"; |
| 2029 | |
| 2030 | $dao = CRM_Core_DAO::executeQuery($query); |
| 2031 | |
| 2032 | while ($dao->fetch()) { |
| 2033 | if ($dao->contribution_id && |
| 2034 | $dao->is_pay_later && |
| 2035 | $dao->contribution_status_id == $pendingStatusId && |
| 2036 | strpos($dao->source, $source) !== FALSE |
| 2037 | ) { |
| 2038 | $contributionId = $dao->contribution_id; |
| 2039 | } |
| 2040 | } |
| 2041 | |
| 2042 | return $contributionId; |
| 2043 | } |
| 2044 | |
| 2045 | /** |
| 2046 | * Update contribution as well as related objects. |
| 2047 | * |
| 2048 | * This function by-passes hooks - to address this - don't use this function. |
| 2049 | * |
| 2050 | * @param array $params |
| 2051 | * @param bool $processContributionObject |
| 2052 | * |
| 2053 | * @return array |
| 2054 | * |
| 2055 | * @throws CRM_Core_Exception |
| 2056 | * @throws \CiviCRM_API3_Exception |
| 2057 | * @deprecated |
| 2058 | * |
| 2059 | * Use api contribute.completetransaction |
| 2060 | * For failures use failPayment (preferably exposing by api in the process). |
| 2061 | * |
| 2062 | */ |
| 2063 | public static function transitionComponents($params, $processContributionObject = FALSE) { |
| 2064 | // get minimum required values. |
| 2065 | $contactId = $params['contact_id'] ?? NULL; |
| 2066 | $componentId = $params['component_id'] ?? NULL; |
| 2067 | $componentName = $params['componentName'] ?? NULL; |
| 2068 | $contributionId = $params['contribution_id'] ?? NULL; |
| 2069 | $contributionStatusId = $params['contribution_status_id'] ?? NULL; |
| 2070 | |
| 2071 | // if we already processed contribution object pass previous status id. |
| 2072 | $previousContriStatusId = $params['previous_contribution_status_id'] ?? NULL; |
| 2073 | |
| 2074 | $updateResult = []; |
| 2075 | |
| 2076 | $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
| 2077 | |
| 2078 | // we process only ( Completed, Cancelled, or Failed ) contributions. |
| 2079 | if (!$contributionId || |
| 2080 | !in_array($contributionStatusId, [ |
| 2081 | array_search('Completed', $contributionStatuses), |
| 2082 | array_search('Cancelled', $contributionStatuses), |
| 2083 | array_search('Failed', $contributionStatuses), |
| 2084 | ]) |
| 2085 | ) { |
| 2086 | return $updateResult; |
| 2087 | } |
| 2088 | |
| 2089 | if (!$componentName || !$componentId) { |
| 2090 | // get the related component details. |
| 2091 | $componentDetails = self::getComponentDetails($contributionId); |
| 2092 | } |
| 2093 | else { |
| 2094 | $componentDetails['contact_id'] = $contactId; |
| 2095 | $componentDetails['component'] = $componentName; |
| 2096 | |
| 2097 | if ($componentName == 'event') { |
| 2098 | $componentDetails['participant'] = $componentId; |
| 2099 | } |
| 2100 | else { |
| 2101 | $componentDetails['membership'] = $componentId; |
| 2102 | } |
| 2103 | } |
| 2104 | |
| 2105 | if (!empty($componentDetails['contact_id'])) { |
| 2106 | $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', |
| 2107 | $contributionId, |
| 2108 | 'contact_id' |
| 2109 | ); |
| 2110 | } |
| 2111 | |
| 2112 | // do check for required ids. |
| 2113 | if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) || empty($componentDetails['contact_id'])) { |
| 2114 | return $updateResult; |
| 2115 | } |
| 2116 | |
| 2117 | $input = $ids = []; |
| 2118 | |
| 2119 | $input['component'] = $componentDetails['component'] ?? NULL; |
| 2120 | $ids['contribution'] = $contributionId; |
| 2121 | $ids['contact'] = $componentDetails['contact_id'] ?? NULL; |
| 2122 | $ids['membership'] = $componentDetails['membership'] ?? NULL; |
| 2123 | $ids['participant'] = $componentDetails['participant'] ?? NULL; |
| 2124 | $ids['event'] = $componentDetails['event'] ?? NULL; |
| 2125 | $ids['pledge_payment'] = $componentDetails['pledge_payment'] ?? NULL; |
| 2126 | $ids['contributionRecur'] = NULL; |
| 2127 | $ids['contributionPage'] = NULL; |
| 2128 | |
| 2129 | $contribution = new CRM_Contribute_BAO_Contribution(); |
| 2130 | $contribution->id = $ids['contribution']; |
| 2131 | $contribution->find(); |
| 2132 | |
| 2133 | $contribution->loadRelatedObjects($input, $ids); |
| 2134 | |
| 2135 | $memberships = $contribution->_relatedObjects['membership'] ?? []; |
| 2136 | $participant = $contribution->_relatedObjects['participant'] ?? []; |
| 2137 | $pledgePayment = $contribution->_relatedObjects['pledge_payment'] ?? []; |
| 2138 | |
| 2139 | $pledgeID = $oldStatus = NULL; |
| 2140 | $pledgePaymentIDs = []; |
| 2141 | if ($pledgePayment) { |
| 2142 | foreach ($pledgePayment as $key => $object) { |
| 2143 | $pledgePaymentIDs[] = $object->id; |
| 2144 | } |
| 2145 | $pledgeID = $pledgePayment[0]->pledge_id; |
| 2146 | } |
| 2147 | |
| 2148 | $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus(); |
| 2149 | |
| 2150 | if ($participant) { |
| 2151 | $participantStatuses = CRM_Event_PseudoConstant::participantStatus(); |
| 2152 | $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', |
| 2153 | $participant->id, |
| 2154 | 'status_id' |
| 2155 | ); |
| 2156 | } |
| 2157 | // we might want to process contribution object. |
| 2158 | $processContribution = FALSE; |
| 2159 | if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) { |
| 2160 | // Call interim cancel function - with a goal to cleaning up the signature on it and switching to a tested api Contribution.cancel function. |
| 2161 | list($updateResult, $processContribution) = self::cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId); |
| 2162 | } |
| 2163 | elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) { |
| 2164 | if (is_array($memberships)) { |
| 2165 | foreach ($memberships as $membership) { |
| 2166 | $update = TRUE; |
| 2167 | //Update Membership status if there is no other completed contribution associated with the membership. |
| 2168 | $relatedContributions = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id, TRUE); |
| 2169 | foreach ($relatedContributions as $contriId) { |
| 2170 | if ($contriId == $contributionId) { |
| 2171 | continue; |
| 2172 | } |
| 2173 | $statusId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id'); |
| 2174 | if (CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') { |
| 2175 | $update = FALSE; |
| 2176 | } |
| 2177 | } |
| 2178 | if ($membership && $update) { |
| 2179 | $membership->status_id = array_search('Expired', $membershipStatuses); |
| 2180 | $membership->is_override = TRUE; |
| 2181 | $membership->status_override_end_date = 'null'; |
| 2182 | $membership->save(); |
| 2183 | |
| 2184 | $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; |
| 2185 | if ($processContributionObject) { |
| 2186 | $processContribution = TRUE; |
| 2187 | } |
| 2188 | } |
| 2189 | } |
| 2190 | } |
| 2191 | if ($participant) { |
| 2192 | $updatedStatusId = array_search('Cancelled', $participantStatuses); |
| 2193 | CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE); |
| 2194 | |
| 2195 | $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; |
| 2196 | if ($processContributionObject) { |
| 2197 | $processContribution = TRUE; |
| 2198 | } |
| 2199 | } |
| 2200 | |
| 2201 | if ($pledgePayment) { |
| 2202 | CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); |
| 2203 | |
| 2204 | $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; |
| 2205 | if ($processContributionObject) { |
| 2206 | $processContribution = TRUE; |
| 2207 | } |
| 2208 | } |
| 2209 | } |
| 2210 | elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) { |
| 2211 | |
| 2212 | // only pending contribution related object processed. |
| 2213 | if ($previousContriStatusId && |
| 2214 | !in_array($contributionStatuses[$previousContriStatusId], [ |
| 2215 | 'Pending', |
| 2216 | 'Partially paid', |
| 2217 | ]) |
| 2218 | ) { |
| 2219 | // this is case when we already processed contribution object. |
| 2220 | return $updateResult; |
| 2221 | } |
| 2222 | elseif (!$previousContriStatusId && |
| 2223 | !in_array($contributionStatuses[$contribution->contribution_status_id], [ |
| 2224 | 'Pending', |
| 2225 | 'Partially paid', |
| 2226 | ]) |
| 2227 | ) { |
| 2228 | // this is case when we are going to process contribution object later. |
| 2229 | return $updateResult; |
| 2230 | } |
| 2231 | |
| 2232 | if (is_array($memberships)) { |
| 2233 | foreach ($memberships as $membership) { |
| 2234 | if ($membership) { |
| 2235 | $format = '%Y%m%d'; |
| 2236 | |
| 2237 | //CRM-4523 |
| 2238 | $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, |
| 2239 | $membership->membership_type_id, |
| 2240 | $membership->is_test, $membership->id |
| 2241 | ); |
| 2242 | |
| 2243 | // CRM-8141 update the membership type with the value recorded in log when membership created/renewed |
| 2244 | // this picks up membership type changes during renewals |
| 2245 | $sql = " |
| 2246 | SELECT membership_type_id |
| 2247 | FROM civicrm_membership_log |
| 2248 | WHERE membership_id=$membership->id |
| 2249 | ORDER BY id DESC |
| 2250 | LIMIT 1;"; |
| 2251 | $dao = new CRM_Core_DAO(); |
| 2252 | $dao->query($sql); |
| 2253 | if ($dao->fetch()) { |
| 2254 | if (!empty($dao->membership_type_id)) { |
| 2255 | $membership->membership_type_id = $dao->membership_type_id; |
| 2256 | $membership->save(); |
| 2257 | } |
| 2258 | } |
| 2259 | // else fall back to using current membership type |
| 2260 | // Figure out number of terms |
| 2261 | $numterms = 1; |
| 2262 | $lineitems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionId); |
| 2263 | foreach ($lineitems as $lineitem) { |
| 2264 | if ($membership->membership_type_id == ($lineitem['membership_type_id'] ?? NULL)) { |
| 2265 | $numterms = $lineitem['membership_num_terms'] ?? NULL; |
| 2266 | |
| 2267 | // in case membership_num_terms comes through as null or zero |
| 2268 | $numterms = $numterms >= 1 ? $numterms : 1; |
| 2269 | break; |
| 2270 | } |
| 2271 | } |
| 2272 | |
| 2273 | // CRM-15735-to update the membership status as per the contribution receive date |
| 2274 | $joinDate = NULL; |
| 2275 | $oldStatus = $membership->status_id; |
| 2276 | if (!empty($params['receive_date'])) { |
| 2277 | $joinDate = $params['receive_date']; |
| 2278 | $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($membership->start_date, |
| 2279 | $membership->end_date, |
| 2280 | $membership->join_date, |
| 2281 | $params['receive_date'], |
| 2282 | FALSE, |
| 2283 | $membership->membership_type_id, |
| 2284 | (array) $membership |
| 2285 | ); |
| 2286 | $membership->status_id = CRM_Utils_Array::value('id', $status, $membership->status_id); |
| 2287 | $membership->save(); |
| 2288 | } |
| 2289 | |
| 2290 | if ($currentMembership) { |
| 2291 | CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL); |
| 2292 | $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms); |
| 2293 | $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format); |
| 2294 | } |
| 2295 | else { |
| 2296 | $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, $joinDate, NULL, NULL, $numterms); |
| 2297 | } |
| 2298 | |
| 2299 | //get the status for membership. |
| 2300 | $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], |
| 2301 | $dates['end_date'], |
| 2302 | $dates['join_date'], |
| 2303 | 'today', |
| 2304 | TRUE, |
| 2305 | $membership->membership_type_id, |
| 2306 | (array) $membership |
| 2307 | ); |
| 2308 | |
| 2309 | $formattedParams = [ |
| 2310 | 'status_id' => CRM_Utils_Array::value('id', $calcStatus, |
| 2311 | array_search('Current', $membershipStatuses) |
| 2312 | ), |
| 2313 | 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format), |
| 2314 | 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format), |
| 2315 | 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format), |
| 2316 | ]; |
| 2317 | |
| 2318 | CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams); |
| 2319 | |
| 2320 | $membership->copyValues($formattedParams); |
| 2321 | $membership->save(); |
| 2322 | |
| 2323 | //updating the membership log |
| 2324 | $membershipLog = []; |
| 2325 | $membershipLog = $formattedParams; |
| 2326 | $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'] ?? NULL, $format); |
| 2327 | $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date']; |
| 2328 | |
| 2329 | $membershipLog['start_date'] = $logStartDate; |
| 2330 | $membershipLog['membership_id'] = $membership->id; |
| 2331 | $membershipLog['modified_id'] = $membership->contact_id; |
| 2332 | $membershipLog['modified_date'] = date('Ymd'); |
| 2333 | $membershipLog['membership_type_id'] = $membership->membership_type_id; |
| 2334 | |
| 2335 | CRM_Member_BAO_MembershipLog::add($membershipLog); |
| 2336 | |
| 2337 | //update related Memberships. |
| 2338 | CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams); |
| 2339 | |
| 2340 | foreach (['Membership Signup', 'Membership Renewal'] as $activityType) { |
| 2341 | $scheduledActivityID = CRM_Utils_Array::value('id', |
| 2342 | civicrm_api3('Activity', 'Get', |
| 2343 | [ |
| 2344 | 'source_record_id' => $membership->id, |
| 2345 | 'activity_type_id' => $activityType, |
| 2346 | 'status_id' => 'Scheduled', |
| 2347 | 'options' => [ |
| 2348 | 'limit' => 1, |
| 2349 | 'sort' => 'id DESC', |
| 2350 | ], |
| 2351 | ] |
| 2352 | ) |
| 2353 | ); |
| 2354 | // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership |
| 2355 | // 2. OR Create renewal activity scheduled if its membership renewal will be paid later |
| 2356 | if ($scheduledActivityID) { |
| 2357 | CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $membership->contact_id, ['id' => $scheduledActivityID]); |
| 2358 | break; |
| 2359 | } |
| 2360 | } |
| 2361 | |
| 2362 | // track membership status change if any |
| 2363 | if (!empty($oldStatus) && $membership->status_id != $oldStatus) { |
| 2364 | $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'get'); |
| 2365 | CRM_Activity_BAO_Activity::addActivity($membership, |
| 2366 | 'Change Membership Status', |
| 2367 | NULL, |
| 2368 | [ |
| 2369 | 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}", |
| 2370 | 'source_contact_id' => $membershipLog['modified_id'], |
| 2371 | 'priority_id' => 'Normal', |
| 2372 | ] |
| 2373 | ); |
| 2374 | } |
| 2375 | |
| 2376 | $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; |
| 2377 | if ($processContributionObject) { |
| 2378 | $processContribution = TRUE; |
| 2379 | } |
| 2380 | |
| 2381 | CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership); |
| 2382 | } |
| 2383 | } |
| 2384 | } |
| 2385 | |
| 2386 | if ($participant) { |
| 2387 | $updatedStatusId = array_search('Registered', $participantStatuses); |
| 2388 | CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE); |
| 2389 | |
| 2390 | $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; |
| 2391 | if ($processContributionObject) { |
| 2392 | $processContribution = TRUE; |
| 2393 | } |
| 2394 | } |
| 2395 | |
| 2396 | if ($pledgePayment) { |
| 2397 | CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); |
| 2398 | |
| 2399 | $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; |
| 2400 | if ($processContributionObject) { |
| 2401 | $processContribution = TRUE; |
| 2402 | } |
| 2403 | } |
| 2404 | } |
| 2405 | |
| 2406 | // process contribution object. |
| 2407 | if ($processContribution) { |
| 2408 | $contributionParams = []; |
| 2409 | $fields = [ |
| 2410 | 'contact_id', |
| 2411 | 'total_amount', |
| 2412 | 'receive_date', |
| 2413 | 'is_test', |
| 2414 | 'campaign_id', |
| 2415 | 'payment_instrument_id', |
| 2416 | 'trxn_id', |
| 2417 | 'invoice_id', |
| 2418 | 'financial_type_id', |
| 2419 | 'contribution_status_id', |
| 2420 | 'non_deductible_amount', |
| 2421 | 'receipt_date', |
| 2422 | 'check_number', |
| 2423 | ]; |
| 2424 | foreach ($fields as $field) { |
| 2425 | if (empty($params[$field])) { |
| 2426 | continue; |
| 2427 | } |
| 2428 | $contributionParams[$field] = $params[$field]; |
| 2429 | } |
| 2430 | |
| 2431 | $contributionParams['id'] = $contributionId; |
| 2432 | $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams); |
| 2433 | } |
| 2434 | |
| 2435 | return $updateResult; |
| 2436 | } |
| 2437 | |
| 2438 | /** |
| 2439 | * Returns all contribution related object ids. |
| 2440 | * |
| 2441 | * @param $contributionId |
| 2442 | * |
| 2443 | * @return array |
| 2444 | */ |
| 2445 | public static function getComponentDetails($contributionId) { |
| 2446 | $componentDetails = $pledgePayment = []; |
| 2447 | if (!$contributionId) { |
| 2448 | return $componentDetails; |
| 2449 | } |
| 2450 | |
| 2451 | $query = " |
| 2452 | SELECT c.id as contribution_id, |
| 2453 | c.contact_id as contact_id, |
| 2454 | c.contribution_recur_id, |
| 2455 | mp.membership_id as membership_id, |
| 2456 | m.membership_type_id as membership_type_id, |
| 2457 | pp.participant_id as participant_id, |
| 2458 | p.event_id as event_id, |
| 2459 | pgp.id as pledge_payment_id |
| 2460 | FROM civicrm_contribution c |
| 2461 | LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id |
| 2462 | LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id |
| 2463 | LEFT JOIN civicrm_participant p ON pp.participant_id = p.id |
| 2464 | LEFT JOIN civicrm_membership m ON m.id = mp.membership_id |
| 2465 | LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id |
| 2466 | WHERE c.id = $contributionId"; |
| 2467 | |
| 2468 | $dao = CRM_Core_DAO::executeQuery($query); |
| 2469 | $componentDetails = []; |
| 2470 | |
| 2471 | while ($dao->fetch()) { |
| 2472 | $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute'; |
| 2473 | $componentDetails['contact_id'] = $dao->contact_id; |
| 2474 | if ($dao->event_id) { |
| 2475 | $componentDetails['event'] = $dao->event_id; |
| 2476 | } |
| 2477 | if ($dao->participant_id) { |
| 2478 | $componentDetails['participant'] = $dao->participant_id; |
| 2479 | } |
| 2480 | if ($dao->membership_id) { |
| 2481 | if (!isset($componentDetails['membership'])) { |
| 2482 | $componentDetails['membership'] = $componentDetails['membership_type'] = []; |
| 2483 | } |
| 2484 | $componentDetails['membership'][] = $dao->membership_id; |
| 2485 | $componentDetails['membership_type'][] = $dao->membership_type_id; |
| 2486 | } |
| 2487 | if ($dao->pledge_payment_id) { |
| 2488 | $pledgePayment[] = $dao->pledge_payment_id; |
| 2489 | } |
| 2490 | if ($dao->contribution_recur_id) { |
| 2491 | $componentDetails['contributionRecur'] = $dao->contribution_recur_id; |
| 2492 | } |
| 2493 | } |
| 2494 | |
| 2495 | if ($pledgePayment) { |
| 2496 | $componentDetails['pledge_payment'] = $pledgePayment; |
| 2497 | } |
| 2498 | |
| 2499 | return $componentDetails; |
| 2500 | } |
| 2501 | |
| 2502 | /** |
| 2503 | * @param int $contactId |
| 2504 | * @param bool $includeSoftCredit |
| 2505 | * |
| 2506 | * @return null|string |
| 2507 | */ |
| 2508 | public static function contributionCount($contactId, $includeSoftCredit = TRUE) { |
| 2509 | if (!$contactId) { |
| 2510 | return 0; |
| 2511 | } |
| 2512 | $financialTypes = CRM_Financial_BAO_FinancialType::getAllAvailableFinancialTypes(); |
| 2513 | $additionalWhere = " AND contribution.financial_type_id IN (0)"; |
| 2514 | $liWhere = " AND i.financial_type_id IN (0)"; |
| 2515 | if (!empty($financialTypes)) { |
| 2516 | $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")"; |
| 2517 | $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")"; |
| 2518 | } |
| 2519 | $contactContributionsSQL = " |
| 2520 | SELECT contribution.id AS id |
| 2521 | FROM civicrm_contribution contribution |
| 2522 | LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere |
| 2523 | WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} |
| 2524 | $additionalWhere |
| 2525 | AND i.id IS NULL"; |
| 2526 | |
| 2527 | $contactSoftCreditContributionsSQL = " |
| 2528 | SELECT contribution.id |
| 2529 | FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution |
| 2530 | ON ( contribution.id = softContribution.contribution_id ) |
| 2531 | WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} "; |
| 2532 | $query = "SELECT count( x.id ) count FROM ( "; |
| 2533 | $query .= $contactContributionsSQL; |
| 2534 | |
| 2535 | if ($includeSoftCredit) { |
| 2536 | $query .= " UNION "; |
| 2537 | $query .= $contactSoftCreditContributionsSQL; |
| 2538 | } |
| 2539 | |
| 2540 | $query .= ") x"; |
| 2541 | |
| 2542 | return CRM_Core_DAO::singleValueQuery($query); |
| 2543 | } |
| 2544 | |
| 2545 | /** |
| 2546 | * Repeat a transaction as part of a recurring series. |
| 2547 | * |
| 2548 | * The ideal flow is |
| 2549 | * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending |
| 2550 | * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it . |
| 2551 | * 3) Repeat transaction calls order.create to create the pending contribution with correct line items |
| 2552 | * and associated entities. |
| 2553 | * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing) |
| 2554 | * which updates the various entities and sends appropriate emails. |
| 2555 | * |
| 2556 | * Gaps in the above (@todo) |
| 2557 | * 1) many processors still call repeattransaction with contribution_status_id = Completed |
| 2558 | * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons |
| 2559 | * 3) Repeat transaction duplicates rather than calls Order.create |
| 2560 | * 4) Use of payment.create still limited - completetransaction is more common. |
| 2561 | * 5) the template transaction is tricky - historically we used the first contribution |
| 2562 | * linked to a recurring contribution. More recently that was changed to be the most recent. |
| 2563 | * Ideally it would be an actual template - not a contribution used as a template which |
| 2564 | * would give more appropriate flexibility. Note line_items have an entity so that table |
| 2565 | * could be used for the line item template - the difficulty is the custom fields... |
| 2566 | * 6) the determination of the membership to be linked is tricksy. The prioritised method is |
| 2567 | * to load the membership(s) referred to via line items in the template transactions. Any other |
| 2568 | * method is likely to lead to incorrect line items & related entities being created (as the line_item |
| 2569 | * link is a required part of 'correct data'). However there are 3 other methods to determine it |
| 2570 | * - membership_payment record |
| 2571 | * - civicrm_membership.contribution_recur_id |
| 2572 | * - input override. |
| 2573 | * Passing in an input override WILL ensure the membership is extended to prevent regressions |
| 2574 | * of historical processors since this has been handled 'forever' - specifically for paypal. |
| 2575 | * albeit by an even nastier mechanism than the current input override. |
| 2576 | * The count is out on how correct related entities wind up in this case. |
| 2577 | * |
| 2578 | * @param CRM_Contribute_BAO_Contribution $contribution |
| 2579 | * @param array $input |
| 2580 | * @param array $contributionParams |
| 2581 | * |
| 2582 | * @return bool|array |
| 2583 | * @throws CiviCRM_API3_Exception |
| 2584 | */ |
| 2585 | protected static function repeatTransaction(&$contribution, $input, $contributionParams) { |
| 2586 | if (!empty($contribution->id)) { |
| 2587 | return FALSE; |
| 2588 | } |
| 2589 | if (empty($contribution->id)) { |
| 2590 | // Unclear why this would only be set for repeats. |
| 2591 | if (!empty($input['amount'])) { |
| 2592 | $contribution->total_amount = $contributionParams['total_amount'] = $input['amount']; |
| 2593 | } |
| 2594 | |
| 2595 | if (!empty($contributionParams['contribution_recur_id'])) { |
| 2596 | $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [ |
| 2597 | 'id' => $contributionParams['contribution_recur_id'], |
| 2598 | ]); |
| 2599 | if (!empty($recurringContribution['campaign_id'])) { |
| 2600 | // CRM-17718 the campaign id on the contribution recur record should get precedence. |
| 2601 | $contributionParams['campaign_id'] = $recurringContribution['campaign_id']; |
| 2602 | } |
| 2603 | if (!empty($recurringContribution['financial_type_id'])) { |
| 2604 | // CRM-17718 the campaign id on the contribution recur record should get precedence. |
| 2605 | $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id']; |
| 2606 | } |
| 2607 | } |
| 2608 | $templateContribution = CRM_Contribute_BAO_ContributionRecur::getTemplateContribution( |
| 2609 | $contributionParams['contribution_recur_id'], |
| 2610 | array_intersect_key($contributionParams, [ |
| 2611 | 'total_amount' => TRUE, |
| 2612 | 'financial_type_id' => TRUE, |
| 2613 | ]) |
| 2614 | ); |
| 2615 | $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item']; |
| 2616 | $contributionParams['status_id'] = 'Pending'; |
| 2617 | |
| 2618 | if (isset($contributionParams['financial_type_id']) && count($input['line_item']) === 1) { |
| 2619 | // We permit the financial type to be overridden for single line items. |
| 2620 | // More comments on this are in getTemplateTransaction. |
| 2621 | $contribution->financial_type_id = $contributionParams['financial_type_id']; |
| 2622 | } |
| 2623 | else { |
| 2624 | $contributionParams['financial_type_id'] = $templateContribution['financial_type_id']; |
| 2625 | } |
| 2626 | foreach (['contact_id', 'currency', 'source'] as $fieldName) { |
| 2627 | $contributionParams[$fieldName] = $templateContribution[$fieldName]; |
| 2628 | } |
| 2629 | |
| 2630 | $contributionParams['source'] = $contributionParams['source'] ?: ts('Recurring contribution'); |
| 2631 | |
| 2632 | //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments |
| 2633 | //do not create CC or BCC emails or profile notifications. |
| 2634 | //The if is just to be safe. Not sure if we can ever arrive with this unset |
| 2635 | // but per CRM-19478 it seems it can be 'null' |
| 2636 | if (isset($contribution->contribution_page_id) && is_numeric($contribution->contribution_page_id)) { |
| 2637 | $contributionParams['contribution_page_id'] = $contribution->contribution_page_id; |
| 2638 | } |
| 2639 | if (!empty($contribution->tax_amount)) { |
| 2640 | $contributionParams['tax_amount'] = $contribution->tax_amount; |
| 2641 | } |
| 2642 | |
| 2643 | $createContribution = civicrm_api3('Contribution', 'create', $contributionParams); |
| 2644 | $contribution->id = $createContribution['id']; |
| 2645 | $contribution->copyCustomFields($templateContribution['id'], $contribution->id); |
| 2646 | self::handleMembershipIDOverride($contribution->id, $input); |
| 2647 | return $createContribution; |
| 2648 | } |
| 2649 | } |
| 2650 | |
| 2651 | /** |
| 2652 | * Get individual id for onbehalf contribution. |
| 2653 | * |
| 2654 | * @param int $contributionId |
| 2655 | * Contribution id. |
| 2656 | * @param int $contributorId |
| 2657 | * Contributor id. |
| 2658 | * |
| 2659 | * @return array |
| 2660 | * containing organization id and individual id |
| 2661 | */ |
| 2662 | public static function getOnbehalfIds($contributionId, $contributorId = NULL) { |
| 2663 | |
| 2664 | $ids = []; |
| 2665 | |
| 2666 | if (!$contributionId) { |
| 2667 | return $ids; |
| 2668 | } |
| 2669 | |
| 2670 | // fetch contributor id if null |
| 2671 | if (!$contributorId) { |
| 2672 | $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', |
| 2673 | $contributionId, 'contact_id' |
| 2674 | ); |
| 2675 | } |
| 2676 | |
| 2677 | $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name'); |
| 2678 | $activityTypeId = array_search('Contribution', $activityTypeIds); |
| 2679 | |
| 2680 | if ($activityTypeId && $contributorId) { |
| 2681 | $activityQuery = " |
| 2682 | SELECT civicrm_activity_contact.contact_id |
| 2683 | FROM civicrm_activity_contact |
| 2684 | INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id |
| 2685 | WHERE civicrm_activity.activity_type_id = %1 |
| 2686 | AND civicrm_activity.source_record_id = %2 |
| 2687 | AND civicrm_activity_contact.record_type_id = %3 |
| 2688 | "; |
| 2689 | |
| 2690 | $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate'); |
| 2691 | $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); |
| 2692 | |
| 2693 | $params = [ |
| 2694 | 1 => [$activityTypeId, 'Integer'], |
| 2695 | 2 => [$contributionId, 'Integer'], |
| 2696 | 3 => [$sourceID, 'Integer'], |
| 2697 | ]; |
| 2698 | |
| 2699 | $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params); |
| 2700 | |
| 2701 | // for on behalf contribution source is individual and contributor is organization |
| 2702 | if ($sourceContactId && $sourceContactId != $contributorId) { |
| 2703 | $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name'); |
| 2704 | // get rel type id for employee of relation |
| 2705 | foreach ($relationshipTypeIds as $id => $typeVals) { |
| 2706 | if ($typeVals['name_a_b'] == 'Employee of') { |
| 2707 | $relationshipTypeId = $id; |
| 2708 | break; |
| 2709 | } |
| 2710 | } |
| 2711 | |
| 2712 | $rel = new CRM_Contact_DAO_Relationship(); |
| 2713 | $rel->relationship_type_id = $relationshipTypeId; |
| 2714 | $rel->contact_id_a = $sourceContactId; |
| 2715 | $rel->contact_id_b = $contributorId; |
| 2716 | if ($rel->find(TRUE)) { |
| 2717 | $ids['individual_id'] = $rel->contact_id_a; |
| 2718 | $ids['organization_id'] = $rel->contact_id_b; |
| 2719 | } |
| 2720 | } |
| 2721 | } |
| 2722 | |
| 2723 | return $ids; |
| 2724 | } |
| 2725 | |
| 2726 | /** |
| 2727 | * @return array |
| 2728 | */ |
| 2729 | public static function getContributionDates() { |
| 2730 | $config = CRM_Core_Config::singleton(); |
| 2731 | $currentMonth = date('m'); |
| 2732 | $currentDay = date('d'); |
| 2733 | if ((int ) $config->fiscalYearStart['M'] > $currentMonth || |
| 2734 | ((int ) $config->fiscalYearStart['M'] == $currentMonth && |
| 2735 | (int ) $config->fiscalYearStart['d'] > $currentDay |
| 2736 | ) |
| 2737 | ) { |
| 2738 | $year = date('Y') - 1; |
| 2739 | } |
| 2740 | else { |
| 2741 | $year = date('Y'); |
| 2742 | } |
| 2743 | $year = ['Y' => $year]; |
| 2744 | $yearDate = $config->fiscalYearStart; |
| 2745 | $yearDate = array_merge($year, $yearDate); |
| 2746 | $yearDate = CRM_Utils_Date::format($yearDate); |
| 2747 | |
| 2748 | $monthDate = date('Ym') . '01'; |
| 2749 | |
| 2750 | $now = date('Ymd'); |
| 2751 | |
| 2752 | return [ |
| 2753 | 'now' => $now, |
| 2754 | 'yearDate' => $yearDate, |
| 2755 | 'monthDate' => $monthDate, |
| 2756 | ]; |
| 2757 | } |
| 2758 | |
| 2759 | /** |
| 2760 | * Load objects relations to contribution object. |
| 2761 | * Objects are stored in the $_relatedObjects property |
| 2762 | * In the first instance we are just moving functionality from BASEIpn - |
| 2763 | * |
| 2764 | * @see http://issues.civicrm.org/jira/browse/CRM-9996 |
| 2765 | * |
| 2766 | * Note that the unit test for the BaseIPN class tests this function |
| 2767 | * |
| 2768 | * @param array $input |
| 2769 | * Input as delivered from Payment Processor. |
| 2770 | * @param array $ids |
| 2771 | * Ids as Loaded by Payment Processor. |
| 2772 | * @param bool $loadAll |
| 2773 | * Load all related objects - even where id not passed in? (allows API to call this). |
| 2774 | * |
| 2775 | * @return bool |
| 2776 | * @throws Exception |
| 2777 | */ |
| 2778 | public function loadRelatedObjects($input, &$ids, $loadAll = FALSE) { |
| 2779 | // @todo deprecate this function - the steps should be |
| 2780 | // 1) add additional functions like 'getRelatedMemberships' |
| 2781 | // 2) switch all calls that refer to ->_relatedObjects to |
| 2782 | // using the helper functions |
| 2783 | // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm |
| 2784 | // 4) make ->_relatedObjects protected |
| 2785 | // 5) hone up the individual functions to not use rely on this having been called |
| 2786 | // 6) deprecate like mad |
| 2787 | if ($loadAll) { |
| 2788 | $ids = array_merge($this->getComponentDetails($this->id), $ids); |
| 2789 | if (empty($ids['contact']) && isset($this->contact_id)) { |
| 2790 | $ids['contact'] = $this->contact_id; |
| 2791 | } |
| 2792 | } |
| 2793 | if (empty($this->_component)) { |
| 2794 | if (!empty($ids['event'])) { |
| 2795 | $this->_component = 'event'; |
| 2796 | } |
| 2797 | else { |
| 2798 | $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute')); |
| 2799 | } |
| 2800 | } |
| 2801 | |
| 2802 | // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious |
| 2803 | // refactoring than anything else, and has unit test coverage. |
| 2804 | if (empty($this->financial_type_id)) { |
| 2805 | $this->find(TRUE); |
| 2806 | } |
| 2807 | |
| 2808 | $paymentProcessorID = CRM_Utils_Array::value('payment_processor_id', $input, CRM_Utils_Array::value( |
| 2809 | 'paymentProcessor', |
| 2810 | $ids |
| 2811 | )); |
| 2812 | |
| 2813 | if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id) { |
| 2814 | $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', |
| 2815 | $this->contribution_page_id, |
| 2816 | 'payment_processor' |
| 2817 | ); |
| 2818 | if ($paymentProcessorID) { |
| 2819 | $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage; |
| 2820 | } |
| 2821 | } |
| 2822 | |
| 2823 | $ids['contributionType'] = $this->financial_type_id; |
| 2824 | $ids['financialType'] = $this->financial_type_id; |
| 2825 | if ($this->contribution_page_id) { |
| 2826 | $ids['contributionPage'] = $this->contribution_page_id; |
| 2827 | } |
| 2828 | |
| 2829 | $this->loadRelatedEntitiesByID($ids); |
| 2830 | |
| 2831 | if (!empty($ids['contributionRecur']) && !$paymentProcessorID) { |
| 2832 | $paymentProcessorID = $this->_relatedObjects['contributionRecur']->payment_processor_id; |
| 2833 | } |
| 2834 | |
| 2835 | if (!empty($ids['pledge_payment'])) { |
| 2836 | foreach ($ids['pledge_payment'] as $key => $paymentID) { |
| 2837 | if (empty($paymentID)) { |
| 2838 | continue; |
| 2839 | } |
| 2840 | $payment = new CRM_Pledge_BAO_PledgePayment(); |
| 2841 | $payment->id = $paymentID; |
| 2842 | if (!$payment->find(TRUE)) { |
| 2843 | throw new Exception("Could not find pledge payment record: " . $paymentID); |
| 2844 | } |
| 2845 | $this->_relatedObjects['pledge_payment'][] = $payment; |
| 2846 | } |
| 2847 | } |
| 2848 | |
| 2849 | // These are probably no longer accessed from anywhere |
| 2850 | // @todo remove this line, after ensuring not used. |
| 2851 | $ids = $this->loadRelatedMembershipObjects($ids); |
| 2852 | |
| 2853 | if ($this->_component != 'contribute') { |
| 2854 | // we are in event mode |
| 2855 | // make sure event exists and is valid |
| 2856 | $event = new CRM_Event_BAO_Event(); |
| 2857 | $event->id = $ids['event']; |
| 2858 | if ($ids['event'] && |
| 2859 | !$event->find(TRUE) |
| 2860 | ) { |
| 2861 | throw new Exception("Could not find event: " . $ids['event']); |
| 2862 | } |
| 2863 | |
| 2864 | $this->_relatedObjects['event'] = &$event; |
| 2865 | |
| 2866 | $participant = new CRM_Event_BAO_Participant(); |
| 2867 | $participant->id = $ids['participant']; |
| 2868 | if ($ids['participant'] && |
| 2869 | !$participant->find(TRUE) |
| 2870 | ) { |
| 2871 | throw new Exception("Could not find participant: " . $ids['participant']); |
| 2872 | } |
| 2873 | $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date); |
| 2874 | |
| 2875 | $this->_relatedObjects['participant'] = &$participant; |
| 2876 | |
| 2877 | // get the payment processor id from event - this is inaccurate see CRM-16923 |
| 2878 | // in future we should look at throwing an exception here rather than an dubious guess. |
| 2879 | if (!$paymentProcessorID) { |
| 2880 | $paymentProcessorID = $this->_relatedObjects['event']->payment_processor; |
| 2881 | if ($paymentProcessorID) { |
| 2882 | $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent; |
| 2883 | } |
| 2884 | } |
| 2885 | } |
| 2886 | |
| 2887 | $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds($this->id); |
| 2888 | if (!empty($relatedContact['individual_id'])) { |
| 2889 | $ids['related_contact'] = $relatedContact['individual_id']; |
| 2890 | } |
| 2891 | |
| 2892 | if ($paymentProcessorID) { |
| 2893 | $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID, |
| 2894 | $this->is_test ? 'test' : 'live' |
| 2895 | ); |
| 2896 | $ids['paymentProcessor'] = $paymentProcessorID; |
| 2897 | $this->_relatedObjects['paymentProcessor'] = $paymentProcessor; |
| 2898 | } |
| 2899 | |
| 2900 | // Add contribution id to $ids. CRM-20401 |
| 2901 | $ids['contribution'] = $this->id; |
| 2902 | return TRUE; |
| 2903 | } |
| 2904 | |
| 2905 | /** |
| 2906 | * Create array of message information - ie. return html version, txt version, to field |
| 2907 | * |
| 2908 | * @param array $input |
| 2909 | * Incoming information. |
| 2910 | * - is_recur - should this be treated as recurring (not sure why you wouldn't |
| 2911 | * just check presence of recur object but maintaining legacy approach |
| 2912 | * to be careful) |
| 2913 | * @param array $ids |
| 2914 | * IDs of related objects. |
| 2915 | * @param array $values |
| 2916 | * Any values that may have already been compiled by calling process. |
| 2917 | * This is augmented by values 'gathered' by gatherMessageValues |
| 2918 | * @param bool $returnMessageText |
| 2919 | * Distinguishes between whether to send message or return. |
| 2920 | * message text. We are working towards this function ALWAYS returning message text & calling |
| 2921 | * function doing emails / pdfs with it |
| 2922 | * |
| 2923 | * @return array |
| 2924 | * messages |
| 2925 | * @throws Exception |
| 2926 | */ |
| 2927 | public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) { |
| 2928 | $this->loadRelatedObjects($input, $ids); |
| 2929 | |
| 2930 | if (empty($this->_component)) { |
| 2931 | $this->_component = $input['component'] ?? NULL; |
| 2932 | } |
| 2933 | |
| 2934 | //not really sure what params might be passed in but lets merge em into values |
| 2935 | $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values); |
| 2936 | $values['is_email_receipt'] = !$returnMessageText; |
| 2937 | if (!empty($input['receipt_date'])) { |
| 2938 | $values['receipt_date'] = $input['receipt_date']; |
| 2939 | } |
| 2940 | |
| 2941 | $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText); |
| 2942 | //what does recur 'mean here - to do with payment processor return functionality but |
| 2943 | // what is the importance |
| 2944 | if (!empty($this->contribution_recur_id) && !empty($this->_relatedObjects['paymentProcessor'])) { |
| 2945 | $paymentObject = Civi\Payment\System::singleton()->getByProcessor($this->_relatedObjects['paymentProcessor']); |
| 2946 | |
| 2947 | $entityID = $entity = NULL; |
| 2948 | if (isset($ids['contribution'])) { |
| 2949 | $entity = 'contribution'; |
| 2950 | $entityID = $ids['contribution']; |
| 2951 | } |
| 2952 | if (!empty($ids['membership'])) { |
| 2953 | //not sure whether is is possible for this not to be an array - load related contacts loads an array but this code was expecting a string |
| 2954 | // the addition of the casting is in case it could get here & be a string. Added in 4.6 - maybe remove later? This AuthorizeNetIPN & PaypalIPN tests hit this |
| 2955 | // line having loaded an array |
| 2956 | $ids['membership'] = (array) $ids['membership']; |
| 2957 | $entity = 'membership'; |
| 2958 | $entityID = $ids['membership'][0]; |
| 2959 | } |
| 2960 | |
| 2961 | $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel')); |
| 2962 | $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing')); |
| 2963 | $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update')); |
| 2964 | |
| 2965 | if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) { |
| 2966 | //direct mode showing billing block, so use directIPN for temporary |
| 2967 | $template->assign('contributeMode', 'directIPN'); |
| 2968 | } |
| 2969 | } |
| 2970 | // todo remove strtolower - check consistency |
| 2971 | if (strtolower($this->_component) == 'event') { |
| 2972 | $eventParams = ['id' => $this->_relatedObjects['participant']->event_id]; |
| 2973 | $values['event'] = []; |
| 2974 | |
| 2975 | CRM_Event_BAO_Event::retrieve($eventParams, $values['event']); |
| 2976 | |
| 2977 | //get location details |
| 2978 | $locationParams = [ |
| 2979 | 'entity_id' => $this->_relatedObjects['participant']->event_id, |
| 2980 | 'entity_table' => 'civicrm_event', |
| 2981 | ]; |
| 2982 | $values['location'] = CRM_Core_BAO_Location::getValues($locationParams); |
| 2983 | |
| 2984 | $ufJoinParams = [ |
| 2985 | 'entity_table' => 'civicrm_event', |
| 2986 | 'entity_id' => $ids['event'], |
| 2987 | 'module' => 'CiviEvent', |
| 2988 | ]; |
| 2989 | |
| 2990 | list($custom_pre_id, |
| 2991 | $custom_post_ids |
| 2992 | ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); |
| 2993 | |
| 2994 | $values['custom_pre_id'] = $custom_pre_id; |
| 2995 | $values['custom_post_id'] = $custom_post_ids; |
| 2996 | //for tasks 'Change Participant Status' and 'Update multiple Contributions' case |
| 2997 | //and cases involving status updation through ipn |
| 2998 | // whatever that means! |
| 2999 | // total_amount appears to be the preferred input param & it is unclear why we support amount here |
| 3000 | // perhaps we should throw an e-notice if amount is set & force total_amount? |
| 3001 | if (!empty($input['amount'])) { |
| 3002 | $values['totalAmount'] = $input['amount']; |
| 3003 | } |
| 3004 | // @todo set this in is_email_receipt, based on $this->_relatedObjects. |
| 3005 | if ($values['event']['is_email_confirm']) { |
| 3006 | $values['is_email_receipt'] = 1; |
| 3007 | } |
| 3008 | |
| 3009 | if (!empty($ids['contribution'])) { |
| 3010 | $values['contributionId'] = $ids['contribution']; |
| 3011 | } |
| 3012 | |
| 3013 | return CRM_Event_BAO_Event::sendMail($ids['contact'], $values, |
| 3014 | $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText |
| 3015 | ); |
| 3016 | } |
| 3017 | else { |
| 3018 | $values['contribution_id'] = $this->id; |
| 3019 | if (!empty($ids['related_contact'])) { |
| 3020 | $values['related_contact'] = $ids['related_contact']; |
| 3021 | if (isset($ids['onbehalf_dupe_alert'])) { |
| 3022 | $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert']; |
| 3023 | } |
| 3024 | $entityBlock = [ |
| 3025 | 'contact_id' => $ids['contact'], |
| 3026 | 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', |
| 3027 | 'Home', 'id', 'name' |
| 3028 | ), |
| 3029 | ]; |
| 3030 | $address = CRM_Core_BAO_Address::getValues($entityBlock); |
| 3031 | $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']); |
| 3032 | } |
| 3033 | $isTest = FALSE; |
| 3034 | if ($this->is_test) { |
| 3035 | $isTest = TRUE; |
| 3036 | } |
| 3037 | if (!empty($this->_relatedObjects['membership'])) { |
| 3038 | foreach ($this->_relatedObjects['membership'] as $membership) { |
| 3039 | if ($membership->id) { |
| 3040 | $values['membership_id'] = $membership->id; |
| 3041 | $values['isMembership'] = TRUE; |
| 3042 | $values['membership_assign'] = TRUE; |
| 3043 | |
| 3044 | // need to set the membership values here |
| 3045 | $template->assign('membership_name', |
| 3046 | CRM_Member_PseudoConstant::membershipType($membership->membership_type_id) |
| 3047 | ); |
| 3048 | $template->assign('mem_start_date', $membership->start_date); |
| 3049 | $template->assign('mem_join_date', $membership->join_date); |
| 3050 | $template->assign('mem_end_date', $membership->end_date); |
| 3051 | $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label'); |
| 3052 | $template->assign('mem_status', $membership_status); |
| 3053 | if ($membership_status == 'Pending' && $membership->is_pay_later == 1) { |
| 3054 | $values['is_pay_later'] = 1; |
| 3055 | } |
| 3056 | // Pass amount to floatval as string '0.00' is considered a |
| 3057 | // valid amount and includes Fee section in the mail. |
| 3058 | if (isset($values['amount'])) { |
| 3059 | $values['amount'] = floatval($values['amount']); |
| 3060 | } |
| 3061 | |
| 3062 | if (!empty($this->contribution_recur_id) && $paymentObject) { |
| 3063 | $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'cancel'); |
| 3064 | $template->assign('cancelSubscriptionUrl', $url); |
| 3065 | $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing'); |
| 3066 | $template->assign('updateSubscriptionBillingUrl', $url); |
| 3067 | $url = $paymentObject->subscriptionURL($entityID, $entity, 'update'); |
| 3068 | $template->assign('updateSubscriptionUrl', $url); |
| 3069 | } |
| 3070 | |
| 3071 | $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText); |
| 3072 | |
| 3073 | return $result; |
| 3074 | // otherwise if its about sending emails, continue sending without return, as we |
| 3075 | // don't want to exit the loop. |
| 3076 | } |
| 3077 | } |
| 3078 | } |
| 3079 | else { |
| 3080 | return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText); |
| 3081 | } |
| 3082 | } |
| 3083 | } |
| 3084 | |
| 3085 | /** |
| 3086 | * Gather values for contribution mail - this function has been created |
| 3087 | * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function |
| 3088 | * Values related to the contribution in question are gathered |
| 3089 | * |
| 3090 | * @param array $input |
| 3091 | * Input into function (probably from payment processor). |
| 3092 | * @param array $values |
| 3093 | * @param array $ids |
| 3094 | * The set of ids related to the input. |
| 3095 | * |
| 3096 | * @return array |
| 3097 | * @throws \CRM_Core_Exception |
| 3098 | */ |
| 3099 | public function _gatherMessageValues($input, &$values, $ids = []) { |
| 3100 | // set display address of contributor |
| 3101 | $values['billingName'] = ''; |
| 3102 | if ($this->address_id) { |
| 3103 | $addressDetails = CRM_Core_BAO_Address::getValues(['id' => $this->address_id], FALSE, 'id'); |
| 3104 | $addressDetails = reset($addressDetails); |
| 3105 | $values['billingName'] = $addressDetails['name'] ?? ''; |
| 3106 | } |
| 3107 | // Else we assign the billing address of the contribution contact. |
| 3108 | else { |
| 3109 | $addressDetails = (array) CRM_Core_BAO_Address::getValues(['contact_id' => $this->contact_id, 'is_billing' => 1]); |
| 3110 | $addressDetails = reset($addressDetails); |
| 3111 | } |
| 3112 | $values['address'] = $addressDetails['display'] ?? ''; |
| 3113 | |
| 3114 | if ($this->_component === 'contribute') { |
| 3115 | //get soft contributions |
| 3116 | $softContributions = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id, TRUE); |
| 3117 | if (!empty($softContributions)) { |
| 3118 | // For pcp soft credit, there is no 'soft_credit' member it comes |
| 3119 | // back in different array members, but shortly after returning from |
| 3120 | // this function it calls _assignMessageVariablesToTemplate which does |
| 3121 | // its own lookup of any pcp soft credit, so we can skip it here. |
| 3122 | $values['softContributions'] = $softContributions['soft_credit'] ?? NULL; |
| 3123 | } |
| 3124 | if (isset($this->contribution_page_id)) { |
| 3125 | // This is a call we want to use less, in favour of loading related objects. |
| 3126 | $values = $this->addContributionPageValuesToValuesHeavyHandedly($values); |
| 3127 | if ($this->contribution_page_id) { |
| 3128 | // This is precautionary as there are some legacy flows, but it should really be |
| 3129 | // loaded by now. |
| 3130 | if (!isset($this->_relatedObjects['contributionPage'])) { |
| 3131 | $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id]); |
| 3132 | } |
| 3133 | CRM_Contribute_BAO_Contribution_Utils::overrideDefaultCurrency($values); |
| 3134 | } |
| 3135 | } |
| 3136 | // no contribution page -probably back office |
| 3137 | else { |
| 3138 | // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id) |
| 3139 | $values['title'] = 'Contribution'; |
| 3140 | } |
| 3141 | // set lineItem for contribution |
| 3142 | if ($this->id) { |
| 3143 | $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($this->id); |
| 3144 | if (!empty($lineItems)) { |
| 3145 | $firstLineItem = reset($lineItems); |
| 3146 | $priceSet = []; |
| 3147 | if (!empty($firstLineItem['price_set_id'])) { |
| 3148 | $priceSet = civicrm_api3('PriceSet', 'getsingle', [ |
| 3149 | 'id' => $firstLineItem['price_set_id'], |
| 3150 | 'return' => 'is_quick_config, id', |
| 3151 | ]); |
| 3152 | $values['priceSetID'] = $priceSet['id']; |
| 3153 | } |
| 3154 | foreach ($lineItems as &$eachItem) { |
| 3155 | if (isset($this->_relatedObjects['membership']) |
| 3156 | && is_array($this->_relatedObjects['membership']) |
| 3157 | && array_key_exists($eachItem['entity_id'] . '_' . $eachItem['membership_type_id'], $this->_relatedObjects['membership'])) { |
| 3158 | $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->join_date); |
| 3159 | $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->start_date); |
| 3160 | $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->end_date); |
| 3161 | } |
| 3162 | // This is actually used in conjunction with is_quick_config in the template & we should deprecate it. |
| 3163 | // However, that does create upgrade pain so would be better to be phased in. |
| 3164 | $values['useForMember'] = empty($priceSet['is_quick_config']); |
| 3165 | } |
| 3166 | $values['lineItem'][0] = $lineItems; |
| 3167 | } |
| 3168 | } |
| 3169 | |
| 3170 | $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds( |
| 3171 | $this->id, |
| 3172 | $this->contact_id |
| 3173 | ); |
| 3174 | // if this is onbehalf of contribution then set related contact |
| 3175 | if (!empty($relatedContact['individual_id'])) { |
| 3176 | $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id']; |
| 3177 | } |
| 3178 | } |
| 3179 | else { |
| 3180 | $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects['participant']->id, $this->id)); |
| 3181 | } |
| 3182 | |
| 3183 | $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', NULL, $this->id); |
| 3184 | |
| 3185 | $customGroup = []; |
| 3186 | foreach ($groupTree as $key => $group) { |
| 3187 | if ($key === 'info') { |
| 3188 | continue; |
| 3189 | } |
| 3190 | |
| 3191 | foreach ($group['fields'] as $k => $customField) { |
| 3192 | $groupLabel = $group['title']; |
| 3193 | if (!empty($customField['customValue'])) { |
| 3194 | foreach ($customField['customValue'] as $customFieldValues) { |
| 3195 | $customGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ?? NULL; |
| 3196 | } |
| 3197 | } |
| 3198 | } |
| 3199 | } |
| 3200 | $values['customGroup'] = $customGroup; |
| 3201 | |
| 3202 | $values['is_pay_later'] = $this->is_pay_later; |
| 3203 | |
| 3204 | return $values; |
| 3205 | } |
| 3206 | |
| 3207 | /** |
| 3208 | * Assign message variables to template but try to break the habit. |
| 3209 | * |
| 3210 | * In order to get away from leaky variables it is better to ensure variables are set in values and assign them |
| 3211 | * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing |
| 3212 | * multiple recurring payments for processors like IATS that use tokens. |
| 3213 | * |
| 3214 | * Apply variables for message to smarty template - this function is part of analysing what is in the huge |
| 3215 | * function & breaking it down into manageable chunks. Eventually it will be refactored into something else |
| 3216 | * Note we send directly from this function in some cases because it is only partly refactored. |
| 3217 | * |
| 3218 | * Don't call this function directly as the signature will change. |
| 3219 | * |
| 3220 | * @param $values |
| 3221 | * @param $input |
| 3222 | * @param bool $returnMessageText |
| 3223 | * |
| 3224 | * @return mixed |
| 3225 | */ |
| 3226 | public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) { |
| 3227 | // @todo - this should have a better separation of concerns - ie. |
| 3228 | // gatherMessageValues should build an array of values to be assigned to the template |
| 3229 | // and this function should assign them (assigning null if not set). |
| 3230 | // the way the pcpParams & honor Params section works is a baby-step towards this. |
| 3231 | $template = CRM_Core_Smarty::singleton(); |
| 3232 | $template->assign('first_name', $this->_relatedObjects['contact']->first_name); |
| 3233 | $template->assign('last_name', $this->_relatedObjects['contact']->last_name); |
| 3234 | $template->assign('displayName', $this->_relatedObjects['contact']->display_name); |
| 3235 | $template->assign('billingName', $values['billingName']); |
| 3236 | |
| 3237 | // For some unit tests contribution cannot contain paymentProcessor information |
| 3238 | $billingMode = empty($this->_relatedObjects['paymentProcessor']) ? CRM_Core_Payment::BILLING_MODE_NOTIFY : $this->_relatedObjects['paymentProcessor']['billing_mode']; |
| 3239 | $template->assign('contributeMode', CRM_Core_SelectValues::contributeMode()[$billingMode] ?? NULL); |
| 3240 | |
| 3241 | //assign honor information to receipt message |
| 3242 | $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id); |
| 3243 | |
| 3244 | $honorParams = [ |
| 3245 | 'soft_credit_type' => NULL, |
| 3246 | 'honor_block_is_active' => NULL, |
| 3247 | ]; |
| 3248 | if (isset($softRecord['soft_credit'])) { |
| 3249 | //if id of contribution page is present |
| 3250 | if (!empty($values['id'])) { |
| 3251 | $values['honor'] = [ |
| 3252 | 'honor_profile_values' => [], |
| 3253 | 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'), |
| 3254 | 'honor_id' => $softRecord['soft_credit'][1]['contact_id'], |
| 3255 | ]; |
| 3256 | |
| 3257 | $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label']; |
| 3258 | $honorParams['honor_block_is_active'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'); |
| 3259 | } |
| 3260 | else { |
| 3261 | //offline contribution |
| 3262 | $softCreditTypes = $softCredits = []; |
| 3263 | foreach ($softRecord['soft_credit'] as $key => $softCredit) { |
| 3264 | $softCreditTypes[$key] = $softCredit['soft_credit_type_label']; |
| 3265 | $softCredits[$key] = [ |
| 3266 | 'Name' => $softCredit['contact_name'], |
| 3267 | 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']), |
| 3268 | ]; |
| 3269 | } |
| 3270 | $template->assign('softCreditTypes', $softCreditTypes); |
| 3271 | $template->assign('softCredits', $softCredits); |
| 3272 | } |
| 3273 | } |
| 3274 | |
| 3275 | $dao = new CRM_Contribute_DAO_ContributionProduct(); |
| 3276 | $dao->contribution_id = $this->id; |
| 3277 | if ($dao->find(TRUE)) { |
| 3278 | $premiumId = $dao->product_id; |
| 3279 | $template->assign('option', $dao->product_option); |
| 3280 | |
| 3281 | $productDAO = new CRM_Contribute_DAO_Product(); |
| 3282 | $productDAO->id = $premiumId; |
| 3283 | $productDAO->find(TRUE); |
| 3284 | $template->assign('selectPremium', TRUE); |
| 3285 | $template->assign('product_name', $productDAO->name); |
| 3286 | $template->assign('price', $productDAO->price); |
| 3287 | $template->assign('sku', $productDAO->sku); |
| 3288 | } |
| 3289 | $template->assign('title', $values['title'] ?? NULL); |
| 3290 | $values['amount'] = CRM_Utils_Array::value('total_amount', $input, (CRM_Utils_Array::value('amount', $input)), NULL); |
| 3291 | if (!$values['amount'] && isset($this->total_amount)) { |
| 3292 | $values['amount'] = $this->total_amount; |
| 3293 | } |
| 3294 | |
| 3295 | $pcpParams = [ |
| 3296 | 'pcpBlock' => NULL, |
| 3297 | 'pcp_display_in_roll' => NULL, |
| 3298 | 'pcp_roll_nickname' => NULL, |
| 3299 | 'pcp_personal_note' => NULL, |
| 3300 | 'title' => NULL, |
| 3301 | ]; |
| 3302 | |
| 3303 | if (strtolower($this->_component) == 'contribute') { |
| 3304 | //PCP Info |
| 3305 | $softDAO = new CRM_Contribute_DAO_ContributionSoft(); |
| 3306 | $softDAO->contribution_id = $this->id; |
| 3307 | if ($softDAO->find(TRUE)) { |
| 3308 | $pcpParams['pcpBlock'] = TRUE; |
| 3309 | $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll; |
| 3310 | $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname; |
| 3311 | $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note; |
| 3312 | |
| 3313 | //assign the pcp page title for email subject |
| 3314 | $pcpDAO = new CRM_PCP_DAO_PCP(); |
| 3315 | $pcpDAO->id = $softDAO->pcp_id; |
| 3316 | if ($pcpDAO->find(TRUE)) { |
| 3317 | $pcpParams['title'] = $pcpDAO->title; |
| 3318 | } |
| 3319 | } |
| 3320 | } |
| 3321 | foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) { |
| 3322 | $template->assign($templateKey, $templateValue); |
| 3323 | } |
| 3324 | |
| 3325 | if ($this->financial_type_id) { |
| 3326 | $values['financial_type_id'] = $this->financial_type_id; |
| 3327 | } |
| 3328 | |
| 3329 | $template->assign('trxn_id', $this->trxn_id); |
| 3330 | $template->assign('receive_date', |
| 3331 | CRM_Utils_Date::processDate($this->receive_date) |
| 3332 | ); |
| 3333 | $values['receipt_date'] = (empty($this->receipt_date) ? NULL : $this->receipt_date); |
| 3334 | $template->assign('action', $this->is_test ? 1024 : 1); |
| 3335 | $template->assign('receipt_text', $values['receipt_text'] ?? NULL); |
| 3336 | $template->assign('is_monetary', 1); |
| 3337 | $template->assign('is_recur', !empty($this->contribution_recur_id)); |
| 3338 | $template->assign('currency', $this->currency); |
| 3339 | $template->assign('address', CRM_Utils_Address::format($input)); |
| 3340 | if (!empty($values['customGroup'])) { |
| 3341 | $template->assign('customGroup', $values['customGroup']); |
| 3342 | } |
| 3343 | if (!empty($values['softContributions'])) { |
| 3344 | $template->assign('softContributions', $values['softContributions']); |
| 3345 | } |
| 3346 | if ($this->_component == 'event') { |
| 3347 | $template->assign('title', $values['event']['title']); |
| 3348 | $participantRoles = CRM_Event_PseudoConstant::participantRole(); |
| 3349 | $viewRoles = []; |
| 3350 | foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) { |
| 3351 | $viewRoles[] = $participantRoles[$v]; |
| 3352 | } |
| 3353 | $values['event']['participant_role'] = implode(', ', $viewRoles); |
| 3354 | $template->assign('event', $values['event']); |
| 3355 | $template->assign('participant', $values['participant']); |
| 3356 | $template->assign('location', $values['location']); |
| 3357 | $template->assign('customPre', $values['custom_pre_id']); |
| 3358 | $template->assign('customPost', $values['custom_post_id']); |
| 3359 | |
| 3360 | $isTest = FALSE; |
| 3361 | if ($this->_relatedObjects['participant']->is_test) { |
| 3362 | $isTest = TRUE; |
| 3363 | } |
| 3364 | |
| 3365 | $values['params'] = []; |
| 3366 | //to get email of primary participant. |
| 3367 | $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id'); |
| 3368 | $primaryAmount[] = [ |
| 3369 | 'label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail, |
| 3370 | 'amount' => $this->_relatedObjects['participant']->fee_amount, |
| 3371 | ]; |
| 3372 | //build an array of cId/pId of participants |
| 3373 | $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE); |
| 3374 | unset($additionalIDs[$this->_relatedObjects['participant']->id]); |
| 3375 | //send receipt to additional participant if exists |
| 3376 | if (count($additionalIDs)) { |
| 3377 | $template->assign('isPrimary', 0); |
| 3378 | $template->assign('customProfile', NULL); |
| 3379 | //set additionalParticipant true |
| 3380 | $values['params']['additionalParticipant'] = TRUE; |
| 3381 | foreach ($additionalIDs as $pId => $cId) { |
| 3382 | $amount = []; |
| 3383 | //to change the status pending to completed |
| 3384 | $additional = new CRM_Event_DAO_Participant(); |
| 3385 | $additional->id = $pId; |
| 3386 | $additional->contact_id = $cId; |
| 3387 | $additional->find(TRUE); |
| 3388 | $additional->register_date = $this->_relatedObjects['participant']->register_date; |
| 3389 | $additional->status_id = 1; |
| 3390 | $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id'); |
| 3391 | //if additional participant dont have email |
| 3392 | //use display name. |
| 3393 | if (!$additionalParticipantInfo) { |
| 3394 | $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id); |
| 3395 | } |
| 3396 | $amount[0] = [ |
| 3397 | 'label' => $additional->fee_level, |
| 3398 | 'amount' => $additional->fee_amount, |
| 3399 | ]; |
| 3400 | $primaryAmount[] = [ |
| 3401 | 'label' => $additional->fee_level . ' - ' . $additionalParticipantInfo, |
| 3402 | 'amount' => $additional->fee_amount, |
| 3403 | ]; |
| 3404 | $additional->save(); |
| 3405 | $template->assign('amount', $amount); |
| 3406 | CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText); |
| 3407 | } |
| 3408 | } |
| 3409 | |
| 3410 | //build an array of custom profile and assigning it to template |
| 3411 | $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest); |
| 3412 | |
| 3413 | if (count($customProfile)) { |
| 3414 | $template->assign('customProfile', $customProfile); |
| 3415 | } |
| 3416 | |
| 3417 | // for primary contact |
| 3418 | $values['params']['additionalParticipant'] = FALSE; |
| 3419 | $template->assign('isPrimary', 1); |
| 3420 | $template->assign('amount', $primaryAmount); |
| 3421 | $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date)); |
| 3422 | if ($this->payment_instrument_id) { |
| 3423 | $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); |
| 3424 | $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]); |
| 3425 | } |
| 3426 | // carry paylater, since we did not created billing, |
| 3427 | // so need to pull email from primary location, CRM-4395 |
| 3428 | $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later; |
| 3429 | } |
| 3430 | return $template; |
| 3431 | } |
| 3432 | |
| 3433 | /** |
| 3434 | * Check whether payment processor supports |
| 3435 | * cancellation of contribution subscription |
| 3436 | * |
| 3437 | * @param int $contributionId |
| 3438 | * Contribution id. |
| 3439 | * |
| 3440 | * @param bool $isNotCancelled |
| 3441 | * |
| 3442 | * @return bool |
| 3443 | */ |
| 3444 | public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) { |
| 3445 | $cacheKeyString = "$contributionId"; |
| 3446 | $cacheKeyString .= $isNotCancelled ? '_1' : '_0'; |
| 3447 | |
| 3448 | static $supportsCancel = []; |
| 3449 | |
| 3450 | if (!array_key_exists($cacheKeyString, $supportsCancel)) { |
| 3451 | $supportsCancel[$cacheKeyString] = FALSE; |
| 3452 | $isCancelled = FALSE; |
| 3453 | |
| 3454 | if ($isNotCancelled) { |
| 3455 | $isCancelled = self::isSubscriptionCancelled($contributionId); |
| 3456 | } |
| 3457 | |
| 3458 | $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj'); |
| 3459 | if (!empty($paymentObject)) { |
| 3460 | $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled; |
| 3461 | } |
| 3462 | } |
| 3463 | return $supportsCancel[$cacheKeyString]; |
| 3464 | } |
| 3465 | |
| 3466 | /** |
| 3467 | * Check whether subscription is already cancelled. |
| 3468 | * |
| 3469 | * @param int $contributionId |
| 3470 | * Contribution id. |
| 3471 | * |
| 3472 | * @return string |
| 3473 | * contribution status |
| 3474 | */ |
| 3475 | public static function isSubscriptionCancelled($contributionId) { |
| 3476 | $sql = " |
| 3477 | SELECT cr.contribution_status_id |
| 3478 | FROM civicrm_contribution_recur cr |
| 3479 | LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id ) |
| 3480 | WHERE con.id = %1 LIMIT 1"; |
| 3481 | $params = [1 => [$contributionId, 'Integer']]; |
| 3482 | $statusId = CRM_Core_DAO::singleValueQuery($sql, $params); |
| 3483 | $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId, 'name'); |
| 3484 | if ($status == 'Cancelled') { |
| 3485 | return TRUE; |
| 3486 | } |
| 3487 | return FALSE; |
| 3488 | } |
| 3489 | |
| 3490 | /** |
| 3491 | * Create all financial accounts entry. |
| 3492 | * |
| 3493 | * @param array $params |
| 3494 | * Contribution object, line item array and params for trxn. |
| 3495 | * |
| 3496 | * |
| 3497 | * @param array $financialTrxnValues |
| 3498 | * |
| 3499 | * @return null|\CRM_Core_BAO_FinancialTrxn |
| 3500 | */ |
| 3501 | public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) { |
| 3502 | $skipRecords = $update = $return = $isRelatedId = FALSE; |
| 3503 | $isUpdate = !empty($params['prevContribution']); |
| 3504 | |
| 3505 | $additionalParticipantId = []; |
| 3506 | $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
| 3507 | $contributionStatus = empty($params['contribution_status_id']) ? NULL : $contributionStatuses[$params['contribution_status_id']]; |
| 3508 | |
| 3509 | if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') { |
| 3510 | $entityId = $params['participant_id']; |
| 3511 | $entityTable = 'civicrm_participant'; |
| 3512 | $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId); |
| 3513 | } |
| 3514 | elseif (!empty($params['membership_id'])) { |
| 3515 | //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships |
| 3516 | // are created off one contribution should be handled elsewhere |
| 3517 | $entityId = $params['membership_id']; |
| 3518 | $entityTable = 'civicrm_membership'; |
| 3519 | } |
| 3520 | else { |
| 3521 | $entityId = $params['contribution']->id; |
| 3522 | $entityTable = 'civicrm_contribution'; |
| 3523 | } |
| 3524 | |
| 3525 | if (CRM_Utils_Array::value('contribution_mode', $params) == 'membership') { |
| 3526 | $isRelatedId = TRUE; |
| 3527 | } |
| 3528 | |
| 3529 | $entityID[] = $entityId; |
| 3530 | if (!empty($additionalParticipantId)) { |
| 3531 | $entityID += $additionalParticipantId; |
| 3532 | } |
| 3533 | // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated |
| 3534 | if (empty($params['prevContribution'])) { |
| 3535 | $entityID = NULL; |
| 3536 | } |
| 3537 | |
| 3538 | $statusId = $params['contribution']->contribution_status_id; |
| 3539 | |
| 3540 | // build line item array if its not set in $params |
| 3541 | if (empty($params['line_item']) || $additionalParticipantId) { |
| 3542 | CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId); |
| 3543 | } |
| 3544 | |
| 3545 | if ($contributionStatus != 'Failed' && |
| 3546 | !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later) |
| 3547 | ) { |
| 3548 | $skipRecords = TRUE; |
| 3549 | $pendingStatus = [ |
| 3550 | 'Pending', |
| 3551 | 'In Progress', |
| 3552 | ]; |
| 3553 | if (in_array($contributionStatus, $pendingStatus)) { |
| 3554 | $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship( |
| 3555 | $params['financial_type_id'], |
| 3556 | 'Accounts Receivable Account is' |
| 3557 | ); |
| 3558 | } |
| 3559 | elseif (!empty($params['payment_processor'])) { |
| 3560 | $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor'); |
| 3561 | $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [ |
| 3562 | 'id' => $params['payment_processor'], |
| 3563 | 'return' => 'payment_instrument_id', |
| 3564 | ]); |
| 3565 | } |
| 3566 | elseif (!empty($params['payment_instrument_id'])) { |
| 3567 | $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']); |
| 3568 | } |
| 3569 | else { |
| 3570 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' ")); |
| 3571 | $queryParams = [1 => [$relationTypeId, 'Integer']]; |
| 3572 | $params['to_financial_account_id'] = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams); |
| 3573 | } |
| 3574 | |
| 3575 | $totalAmount = $params['total_amount'] ?? NULL; |
| 3576 | if (!isset($totalAmount) && !empty($params['prevContribution'])) { |
| 3577 | $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount; |
| 3578 | } |
| 3579 | //build financial transaction params |
| 3580 | $trxnParams = [ |
| 3581 | 'contribution_id' => $params['contribution']->id, |
| 3582 | 'to_financial_account_id' => $params['to_financial_account_id'], |
| 3583 | 'trxn_date' => !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis'), |
| 3584 | 'total_amount' => $totalAmount, |
| 3585 | 'fee_amount' => $params['fee_amount'] ?? NULL, |
| 3586 | 'net_amount' => CRM_Utils_Array::value('net_amount', $params, $totalAmount), |
| 3587 | 'currency' => $params['contribution']->currency, |
| 3588 | 'trxn_id' => $params['contribution']->trxn_id, |
| 3589 | // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially |
| 3590 | // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but |
| 3591 | // this should really default to completed (after discussion). |
| 3592 | 'status_id' => $statusId, |
| 3593 | 'payment_instrument_id' => CRM_Utils_Array::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id), |
| 3594 | 'check_number' => $params['check_number'] ?? NULL, |
| 3595 | 'pan_truncation' => $params['pan_truncation'] ?? NULL, |
| 3596 | 'card_type_id' => $params['card_type_id'] ?? NULL, |
| 3597 | ]; |
| 3598 | if ($contributionStatus == 'Refunded' || $contributionStatus == 'Chargeback' || $contributionStatus == 'Cancelled') { |
| 3599 | $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date) ? $params['contribution']->cancel_date : date('YmdHis'); |
| 3600 | if (isset($params['refund_trxn_id'])) { |
| 3601 | // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form. |
| 3602 | $trxnParams['trxn_id'] = $params['refund_trxn_id']; |
| 3603 | } |
| 3604 | } |
| 3605 | //CRM-16259, set is_payment flag for non pending status |
| 3606 | if (!in_array($contributionStatus, $pendingStatus)) { |
| 3607 | $trxnParams['is_payment'] = 1; |
| 3608 | } |
| 3609 | if (!empty($params['payment_processor'])) { |
| 3610 | $trxnParams['payment_processor_id'] = $params['payment_processor']; |
| 3611 | } |
| 3612 | |
| 3613 | if (isset($fromFinancialAccountId)) { |
| 3614 | $trxnParams['from_financial_account_id'] = $fromFinancialAccountId; |
| 3615 | } |
| 3616 | |
| 3617 | // consider external values passed for recording transaction entry |
| 3618 | if (!empty($financialTrxnValues)) { |
| 3619 | $trxnParams = array_merge($trxnParams, $financialTrxnValues); |
| 3620 | } |
| 3621 | if (empty($trxnParams['payment_processor_id'])) { |
| 3622 | unset($trxnParams['payment_processor_id']); |
| 3623 | } |
| 3624 | |
| 3625 | $params['trxnParams'] = $trxnParams; |
| 3626 | |
| 3627 | if ($isUpdate) { |
| 3628 | $updated = FALSE; |
| 3629 | $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount; |
| 3630 | $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount; |
| 3631 | $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount; |
| 3632 | if (!isset($params['trxnParams']['trxn_id'])) { |
| 3633 | // Actually I have no idea why we are overwriting any values from the previous contribution. |
| 3634 | // (filling makes sense to me). However, only protecting this value as I really really know we |
| 3635 | // don't want this one overwritten. |
| 3636 | // CRM-17751. |
| 3637 | $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id; |
| 3638 | } |
| 3639 | $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id; |
| 3640 | |
| 3641 | if (!(($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses) |
| 3642 | || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatuses)) |
| 3643 | && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses)) |
| 3644 | ) { |
| 3645 | $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id; |
| 3646 | $params['trxnParams']['check_number'] = $params['prevContribution']->check_number; |
| 3647 | } |
| 3648 | |
| 3649 | //if financial type is changed |
| 3650 | if (!empty($params['financial_type_id']) && |
| 3651 | $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id |
| 3652 | ) { |
| 3653 | $accountRelationship = 'Income Account is'; |
| 3654 | if (!empty($params['revenue_recognition_date']) || $params['prevContribution']->revenue_recognition_date) { |
| 3655 | $accountRelationship = 'Deferred Revenue Account is'; |
| 3656 | } |
| 3657 | $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id, $accountRelationship); |
| 3658 | $newFinancialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship); |
| 3659 | if ($oldFinancialAccount != $newFinancialAccount) { |
| 3660 | $params['total_amount'] = 0; |
| 3661 | // If we have a fee amount set reverse this as well. |
| 3662 | if (isset($params['fee_amount'])) { |
| 3663 | $params['trxnParams']['fee_amount'] = 0 - $params['fee_amount']; |
| 3664 | } |
| 3665 | if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) { |
| 3666 | $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship( |
| 3667 | $params['prevContribution']->financial_type_id, $accountRelationship); |
| 3668 | } |
| 3669 | else { |
| 3670 | $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC'); |
| 3671 | if (!empty($lastFinancialTrxnId['financialTrxnId'])) { |
| 3672 | $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id'); |
| 3673 | } |
| 3674 | } |
| 3675 | self::updateFinancialAccounts($params, 'changeFinancialType'); |
| 3676 | $params['skipLineItem'] = FALSE; |
| 3677 | foreach ($params['line_item'] as &$lineItems) { |
| 3678 | foreach ($lineItems as &$line) { |
| 3679 | $line['financial_type_id'] = $params['financial_type_id']; |
| 3680 | } |
| 3681 | } |
| 3682 | CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType'); |
| 3683 | /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */ |
| 3684 | $params['financial_account_id'] = $newFinancialAccount; |
| 3685 | $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount']; |
| 3686 | // Set the transaction fee amount back to the original value for creating the new positive financial trxn. |
| 3687 | if (isset($params['fee_amount'])) { |
| 3688 | $params['trxnParams']['fee_amount'] = $params['fee_amount']; |
| 3689 | } |
| 3690 | self::updateFinancialAccounts($params); |
| 3691 | CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE); |
| 3692 | $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; |
| 3693 | $updated = TRUE; |
| 3694 | $params['deferred_financial_account_id'] = $newFinancialAccount; |
| 3695 | } |
| 3696 | } |
| 3697 | |
| 3698 | //Update contribution status |
| 3699 | $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id; |
| 3700 | if (!isset($params['refund_trxn_id'])) { |
| 3701 | // CRM-17751 This has previously been deliberately set. No explanation as to why one variant |
| 3702 | // gets preference over another so I am only 'protecting' a very specific tested flow |
| 3703 | // and letting natural justice take care of the rest. |
| 3704 | $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id; |
| 3705 | } |
| 3706 | if (!empty($params['contribution_status_id']) && |
| 3707 | $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id |
| 3708 | ) { |
| 3709 | //Update Financial Records |
| 3710 | $callUpdateFinancialAccounts = self::updateFinancialAccountsOnContributionStatusChange($params); |
| 3711 | if ($callUpdateFinancialAccounts) { |
| 3712 | self::updateFinancialAccounts($params, 'changedStatus'); |
| 3713 | CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus'); |
| 3714 | } |
| 3715 | $updated = TRUE; |
| 3716 | } |
| 3717 | |
| 3718 | // change Payment Instrument for a Completed contribution |
| 3719 | // first handle special case when contribution is changed from Pending to Completed status when initial payment |
| 3720 | // instrument is null and now new payment instrument is added along with the payment |
| 3721 | if (!$params['contribution']->payment_instrument_id) { |
| 3722 | $params['contribution']->find(TRUE); |
| 3723 | } |
| 3724 | $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id; |
| 3725 | $params['trxnParams']['check_number'] = $params['check_number'] ?? NULL; |
| 3726 | |
| 3727 | if (self::isPaymentInstrumentChange($params, $pendingStatus)) { |
| 3728 | $updated = CRM_Core_BAO_FinancialTrxn::updateFinancialAccountsOnPaymentInstrumentChange($params); |
| 3729 | } |
| 3730 | |
| 3731 | //if Change contribution amount |
| 3732 | $params['trxnParams']['fee_amount'] = $params['fee_amount'] ?? NULL; |
| 3733 | $params['trxnParams']['net_amount'] = $params['net_amount'] ?? NULL; |
| 3734 | $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount; |
| 3735 | $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id; |
| 3736 | if (isset($totalAmount) && |
| 3737 | $totalAmount != $params['prevContribution']->total_amount |
| 3738 | ) { |
| 3739 | //Update Financial Records |
| 3740 | $params['trxnParams']['from_financial_account_id'] = NULL; |
| 3741 | self::updateFinancialAccounts($params, 'changedAmount'); |
| 3742 | CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount'); |
| 3743 | $updated = TRUE; |
| 3744 | } |
| 3745 | |
| 3746 | if (!$updated) { |
| 3747 | // Looks like we might have a data correction update. |
| 3748 | // This would be a case where a transaction id has been entered but it is incorrect & |
| 3749 | // the person goes back in & fixes it, as opposed to a new transaction. |
| 3750 | // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting |
| 3751 | // the data fix scenario. |
| 3752 | // CRM-17751. |
| 3753 | if (isset($params['refund_trxn_id'])) { |
| 3754 | $refundIDs = CRM_Core_BAO_FinancialTrxn::getRefundTransactionIDs($params['id']); |
| 3755 | if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) { |
| 3756 | civicrm_api3('FinancialTrxn', 'create', [ |
| 3757 | 'id' => $refundIDs['financialTrxnId'], |
| 3758 | 'trxn_id' => $params['refund_trxn_id'], |
| 3759 | ]); |
| 3760 | } |
| 3761 | } |
| 3762 | $cardType = $params['card_type_id'] ?? NULL; |
| 3763 | $panTruncation = $params['pan_truncation'] ?? NULL; |
| 3764 | CRM_Core_BAO_FinancialTrxn::updateCreditCardDetails($params['contribution']->id, $panTruncation, $cardType); |
| 3765 | } |
| 3766 | } |
| 3767 | |
| 3768 | else { |
| 3769 | // records finanical trxn and entity financial trxn |
| 3770 | // also make it available as return value |
| 3771 | self::recordAlwaysAccountsReceivable($trxnParams, $params); |
| 3772 | $trxnParams['pan_truncation'] = $params['pan_truncation'] ?? NULL; |
| 3773 | $trxnParams['card_type_id'] = $params['card_type_id'] ?? NULL; |
| 3774 | $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams); |
| 3775 | $params['entity_id'] = $financialTxn->id; |
| 3776 | if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) { |
| 3777 | self::$_trxnIDs[] = $financialTxn->id; |
| 3778 | } |
| 3779 | } |
| 3780 | } |
| 3781 | // record line items and financial items |
| 3782 | if (empty($params['skipLineItem'])) { |
| 3783 | CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $isUpdate); |
| 3784 | } |
| 3785 | |
| 3786 | // create batch entry if batch_id is passed and |
| 3787 | // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611 |
| 3788 | if (!empty($params['batch_id']) && !empty($financialTxn)) { |
| 3789 | $entityParams = [ |
| 3790 | 'batch_id' => $params['batch_id'], |
| 3791 | 'entity_table' => 'civicrm_financial_trxn', |
| 3792 | 'entity_id' => $financialTxn->id, |
| 3793 | ]; |
| 3794 | CRM_Batch_BAO_EntityBatch::create($entityParams); |
| 3795 | } |
| 3796 | |
| 3797 | // when a fee is charged |
| 3798 | if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) { |
| 3799 | CRM_Core_BAO_FinancialTrxn::recordFees($params); |
| 3800 | } |
| 3801 | |
| 3802 | if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant' |
| 3803 | && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id |
| 3804 | ) { |
| 3805 | $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id'); |
| 3806 | $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level); |
| 3807 | CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel); |
| 3808 | } |
| 3809 | unset($params['line_item']); |
| 3810 | self::$_trxnIDs = NULL; |
| 3811 | return $return; |
| 3812 | } |
| 3813 | |
| 3814 | /** |
| 3815 | * Update all financial accounts entry. |
| 3816 | * |
| 3817 | * @param array $params |
| 3818 | * Contribution object, line item array and params for trxn. |
| 3819 | * |
| 3820 | * @param string $context |
| 3821 | * Update scenarios. |
| 3822 | * |
| 3823 | * @todo stop passing $params by reference. It is unclear the purpose of doing this & |
| 3824 | * adds unpredictability. |
| 3825 | * |
| 3826 | */ |
| 3827 | public static function updateFinancialAccounts(&$params, $context = NULL) { |
| 3828 | $trxnID = NULL; |
| 3829 | $inputParams = $params; |
| 3830 | $isARefund = self::isContributionUpdateARefund($params['prevContribution']->contribution_status_id, $params['contribution']->contribution_status_id); |
| 3831 | |
| 3832 | if ($context == 'changedAmount' || $context == 'changeFinancialType') { |
| 3833 | // @todo we should stop passing $params by reference - splitting this out would be a step towards that. |
| 3834 | $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount); |
| 3835 | } |
| 3836 | |
| 3837 | $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']); |
| 3838 | // @todo we should stop passing $params by reference - splitting this out would be a step towards that. |
| 3839 | $params['entity_id'] = $trxn->id; |
| 3840 | |
| 3841 | $itemParams['entity_table'] = 'civicrm_line_item'; |
| 3842 | $trxnIds['id'] = $params['entity_id']; |
| 3843 | $previousLineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($params['contribution']->id); |
| 3844 | foreach ($params['line_item'] as $fieldId => $fields) { |
| 3845 | $params = self::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId); |
| 3846 | } |
| 3847 | } |
| 3848 | |
| 3849 | /** |
| 3850 | * Is this contribution status a reversal. |
| 3851 | * |
| 3852 | * If so we would expect to record a negative value in the financial_trxn table. |
| 3853 | * |
| 3854 | * @param int $status_id |
| 3855 | * |
| 3856 | * @return bool |
| 3857 | */ |
| 3858 | public static function isContributionStatusNegative($status_id) { |
| 3859 | $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded']; |
| 3860 | return in_array(CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE); |
| 3861 | } |
| 3862 | |
| 3863 | /** |
| 3864 | * Check status validation on update of a contribution. |
| 3865 | * |
| 3866 | * @param array $values |
| 3867 | * Previous form values before submit. |
| 3868 | * |
| 3869 | * @param array $fields |
| 3870 | * The input form values. |
| 3871 | * |
| 3872 | * @param array $errors |
| 3873 | * List of errors. |
| 3874 | * |
| 3875 | * @return bool |
| 3876 | */ |
| 3877 | public static function checkStatusValidation($values, &$fields, &$errors) { |
| 3878 | if (CRM_Utils_System::isNull($values) && !empty($fields['id'])) { |
| 3879 | $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id'); |
| 3880 | if ($values['contribution_status_id'] == $fields['contribution_status_id']) { |
| 3881 | return FALSE; |
| 3882 | } |
| 3883 | } |
| 3884 | $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
| 3885 | $checkStatus = [ |
| 3886 | 'Cancelled' => ['Completed', 'Refunded'], |
| 3887 | 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'], |
| 3888 | 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'], |
| 3889 | 'In Progress' => ['Cancelled', 'Completed', 'Failed'], |
| 3890 | 'Refunded' => ['Cancelled', 'Completed'], |
| 3891 | 'Partially paid' => ['Completed'], |
| 3892 | 'Pending refund' => ['Completed', 'Refunded'], |
| 3893 | 'Failed' => ['Pending'], |
| 3894 | ]; |
| 3895 | |
| 3896 | if (!in_array($contributionStatuses[$fields['contribution_status_id']], |
| 3897 | CRM_Utils_Array::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, [])) |
| 3898 | ) { |
| 3899 | $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [ |
| 3900 | 1 => $contributionStatuses[$values['contribution_status_id']], |
| 3901 | 2 => $contributionStatuses[$fields['contribution_status_id']], |
| 3902 | ]); |
| 3903 | } |
| 3904 | } |
| 3905 | |
| 3906 | /** |
| 3907 | * Delete contribution of contact. |
| 3908 | * |
| 3909 | * @see https://issues.civicrm.org/jira/browse/CRM-12155 |
| 3910 | * |
| 3911 | * @param int $contactId |
| 3912 | * Contact id. |
| 3913 | * |
| 3914 | */ |
| 3915 | public static function deleteContactContribution($contactId) { |
| 3916 | $contribution = new CRM_Contribute_DAO_Contribution(); |
| 3917 | $contribution->contact_id = $contactId; |
| 3918 | $contribution->find(); |
| 3919 | while ($contribution->fetch()) { |
| 3920 | self::deleteContribution($contribution->id); |
| 3921 | } |
| 3922 | } |
| 3923 | |
| 3924 | /** |
| 3925 | * Get options for a given contribution field. |
| 3926 | * |
| 3927 | * @param string $fieldName |
| 3928 | * @param string $context see CRM_Core_DAO::buildOptionsContext. |
| 3929 | * @param array $props whatever is known about this dao object. |
| 3930 | * |
| 3931 | * @return array|bool |
| 3932 | * @see CRM_Core_DAO::buildOptions |
| 3933 | * |
| 3934 | */ |
| 3935 | public static function buildOptions($fieldName, $context = NULL, $props = []) { |
| 3936 | $className = __CLASS__; |
| 3937 | $params = []; |
| 3938 | if (isset($props['orderColumn'])) { |
| 3939 | $params['orderColumn'] = $props['orderColumn']; |
| 3940 | } |
| 3941 | switch ($fieldName) { |
| 3942 | // This field is not part of this object but the api supports it |
| 3943 | case 'payment_processor': |
| 3944 | $className = 'CRM_Contribute_BAO_ContributionPage'; |
| 3945 | // Filter results by contribution page |
| 3946 | if (!empty($props['contribution_page_id'])) { |
| 3947 | $page = civicrm_api('contribution_page', 'getsingle', [ |
| 3948 | 'version' => 3, |
| 3949 | 'id' => ($props['contribution_page_id']), |
| 3950 | ]); |
| 3951 | $types = (array) CRM_Utils_Array::value('payment_processor', $page, 0); |
| 3952 | $params['condition'] = 'id IN (' . implode(',', $types) . ')'; |
| 3953 | } |
| 3954 | break; |
| 3955 | |
| 3956 | // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it |
| 3957 | case 'honor_type_id': |
| 3958 | $className = 'CRM_Contribute_BAO_ContributionSoft'; |
| 3959 | $fieldName = 'soft_credit_type_id'; |
| 3960 | $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')"; |
| 3961 | break; |
| 3962 | |
| 3963 | case 'contribution_status_id': |
| 3964 | if ($context !== 'validate') { |
| 3965 | $params['condition'] = "v.name <> 'Template'"; |
| 3966 | } |
| 3967 | } |
| 3968 | return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context); |
| 3969 | } |
| 3970 | |
| 3971 | /** |
| 3972 | * Validate financial type. |
| 3973 | * |
| 3974 | * @see https://issues.civicrm.org/jira/browse/CRM-13231 |
| 3975 | * |
| 3976 | * @param int $financialTypeId |
| 3977 | * Financial Type id. |
| 3978 | * |
| 3979 | * @param string $relationName |
| 3980 | * |
| 3981 | * @return array|bool |
| 3982 | */ |
| 3983 | public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') { |
| 3984 | $financialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeId, $relationName); |
| 3985 | |
| 3986 | if (!$financialAccount) { |
| 3987 | return CRM_Contribute_PseudoConstant::financialType($financialTypeId); |
| 3988 | } |
| 3989 | return FALSE; |
| 3990 | } |
| 3991 | |
| 3992 | /** |
| 3993 | * @param int $targetCid |
| 3994 | * @param $activityType |
| 3995 | * @param string $title |
| 3996 | * @param int $contributionId |
| 3997 | * @param string $totalAmount |
| 3998 | * @param string $currency |
| 3999 | * @param string $trxn_date |
| 4000 | * |
| 4001 | * @throws \CRM_Core_Exception |
| 4002 | * @throws \CiviCRM_API3_Exception |
| 4003 | */ |
| 4004 | public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) { |
| 4005 | $paymentAmount = CRM_Utils_Money::format($totalAmount, $currency); |
| 4006 | $subject = "{$paymentAmount} - Offline {$activityType} for {$title}"; |
| 4007 | $date = CRM_Utils_Date::isoToMysql($trxn_date); |
| 4008 | // source record id would be the contribution id |
| 4009 | $srcRecId = $contributionId; |
| 4010 | |
| 4011 | // activity params |
| 4012 | $activityParams = [ |
| 4013 | 'source_contact_id' => $targetCid, |
| 4014 | 'source_record_id' => $srcRecId, |
| 4015 | 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType), |
| 4016 | 'subject' => $subject, |
| 4017 | 'activity_date_time' => $date, |
| 4018 | 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'), |
| 4019 | 'skipRecentView' => TRUE, |
| 4020 | ]; |
| 4021 | |
| 4022 | // create activity with target contacts |
| 4023 | $session = CRM_Core_Session::singleton(); |
| 4024 | $id = $session->get('userID'); |
| 4025 | if ($id) { |
| 4026 | $activityParams['source_contact_id'] = $id; |
| 4027 | $activityParams['target_contact_id'][] = $targetCid; |
| 4028 | } |
| 4029 | civicrm_api3('Activity', 'create', $activityParams); |
| 4030 | } |
| 4031 | |
| 4032 | /** |
| 4033 | * Get list of payments displayed by Contribute_Page_PaymentInfo. |
| 4034 | * |
| 4035 | * @param int $id |
| 4036 | * @param string $component |
| 4037 | * @param bool $getTrxnInfo |
| 4038 | * |
| 4039 | * @return mixed |
| 4040 | * |
| 4041 | * @throws \CRM_Core_Exception |
| 4042 | * @throws \CiviCRM_API3_Exception |
| 4043 | */ |
| 4044 | public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE) { |
| 4045 | // @todo deprecate passing in component - always call with contribution. |
| 4046 | if ($component == 'event') { |
| 4047 | $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id'); |
| 4048 | |
| 4049 | if (!$contributionId) { |
| 4050 | if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) { |
| 4051 | $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id'); |
| 4052 | $id = $primaryParticipantId; |
| 4053 | } |
| 4054 | if (!$contributionId) { |
| 4055 | return; |
| 4056 | } |
| 4057 | } |
| 4058 | } |
| 4059 | elseif ($component == 'membership') { |
| 4060 | $contributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id'); |
| 4061 | } |
| 4062 | else { |
| 4063 | $contributionId = $id; |
| 4064 | } |
| 4065 | |
| 4066 | // The balance used to be calculated this way - we really want to remove this 'oldCalculation' |
| 4067 | // but need to unpick the whole trxn_id it's returning first. |
| 4068 | $oldCalculation = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId); |
| 4069 | $baseTrxnId = !empty($oldCalculation['trxn_id']) ? $oldCalculation['trxn_id'] : NULL; |
| 4070 | if (!$baseTrxnId) { |
| 4071 | $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId); |
| 4072 | $baseTrxnId = $baseTrxnId['financialTrxnId']; |
| 4073 | } |
| 4074 | $total = CRM_Price_BAO_LineItem::getLineTotal($contributionId); |
| 4075 | |
| 4076 | $paymentBalance = CRM_Contribute_BAO_Contribution::getContributionBalance($contributionId, $total); |
| 4077 | |
| 4078 | $contribution = civicrm_api3('Contribution', 'getsingle', [ |
| 4079 | 'id' => $contributionId, |
| 4080 | 'return' => [ |
| 4081 | 'currency', |
| 4082 | 'is_pay_later', |
| 4083 | 'contribution_status_id', |
| 4084 | 'financial_type_id', |
| 4085 | ], |
| 4086 | ]); |
| 4087 | |
| 4088 | $info['payLater'] = $contribution['is_pay_later']; |
| 4089 | $info['contribution_status'] = $contribution['contribution_status']; |
| 4090 | $info['currency'] = $contribution['currency']; |
| 4091 | |
| 4092 | $info['total'] = $total; |
| 4093 | $info['paid'] = $total - $paymentBalance; |
| 4094 | $info['balance'] = $paymentBalance; |
| 4095 | $info['id'] = $id; |
| 4096 | $info['component'] = $component; |
| 4097 | if ($getTrxnInfo && $baseTrxnId) { |
| 4098 | $info['transaction'] = self::getContributionTransactionInformation($contributionId, $contribution['financial_type_id']); |
| 4099 | } |
| 4100 | |
| 4101 | $info['payment_links'] = self::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']); |
| 4102 | return $info; |
| 4103 | } |
| 4104 | |
| 4105 | /** |
| 4106 | * Get the outstanding balance on a contribution. |
| 4107 | * |
| 4108 | * @param int $contributionId |
| 4109 | * @param float $contributionTotal |
| 4110 | * Optional amount to override the saved amount paid (e.g if calculating what it WILL be). |
| 4111 | * |
| 4112 | * @return float |
| 4113 | */ |
| 4114 | public static function getContributionBalance($contributionId, $contributionTotal = NULL) { |
| 4115 | if ($contributionTotal === NULL) { |
| 4116 | $contributionTotal = CRM_Price_BAO_LineItem::getLineTotal($contributionId); |
| 4117 | } |
| 4118 | |
| 4119 | return (float) CRM_Utils_Money::subtractCurrencies( |
| 4120 | $contributionTotal, |
| 4121 | CRM_Core_BAO_FinancialTrxn::getTotalPayments($contributionId, TRUE), |
| 4122 | CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency') |
| 4123 | ); |
| 4124 | } |
| 4125 | |
| 4126 | /** |
| 4127 | * Get the tax amount (misnamed function). |
| 4128 | * |
| 4129 | * @param array $params |
| 4130 | * @param bool $isLineItem |
| 4131 | * |
| 4132 | * @return array |
| 4133 | */ |
| 4134 | public static function checkTaxAmount($params, $isLineItem = FALSE) { |
| 4135 | $taxRates = CRM_Core_PseudoConstant::getTaxRates(); |
| 4136 | |
| 4137 | // Update contribution. |
| 4138 | if (!empty($params['id'])) { |
| 4139 | // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update |
| 4140 | // there are no tax implications - early return. |
| 4141 | if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) { |
| 4142 | return $params; |
| 4143 | } |
| 4144 | if (empty($params['prevContribution'])) { |
| 4145 | $params['prevContribution'] = self::getOriginalContribution($params['id']); |
| 4146 | } |
| 4147 | |
| 4148 | foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) { |
| 4149 | if (!isset($params[$field])) { |
| 4150 | if ($field == 'total_amount' && $params['prevContribution']->tax_amount) { |
| 4151 | // Tax amount gets added back on later.... |
| 4152 | $params['total_amount'] = $params['prevContribution']->total_amount - |
| 4153 | $params['prevContribution']->tax_amount; |
| 4154 | } |
| 4155 | else { |
| 4156 | $params[$field] = $params['prevContribution']->$field; |
| 4157 | if ($params[$field] != $params['prevContribution']->$field) { |
| 4158 | } |
| 4159 | } |
| 4160 | } |
| 4161 | } |
| 4162 | |
| 4163 | self::calculateMissingAmountParams($params, $params['id']); |
| 4164 | if (!array_key_exists($params['financial_type_id'], $taxRates)) { |
| 4165 | // Assign tax Amount on update of contribution |
| 4166 | if (!empty($params['prevContribution']->tax_amount)) { |
| 4167 | $params['tax_amount'] = 'null'; |
| 4168 | CRM_Price_BAO_LineItem::getLineItemArray($params, [$params['id']]); |
| 4169 | foreach ($params['line_item'] as $setID => $priceField) { |
| 4170 | foreach ($priceField as $priceFieldID => $priceFieldValue) { |
| 4171 | $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount']; |
| 4172 | } |
| 4173 | } |
| 4174 | } |
| 4175 | } |
| 4176 | } |
| 4177 | |
| 4178 | // New Contribution and update of contribution with tax rate financial type |
| 4179 | if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && |
| 4180 | empty($params['skipLineItem']) && !$isLineItem |
| 4181 | ) { |
| 4182 | $taxRateParams = $taxRates[$params['financial_type_id']]; |
| 4183 | $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount(CRM_Utils_Array::value('total_amount', $params), $taxRateParams); |
| 4184 | $params['tax_amount'] = round($taxAmount['tax_amount'], 2); |
| 4185 | |
| 4186 | // Get Line Item on update of contribution |
| 4187 | if (isset($params['id'])) { |
| 4188 | CRM_Price_BAO_LineItem::getLineItemArray($params, [$params['id']]); |
| 4189 | } |
| 4190 | else { |
| 4191 | CRM_Price_BAO_LineItem::getLineItemArray($params); |
| 4192 | } |
| 4193 | foreach ($params['line_item'] as $setID => $priceField) { |
| 4194 | foreach ($priceField as $priceFieldID => $priceFieldValue) { |
| 4195 | $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount']; |
| 4196 | } |
| 4197 | } |
| 4198 | $params['total_amount'] = CRM_Utils_Array::value('total_amount', $params) + $params['tax_amount']; |
| 4199 | } |
| 4200 | elseif (isset($params['api.line_item.create'])) { |
| 4201 | // Update total amount of contribution using lineItem |
| 4202 | $taxAmountArray = []; |
| 4203 | foreach ($params['api.line_item.create'] as $key => $value) { |
| 4204 | if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) { |
| 4205 | $taxRate = $taxRates[$value['financial_type_id']]; |
| 4206 | $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($value['line_total'], $taxRate); |
| 4207 | $taxAmountArray[] = round($taxAmount['tax_amount'], 2); |
| 4208 | } |
| 4209 | } |
| 4210 | $params['tax_amount'] = array_sum($taxAmountArray); |
| 4211 | $params['total_amount'] = $params['total_amount'] + $params['tax_amount']; |
| 4212 | } |
| 4213 | |
| 4214 | return $params; |
| 4215 | } |
| 4216 | |
| 4217 | /** |
| 4218 | * Check financial type validation on update of a contribution. |
| 4219 | * |
| 4220 | * @param int $financialTypeId |
| 4221 | * Value of latest Financial Type. |
| 4222 | * |
| 4223 | * @param int $contributionId |
| 4224 | * Contribution Id. |
| 4225 | * |
| 4226 | * @param array $errors |
| 4227 | * List of errors. |
| 4228 | * |
| 4229 | * @return void |
| 4230 | */ |
| 4231 | public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) { |
| 4232 | if (!empty($financialTypeId)) { |
| 4233 | $oldFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id'); |
| 4234 | if ($oldFinancialTypeId == $financialTypeId) { |
| 4235 | return; |
| 4236 | } |
| 4237 | } |
| 4238 | $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;'; |
| 4239 | $params = [ |
| 4240 | '1' => [$contributionId, 'Integer'], |
| 4241 | ]; |
| 4242 | $result = CRM_Core_DAO::executeQuery($sql, $params); |
| 4243 | if ($result->N > 1) { |
| 4244 | $errors['financial_type_id'] = ts('One or more line items have a different financial type than the contribution. Editing the financial type is not yet supported in this situation.'); |
| 4245 | } |
| 4246 | } |
| 4247 | |
| 4248 | /** |
| 4249 | * Update related pledge payment payments. |
| 4250 | * |
| 4251 | * This function has been refactored out of the back office contribution form and may |
| 4252 | * still overlap with other functions. |
| 4253 | * |
| 4254 | * @param string $action |
| 4255 | * @param int $pledgePaymentID |
| 4256 | * @param int $contributionID |
| 4257 | * @param bool $adjustTotalAmount |
| 4258 | * @param float $total_amount |
| 4259 | * @param float $original_total_amount |
| 4260 | * @param int $contribution_status_id |
| 4261 | * @param int $original_contribution_status_id |
| 4262 | */ |
| 4263 | public static function updateRelatedPledge( |
| 4264 | $action, |
| 4265 | $pledgePaymentID, |
| 4266 | $contributionID, |
| 4267 | $adjustTotalAmount, |
| 4268 | $total_amount, |
| 4269 | $original_total_amount, |
| 4270 | $contribution_status_id, |
| 4271 | $original_contribution_status_id |
| 4272 | ) { |
| 4273 | if (!$pledgePaymentID && $action & CRM_Core_Action::ADD && !$contributionID) { |
| 4274 | return; |
| 4275 | } |
| 4276 | |
| 4277 | if ($pledgePaymentID) { |
| 4278 | //store contribution id in payment record. |
| 4279 | CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID); |
| 4280 | } |
| 4281 | else { |
| 4282 | $pledgePaymentID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', |
| 4283 | $contributionID, |
| 4284 | 'id', |
| 4285 | 'contribution_id' |
| 4286 | ); |
| 4287 | } |
| 4288 | |
| 4289 | if (!$pledgePaymentID) { |
| 4290 | return; |
| 4291 | } |
| 4292 | $pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', |
| 4293 | $contributionID, |
| 4294 | 'pledge_id', |
| 4295 | 'contribution_id' |
| 4296 | ); |
| 4297 | |
| 4298 | $updatePledgePaymentStatus = FALSE; |
| 4299 | |
| 4300 | // If either the status or the amount has changed we update the pledge status. |
| 4301 | if ($action & CRM_Core_Action::ADD) { |
| 4302 | $updatePledgePaymentStatus = TRUE; |
| 4303 | } |
| 4304 | elseif ($action & CRM_Core_Action::UPDATE && (($original_contribution_status_id != $contribution_status_id) || |
| 4305 | ($original_total_amount != $total_amount)) |
| 4306 | ) { |
| 4307 | $updatePledgePaymentStatus = TRUE; |
| 4308 | } |
| 4309 | |
| 4310 | if ($updatePledgePaymentStatus) { |
| 4311 | CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, |
| 4312 | [$pledgePaymentID], |
| 4313 | $contribution_status_id, |
| 4314 | NULL, |
| 4315 | $total_amount, |
| 4316 | $adjustTotalAmount |
| 4317 | ); |
| 4318 | } |
| 4319 | } |
| 4320 | |
| 4321 | /** |
| 4322 | * Is there only one line item attached to the contribution. |
| 4323 | * |
| 4324 | * @param int $id |
| 4325 | * Contribution ID. |
| 4326 | * |
| 4327 | * @return bool |
| 4328 | * @throws \CiviCRM_API3_Exception |
| 4329 | */ |
| 4330 | public static function isSingleLineItem($id) { |
| 4331 | $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]); |
| 4332 | return ($lineItemCount == 1); |
| 4333 | } |
| 4334 | |
| 4335 | /** |
| 4336 | * Complete an order. |
| 4337 | * |
| 4338 | * Do not call this directly - use the contribution.completetransaction api as this function is being refactored. |
| 4339 | * |
| 4340 | * Currently overloaded to complete a transaction & repeat a transaction - fix! |
| 4341 | * |
| 4342 | * Moving it out of the BaseIPN class is just the first step. |
| 4343 | * |
| 4344 | * @param array $input |
| 4345 | * @param array $ids |
| 4346 | * @param array $objects |
| 4347 | * @param bool $isPostPaymentCreate |
| 4348 | * Is this being called from the payment.create api. If so the api has taken care of financial entities. |
| 4349 | * Note that our goal is that this would only ever be called from payment.create and never handle financials (only |
| 4350 | * transitioning related elements). |
| 4351 | * |
| 4352 | * @return array |
| 4353 | * @throws \CRM_Core_Exception |
| 4354 | * @throws \CiviCRM_API3_Exception |
| 4355 | */ |
| 4356 | public static function completeOrder($input, $ids, $objects, $isPostPaymentCreate = FALSE) { |
| 4357 | $transaction = new CRM_Core_Transaction(); |
| 4358 | $contribution = $objects['contribution']; |
| 4359 | // @todo see if we even need this - it's used further down to create an activity |
| 4360 | // but the BAO layer should create that - we just need to add a test to cover it & can |
| 4361 | // maybe remove $ids altogether. |
| 4362 | $contributionContactID = $ids['related_contact']; |
| 4363 | $participantID = $ids['participant']; |
| 4364 | $recurringContributionID = $ids['contributionRecur']; |
| 4365 | |
| 4366 | // Unset ids just to make it clear it's not used again. |
| 4367 | unset($ids); |
| 4368 | // The previous details are used when calculating line items so keep it before any code that 'does something' |
| 4369 | if (!empty($contribution->id)) { |
| 4370 | $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(['id' => $contribution->id]); |
| 4371 | } |
| 4372 | $inputContributionWhiteList = [ |
| 4373 | 'fee_amount', |
| 4374 | 'net_amount', |
| 4375 | 'trxn_id', |
| 4376 | 'check_number', |
| 4377 | 'payment_instrument_id', |
| 4378 | 'is_test', |
| 4379 | 'campaign_id', |
| 4380 | 'receive_date', |
| 4381 | 'receipt_date', |
| 4382 | 'contribution_status_id', |
| 4383 | 'card_type_id', |
| 4384 | 'pan_truncation', |
| 4385 | 'financial_type_id', |
| 4386 | ]; |
| 4387 | |
| 4388 | // @todo - accept payment_processor_id as an input parameter as it is part of the |
| 4389 | // incoming payment information (at least when coming from a payment processor). |
| 4390 | // this is the last 'object' to get rid of.... |
| 4391 | $paymentProcessorId = ''; |
| 4392 | if (isset($objects['paymentProcessor'])) { |
| 4393 | if (is_array($objects['paymentProcessor'])) { |
| 4394 | $paymentProcessorId = $objects['paymentProcessor']['id']; |
| 4395 | } |
| 4396 | else { |
| 4397 | $paymentProcessorId = $objects['paymentProcessor']->id; |
| 4398 | } |
| 4399 | } |
| 4400 | |
| 4401 | $completedContributionStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'); |
| 4402 | |
| 4403 | $contributionParams = array_merge([ |
| 4404 | 'contribution_status_id' => $completedContributionStatusID, |
| 4405 | 'source' => self::getRecurringContributionDescription($contribution, $participantID), |
| 4406 | ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1) |
| 4407 | )); |
| 4408 | |
| 4409 | $contributionParams['payment_processor'] = $paymentProcessorId; |
| 4410 | |
| 4411 | if (empty($contributionParams['payment_instrument_id']) && isset($contribution->_relatedObjects['paymentProcessor']['payment_instrument_id'])) { |
| 4412 | $contributionParams['payment_instrument_id'] = PaymentProcessor::get()->addWhere('id', '=', $paymentProcessorId)->addSelect('payment_instrument_id')->execute()->first()['payment_instrument_id']; |
| 4413 | } |
| 4414 | |
| 4415 | if ($recurringContributionID) { |
| 4416 | $contributionParams['contribution_recur_id'] = $recurringContributionID; |
| 4417 | } |
| 4418 | $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis')); |
| 4419 | |
| 4420 | $contributionResult = self::repeatTransaction($contribution, $input, $contributionParams); |
| 4421 | $contributionID = (int) $contribution->id; |
| 4422 | |
| 4423 | if ($input['component'] == 'contribute') { |
| 4424 | if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) { |
| 4425 | self::updateMembershipBasedOnCompletionOfContribution( |
| 4426 | $contributionID, |
| 4427 | $changeDate |
| 4428 | ); |
| 4429 | } |
| 4430 | } |
| 4431 | else { |
| 4432 | if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) { |
| 4433 | $participantParams['id'] = $participantID; |
| 4434 | $participantParams['status_id'] = 'Registered'; |
| 4435 | civicrm_api3('Participant', 'create', $participantParams); |
| 4436 | } |
| 4437 | } |
| 4438 | |
| 4439 | $contributionParams['id'] = $contributionID; |
| 4440 | $contributionParams['is_post_payment_create'] = $isPostPaymentCreate; |
| 4441 | |
| 4442 | if (!$contributionResult) { |
| 4443 | $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams); |
| 4444 | } |
| 4445 | |
| 4446 | // Add new soft credit against current $contribution. |
| 4447 | if ($recurringContributionID) { |
| 4448 | CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($recurringContributionID, $contributionID); |
| 4449 | } |
| 4450 | |
| 4451 | $contribution->contribution_status_id = $contributionParams['contribution_status_id']; |
| 4452 | |
| 4453 | CRM_Core_Error::debug_log_message('Contribution record updated successfully'); |
| 4454 | $transaction->commit(); |
| 4455 | |
| 4456 | // @todo - check if Contribution::create does this, test, remove. |
| 4457 | CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contributionID, $recurringContributionID, |
| 4458 | $contributionParams['contribution_status_id'], $input['amount']); |
| 4459 | |
| 4460 | // create an activity record |
| 4461 | // @todo - check if Contribution::create does this, test, remove. |
| 4462 | if ($input['component'] == 'contribute') { |
| 4463 | //CRM-4027 |
| 4464 | $targetContactID = NULL; |
| 4465 | if ($contributionContactID) { |
| 4466 | $targetContactID = $contribution->contact_id; |
| 4467 | $contribution->contact_id = $contributionContactID; |
| 4468 | } |
| 4469 | CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID); |
| 4470 | } |
| 4471 | |
| 4472 | if (self::isEmailReceipt($input, $contribution->contribution_page_id, $recurringContributionID)) { |
| 4473 | civicrm_api3('Contribution', 'sendconfirmation', [ |
| 4474 | 'id' => $contributionID, |
| 4475 | 'payment_processor_id' => $paymentProcessorId, |
| 4476 | ]); |
| 4477 | CRM_Core_Error::debug_log_message("Receipt sent"); |
| 4478 | } |
| 4479 | |
| 4480 | CRM_Core_Error::debug_log_message("Success: Database updated"); |
| 4481 | return $contributionResult; |
| 4482 | } |
| 4483 | |
| 4484 | /** |
| 4485 | * Send receipt from contribution. |
| 4486 | * |
| 4487 | * Do not call this directly - it is being refactored. use contribution.sendmessage api call. |
| 4488 | * |
| 4489 | * Note that the compose message part has been moved to contribution |
| 4490 | * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it. |
| 4491 | * |
| 4492 | * @param array $input |
| 4493 | * Incoming data from Payment processor. |
| 4494 | * @param array $ids |
| 4495 | * Related object IDs. |
| 4496 | * @param int $contributionID |
| 4497 | * @param bool $returnMessageText |
| 4498 | * Should text be returned instead of sent. This. |
| 4499 | * is because the function is also used to generate pdfs |
| 4500 | * |
| 4501 | * @return array |
| 4502 | * @throws \CRM_Core_Exception |
| 4503 | * @throws \CiviCRM_API3_Exception |
| 4504 | * @throws \Exception |
| 4505 | */ |
| 4506 | public static function sendMail($input, $ids, $contributionID, $returnMessageText = FALSE) { |
| 4507 | $values = []; |
| 4508 | $contribution = new CRM_Contribute_BAO_Contribution(); |
| 4509 | $contribution->id = $contributionID; |
| 4510 | if (!$contribution->find(TRUE)) { |
| 4511 | throw new CRM_Core_Exception('Contribution does not exist'); |
| 4512 | } |
| 4513 | $contribution->loadRelatedObjects($input, $ids, TRUE); |
| 4514 | // set receipt from e-mail and name in value |
| 4515 | if (!$returnMessageText) { |
| 4516 | list($values['receipt_from_name'], $values['receipt_from_email']) = self::generateFromEmailAndName($input, $contribution); |
| 4517 | } |
| 4518 | $values['contribution_status'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id); |
| 4519 | $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText); |
| 4520 | if ((!isset($input['receipt_update']) || $input['receipt_update']) && empty($contribution->receipt_date)) { |
| 4521 | civicrm_api3('Contribution', 'create', [ |
| 4522 | 'receipt_date' => 'now', |
| 4523 | 'id' => $contribution->id, |
| 4524 | ]); |
| 4525 | } |
| 4526 | return $return; |
| 4527 | } |
| 4528 | |
| 4529 | /** |
| 4530 | * Generate From email and from name in an array values |
| 4531 | * |
| 4532 | * @param array $input |
| 4533 | * @param \CRM_Contribute_BAO_Contribution $contribution |
| 4534 | * |
| 4535 | * @return array |
| 4536 | */ |
| 4537 | public static function generateFromEmailAndName($input, $contribution) { |
| 4538 | // Use input value if supplied. |
| 4539 | if (!empty($input['receipt_from_email'])) { |
| 4540 | return [ |
| 4541 | CRM_Utils_Array::value('receipt_from_name', $input, ''), |
| 4542 | $input['receipt_from_email'], |
| 4543 | ]; |
| 4544 | } |
| 4545 | // if we are still empty see if we can use anything from a contribution page. |
| 4546 | $pageValues = []; |
| 4547 | if (!empty($contribution->contribution_page_id)) { |
| 4548 | $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id]); |
| 4549 | } |
| 4550 | // if we are still empty see if we can use anything from a contribution page. |
| 4551 | if (!empty($pageValues['receipt_from_email'])) { |
| 4552 | return [ |
| 4553 | CRM_Utils_Array::value('receipt_from_name', $pageValues), |
| 4554 | $pageValues['receipt_from_email'], |
| 4555 | ]; |
| 4556 | } |
| 4557 | // If we are still empty fall back to the domain or logged in user information. |
| 4558 | return CRM_Core_BAO_Domain::getDefaultReceiptFrom(); |
| 4559 | } |
| 4560 | |
| 4561 | /** |
| 4562 | * Load related memberships. |
| 4563 | * |
| 4564 | * @param array $ids |
| 4565 | * |
| 4566 | * @return array $ids |
| 4567 | * |
| 4568 | * @throws Exception |
| 4569 | * @deprecated |
| 4570 | * |
| 4571 | * Note that in theory it should be possible to retrieve these from the line_item table |
| 4572 | * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail |
| 4573 | * as it seems the api is not correctly linking the line items when the contribution is created in the flow |
| 4574 | * where the contribution is created in the API, followed by the membership (using the api) followed by the membership |
| 4575 | * payment. The membership payment BAO does have code to address this but it doesn't appear to be working. |
| 4576 | * |
| 4577 | * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918. |
| 4578 | * |
| 4579 | */ |
| 4580 | public function loadRelatedMembershipObjects($ids = []) { |
| 4581 | $query = " |
| 4582 | SELECT membership_id |
| 4583 | FROM civicrm_membership_payment |
| 4584 | WHERE contribution_id = %1 "; |
| 4585 | $params = [1 => [$this->id, 'Integer']]; |
| 4586 | $ids['membership'] = (array) CRM_Utils_Array::value('membership', $ids, []); |
| 4587 | |
| 4588 | $dao = CRM_Core_DAO::executeQuery($query, $params); |
| 4589 | while ($dao->fetch()) { |
| 4590 | if ($dao->membership_id && !in_array($dao->membership_id, $ids['membership'])) { |
| 4591 | $ids['membership'][$dao->membership_id] = $dao->membership_id; |
| 4592 | } |
| 4593 | } |
| 4594 | |
| 4595 | if (array_key_exists('membership', $ids) && is_array($ids['membership'])) { |
| 4596 | foreach ($ids['membership'] as $id) { |
| 4597 | if (!empty($id)) { |
| 4598 | $membership = new CRM_Member_BAO_Membership(); |
| 4599 | $membership->id = $id; |
| 4600 | if (!$membership->find(TRUE)) { |
| 4601 | throw new Exception("Could not find membership record: $id"); |
| 4602 | } |
| 4603 | $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date); |
| 4604 | $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date); |
| 4605 | $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date); |
| 4606 | $this->_relatedObjects['membership'][$membership->id . '_' . $membership->membership_type_id] = $membership; |
| 4607 | |
| 4608 | } |
| 4609 | } |
| 4610 | } |
| 4611 | return $ids; |
| 4612 | } |
| 4613 | |
| 4614 | /** |
| 4615 | * Get the description (source field) for the recurring contribution. |
| 4616 | * |
| 4617 | * @param CRM_Contribute_BAO_Contribution $contribution |
| 4618 | * @param int|null $participantID |
| 4619 | * |
| 4620 | * @return string |
| 4621 | * @throws \CiviCRM_API3_Exception |
| 4622 | * @throws \API_Exception |
| 4623 | */ |
| 4624 | protected static function getRecurringContributionDescription($contribution, $participantID) { |
| 4625 | if (!empty($contribution->source)) { |
| 4626 | return $contribution->source; |
| 4627 | } |
| 4628 | elseif (!empty($contribution->contribution_page_id) && is_numeric($contribution->contribution_page_id)) { |
| 4629 | $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', [ |
| 4630 | 'id' => $contribution->contribution_page_id, |
| 4631 | 'return' => 'title', |
| 4632 | ]); |
| 4633 | return ts('Online Contribution') . ': ' . $contributionPageTitle; |
| 4634 | } |
| 4635 | elseif ($participantID) { |
| 4636 | $eventTitle = Participant::get(FALSE) |
| 4637 | ->addSelect('event.title') |
| 4638 | ->addWhere('id', '=', (int) $participantID) |
| 4639 | ->execute()->first()['event.title']; |
| 4640 | return ts('Online Event Registration') . ': ' . $eventTitle; |
| 4641 | } |
| 4642 | elseif (!empty($contribution->contribution_recur_id)) { |
| 4643 | return 'recurring contribution'; |
| 4644 | } |
| 4645 | return ''; |
| 4646 | } |
| 4647 | |
| 4648 | /** |
| 4649 | * Function use to store line item proportionally in in entity financial trxn table |
| 4650 | * |
| 4651 | * @param array $trxnParams |
| 4652 | * |
| 4653 | * @param int $trxnId |
| 4654 | * |
| 4655 | * @param float $contributionTotalAmount |
| 4656 | * |
| 4657 | * @throws \CiviCRM_API3_Exception |
| 4658 | */ |
| 4659 | public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) { |
| 4660 | $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($trxnParams['contribution_id']); |
| 4661 | if (!empty($lineItems)) { |
| 4662 | // get financial item |
| 4663 | list($ftIds, $taxItems) = self::getLastFinancialItemIds($trxnParams['contribution_id']); |
| 4664 | $entityParams = [ |
| 4665 | 'contribution_total_amount' => $contributionTotalAmount, |
| 4666 | 'trxn_total_amount' => $trxnParams['total_amount'], |
| 4667 | 'trxn_id' => $trxnId, |
| 4668 | ]; |
| 4669 | self::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems); |
| 4670 | } |
| 4671 | } |
| 4672 | |
| 4673 | /** |
| 4674 | * Checks if line items total amounts |
| 4675 | * match the contribution total amount. |
| 4676 | * |
| 4677 | * @param array $params |
| 4678 | * array of order params. |
| 4679 | * |
| 4680 | * @throws \API_Exception |
| 4681 | */ |
| 4682 | public static function checkLineItems(&$params) { |
| 4683 | $totalAmount = $params['total_amount'] ?? NULL; |
| 4684 | $lineItemAmount = 0; |
| 4685 | |
| 4686 | foreach ($params['line_items'] as &$lineItems) { |
| 4687 | foreach ($lineItems['line_item'] as &$item) { |
| 4688 | if (empty($item['financial_type_id'])) { |
| 4689 | $item['financial_type_id'] = $params['financial_type_id']; |
| 4690 | } |
| 4691 | $lineItemAmount += $item['line_total'] + ($item['tax_amount'] ?? 0.00); |
| 4692 | } |
| 4693 | } |
| 4694 | |
| 4695 | if (!isset($totalAmount)) { |
| 4696 | $params['total_amount'] = $lineItemAmount; |
| 4697 | } |
| 4698 | else { |
| 4699 | $currency = $params['currency'] ?? CRM_Core_Config::singleton()->defaultCurrency; |
| 4700 | |
| 4701 | if (!CRM_Utils_Money::equals($totalAmount, $lineItemAmount, $currency)) { |
| 4702 | throw new CRM_Contribute_Exception_CheckLineItemsException(); |
| 4703 | } |
| 4704 | } |
| 4705 | } |
| 4706 | |
| 4707 | /** |
| 4708 | * Get the financial account for the item associated with the new transaction. |
| 4709 | * |
| 4710 | * @param array $params |
| 4711 | * @param int $default |
| 4712 | * |
| 4713 | * @return int |
| 4714 | */ |
| 4715 | public static function getFinancialAccountForStatusChangeTrxn($params, $default) { |
| 4716 | |
| 4717 | if (!empty($params['financial_account_id'])) { |
| 4718 | return $params['financial_account_id']; |
| 4719 | } |
| 4720 | |
| 4721 | $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($params['contribution_status_id'], 'name'); |
| 4722 | $preferredAccountsRelationships = [ |
| 4723 | 'Refunded' => 'Credit/Contra Revenue Account is', |
| 4724 | 'Chargeback' => 'Chargeback Account is', |
| 4725 | ]; |
| 4726 | |
| 4727 | if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) { |
| 4728 | $financialTypeID = !empty($params['financial_type_id']) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id; |
| 4729 | return CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship( |
| 4730 | $financialTypeID, |
| 4731 | $preferredAccountsRelationships[$contributionStatus] |
| 4732 | ); |
| 4733 | } |
| 4734 | |
| 4735 | return $default; |
| 4736 | } |
| 4737 | |
| 4738 | /** |
| 4739 | * ContributionPage values were being imposed onto values. |
| 4740 | * |
| 4741 | * I have made this explicit and removed the couple (is_recur, is_pay_later) we |
| 4742 | * REALLY didn't want superimposed. The rest are left there in their overkill out |
| 4743 | * of cautiousness. |
| 4744 | * |
| 4745 | * The rationale for making this explicit is that it was a case of carefully set values being |
| 4746 | * seemingly randonly overwritten without much care. In general I think array randomly setting |
| 4747 | * variables en mass is risky. |
| 4748 | * |
| 4749 | * @param array $values |
| 4750 | * |
| 4751 | * @return array |
| 4752 | */ |
| 4753 | protected function addContributionPageValuesToValuesHeavyHandedly(&$values) { |
| 4754 | $contributionPageValues = []; |
| 4755 | CRM_Contribute_BAO_ContributionPage::setValues( |
| 4756 | $this->contribution_page_id, |
| 4757 | $contributionPageValues |
| 4758 | ); |
| 4759 | $valuesToCopy = [ |
| 4760 | // These are the values that I believe to be useful. |
| 4761 | 'id', |
| 4762 | 'title', |
| 4763 | 'pay_later_receipt', |
| 4764 | 'pay_later_text', |
| 4765 | 'receipt_from_email', |
| 4766 | 'receipt_from_name', |
| 4767 | 'receipt_text', |
| 4768 | 'custom_pre_id', |
| 4769 | 'custom_post_id', |
| 4770 | 'honoree_profile_id', |
| 4771 | 'onbehalf_profile_id', |
| 4772 | 'honor_block_is_active', |
| 4773 | // Kinda might be - but would be on the contribution... |
| 4774 | 'campaign_id', |
| 4775 | 'currency', |
| 4776 | // Included for 'fear of regression' but can't justify any use for these.... |
| 4777 | 'intro_text', |
| 4778 | 'payment_processor', |
| 4779 | 'financial_type_id', |
| 4780 | 'amount_block_is_active', |
| 4781 | 'bcc_receipt', |
| 4782 | 'cc_receipt', |
| 4783 | 'created_date', |
| 4784 | 'created_id', |
| 4785 | 'default_amount_id', |
| 4786 | 'end_date', |
| 4787 | 'footer_text', |
| 4788 | 'goal_amount', |
| 4789 | 'initial_amount_help_text', |
| 4790 | 'initial_amount_label', |
| 4791 | 'intro_text', |
| 4792 | 'is_allow_other_amount', |
| 4793 | 'is_billing_required', |
| 4794 | 'is_confirm_enabled', |
| 4795 | 'is_credit_card_only', |
| 4796 | 'is_monetary', |
| 4797 | 'is_partial_payment', |
| 4798 | 'is_recur_installments', |
| 4799 | 'is_recur_interval', |
| 4800 | 'is_share', |
| 4801 | 'max_amount', |
| 4802 | 'min_amount', |
| 4803 | 'min_initial_amount', |
| 4804 | 'recur_frequency_unit', |
| 4805 | 'start_date', |
| 4806 | 'thankyou_footer', |
| 4807 | 'thankyou_text', |
| 4808 | 'thankyou_title', |
| 4809 | |
| 4810 | ]; |
| 4811 | foreach ($valuesToCopy as $valueToCopy) { |
| 4812 | if (isset($contributionPageValues[$valueToCopy])) { |
| 4813 | if ($valueToCopy === 'title') { |
| 4814 | $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils::getContributionPageTitle($this->contribution_page_id); |
| 4815 | } |
| 4816 | else { |
| 4817 | $values[$valueToCopy] = $contributionPageValues[$valueToCopy]; |
| 4818 | } |
| 4819 | } |
| 4820 | } |
| 4821 | return $values; |
| 4822 | } |
| 4823 | |
| 4824 | /** |
| 4825 | * Get values of CiviContribute Settings |
| 4826 | * and check if its enabled or not. |
| 4827 | * Note: The CiviContribute settings are stored as single entry in civicrm_setting |
| 4828 | * in serialized form. Usually this should be stored as flat settings for each form fields |
| 4829 | * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute |
| 4830 | * settings we will live with an inconsistency because it's too hard to change for now. |
| 4831 | * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245 |
| 4832 | * |
| 4833 | * |
| 4834 | * @param string $name |
| 4835 | * |
| 4836 | * @return string |
| 4837 | * |
| 4838 | */ |
| 4839 | public static function checkContributeSettings($name) { |
| 4840 | $contributeSettings = Civi::settings()->get('contribution_invoice_settings'); |
| 4841 | return $contributeSettings[$name] ?? NULL; |
| 4842 | } |
| 4843 | |
| 4844 | /** |
| 4845 | * This function process contribution related objects. |
| 4846 | * |
| 4847 | * @param int $contributionId |
| 4848 | * @param int $statusId |
| 4849 | * @param int|null $previousStatusId |
| 4850 | * |
| 4851 | * @param string $receiveDate |
| 4852 | * |
| 4853 | * @return null|string |
| 4854 | */ |
| 4855 | public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) { |
| 4856 | $statusMsg = NULL; |
| 4857 | if (!$contributionId || !$statusId) { |
| 4858 | return $statusMsg; |
| 4859 | } |
| 4860 | |
| 4861 | $params = [ |
| 4862 | 'contribution_id' => $contributionId, |
| 4863 | 'contribution_status_id' => $statusId, |
| 4864 | 'previous_contribution_status_id' => $previousStatusId, |
| 4865 | 'receive_date' => $receiveDate, |
| 4866 | ]; |
| 4867 | |
| 4868 | $updateResult = CRM_Contribute_BAO_Contribution::transitionComponents($params); |
| 4869 | |
| 4870 | if (!is_array($updateResult) || |
| 4871 | !($updatedComponents = CRM_Utils_Array::value('updatedComponents', $updateResult)) || |
| 4872 | !is_array($updatedComponents) || |
| 4873 | empty($updatedComponents) |
| 4874 | ) { |
| 4875 | return $statusMsg; |
| 4876 | } |
| 4877 | |
| 4878 | // get the user display name. |
| 4879 | $sql = " |
| 4880 | SELECT display_name as displayName |
| 4881 | FROM civicrm_contact |
| 4882 | LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id ) |
| 4883 | WHERE civicrm_contribution.id = {$contributionId}"; |
| 4884 | $userDisplayName = CRM_Core_DAO::singleValueQuery($sql); |
| 4885 | |
| 4886 | // get the status message for user. |
| 4887 | foreach ($updatedComponents as $componentName => $updatedStatusId) { |
| 4888 | |
| 4889 | if ($componentName == 'CiviMember') { |
| 4890 | $updatedStatusName = CRM_Utils_Array::value($updatedStatusId, |
| 4891 | CRM_Member_PseudoConstant::membershipStatus() |
| 4892 | ); |
| 4893 | |
| 4894 | $statusNameMsgPart = 'updated'; |
| 4895 | switch ($updatedStatusName) { |
| 4896 | case 'Cancelled': |
| 4897 | case 'Expired': |
| 4898 | $statusNameMsgPart = $updatedStatusName; |
| 4899 | break; |
| 4900 | } |
| 4901 | |
| 4902 | $statusMsg .= "<br />" . ts("Membership for %1 has been %2.", [ |
| 4903 | 1 => $userDisplayName, |
| 4904 | 2 => $statusNameMsgPart, |
| 4905 | ]); |
| 4906 | } |
| 4907 | |
| 4908 | if ($componentName == 'CiviEvent') { |
| 4909 | $updatedStatusName = CRM_Utils_Array::value($updatedStatusId, |
| 4910 | CRM_Event_PseudoConstant::participantStatus() |
| 4911 | ); |
| 4912 | if ($updatedStatusName == 'Cancelled') { |
| 4913 | $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", [1 => $userDisplayName]); |
| 4914 | } |
| 4915 | elseif ($updatedStatusName == 'Registered') { |
| 4916 | $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", [1 => $userDisplayName]); |
| 4917 | } |
| 4918 | } |
| 4919 | |
| 4920 | if ($componentName == 'CiviPledge') { |
| 4921 | $updatedStatusName = CRM_Utils_Array::value($updatedStatusId, |
| 4922 | CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name') |
| 4923 | ); |
| 4924 | if ($updatedStatusName == 'Cancelled') { |
| 4925 | $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", [1 => $userDisplayName]); |
| 4926 | } |
| 4927 | elseif ($updatedStatusName == 'Failed') { |
| 4928 | $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", [1 => $userDisplayName]); |
| 4929 | } |
| 4930 | elseif ($updatedStatusName == 'Completed') { |
| 4931 | $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", [1 => $userDisplayName]); |
| 4932 | } |
| 4933 | } |
| 4934 | } |
| 4935 | |
| 4936 | return $statusMsg; |
| 4937 | } |
| 4938 | |
| 4939 | /** |
| 4940 | * Get the contribution as it is in the database before being updated. |
| 4941 | * |
| 4942 | * @param int $contributionID |
| 4943 | * |
| 4944 | * @return \CRM_Contribute_BAO_Contribution|null |
| 4945 | */ |
| 4946 | private static function getOriginalContribution($contributionID) { |
| 4947 | return self::getValues(['id' => $contributionID]); |
| 4948 | } |
| 4949 | |
| 4950 | /** |
| 4951 | * Get the amount for the financial item row. |
| 4952 | * |
| 4953 | * Helper function to start to break down recordFinancialTransactions for readability. |
| 4954 | * |
| 4955 | * The logic is more historical than .. logical. Paths other than the deprecated one are tested. |
| 4956 | * |
| 4957 | * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts |
| 4958 | * for historical reasons. Going forwards we can hope to add tests & improve readibility |
| 4959 | * of that function |
| 4960 | * |
| 4961 | * @param array $params |
| 4962 | * Params as passed to contribution.create |
| 4963 | * |
| 4964 | * @param string $context |
| 4965 | * changeFinancialType| changedAmount |
| 4966 | * @param array $lineItemDetails |
| 4967 | * Line items. |
| 4968 | * @param bool $isARefund |
| 4969 | * Is this a refund / negative transaction. |
| 4970 | * @param int $previousLineItemTotal |
| 4971 | * |
| 4972 | * @return float |
| 4973 | * @todo move recordFinancialAccounts & helper functions to their own class? |
| 4974 | * |
| 4975 | */ |
| 4976 | protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) { |
| 4977 | if ($context == 'changedAmount') { |
| 4978 | $lineTotal = $lineItemDetails['line_total']; |
| 4979 | if ($lineTotal != $previousLineItemTotal) { |
| 4980 | $lineTotal -= $previousLineItemTotal; |
| 4981 | } |
| 4982 | return $lineTotal; |
| 4983 | } |
| 4984 | elseif ($context == 'changeFinancialType') { |
| 4985 | return -$lineItemDetails['line_total']; |
| 4986 | } |
| 4987 | elseif ($context == 'changedStatus') { |
| 4988 | $cancelledTaxAmount = 0; |
| 4989 | if ($isARefund) { |
| 4990 | $cancelledTaxAmount = CRM_Utils_Array::value('tax_amount', $lineItemDetails, '0.00'); |
| 4991 | } |
| 4992 | return self::getMultiplier($params['contribution']->contribution_status_id, $context) * ((float) $lineItemDetails['line_total'] + (float) $cancelledTaxAmount); |
| 4993 | } |
| 4994 | elseif ($context === NULL) { |
| 4995 | // erm, yes because? but, hey, it's tested. |
| 4996 | return $lineItemDetails['line_total']; |
| 4997 | } |
| 4998 | elseif (empty($lineItemDetails['line_total'])) { |
| 4999 | // follow legacy code path |
| 5000 | Civi::log() |
| 5001 | ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']); |
| 5002 | return $params['total_amount']; |
| 5003 | } |
| 5004 | else { |
| 5005 | return self::getMultiplier($params['contribution']->contribution_status_id, $context) * ((float) $lineItemDetails['line_total']); |
| 5006 | } |
| 5007 | } |
| 5008 | |
| 5009 | /** |
| 5010 | * Get the multiplier for adjusting rows. |
| 5011 | * |
| 5012 | * If we are dealing with a refund or cancellation then it will be a negative |
| 5013 | * amount to reflect the negative transaction. |
| 5014 | * |
| 5015 | * If we are changing Financial Type it will be a negative amount to |
| 5016 | * adjust down the old type. |
| 5017 | * |
| 5018 | * @param int $contribution_status_id |
| 5019 | * @param string $context |
| 5020 | * |
| 5021 | * @return int |
| 5022 | */ |
| 5023 | protected static function getMultiplier($contribution_status_id, $context) { |
| 5024 | if ($context == 'changeFinancialType' || self::isContributionStatusNegative($contribution_status_id)) { |
| 5025 | return -1; |
| 5026 | } |
| 5027 | return 1; |
| 5028 | } |
| 5029 | |
| 5030 | /** |
| 5031 | * Does this transaction reflect a payment instrument change. |
| 5032 | * |
| 5033 | * @param array $params |
| 5034 | * @param array $pendingStatuses |
| 5035 | * |
| 5036 | * @return bool |
| 5037 | */ |
| 5038 | protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) { |
| 5039 | $contributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id); |
| 5040 | |
| 5041 | if (array_key_exists('payment_instrument_id', $params)) { |
| 5042 | if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) && |
| 5043 | !CRM_Utils_System::isNull($params['payment_instrument_id']) |
| 5044 | ) { |
| 5045 | //check if status is changed from Pending to Completed |
| 5046 | // do not update payment instrument changes for Pending to Completed |
| 5047 | if (!($contributionStatus == 'Completed' && |
| 5048 | in_array($params['prevContribution']->contribution_status_id, $pendingStatuses)) |
| 5049 | ) { |
| 5050 | return TRUE; |
| 5051 | } |
| 5052 | } |
| 5053 | elseif ((!CRM_Utils_System::isNull($params['payment_instrument_id']) && |
| 5054 | !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) && |
| 5055 | $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id |
| 5056 | ) { |
| 5057 | return TRUE; |
| 5058 | } |
| 5059 | elseif (!CRM_Utils_System::isNull($params['contribution']->check_number) && |
| 5060 | $params['contribution']->check_number != $params['prevContribution']->check_number |
| 5061 | ) { |
| 5062 | // another special case when check number is changed, create new financial records |
| 5063 | // create financial trxn with negative amount |
| 5064 | return TRUE; |
| 5065 | } |
| 5066 | } |
| 5067 | return FALSE; |
| 5068 | } |
| 5069 | |
| 5070 | /** |
| 5071 | * Update the memberships associated with a contribution if it has been completed. |
| 5072 | * |
| 5073 | * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just |
| 5074 | * load them in this function. Code clean up would compensate for any minor performance implication. |
| 5075 | * |
| 5076 | * @param int $contributionID |
| 5077 | * @param string $changeDate |
| 5078 | * |
| 5079 | * @throws \CRM_Core_Exception |
| 5080 | * @throws \CiviCRM_API3_Exception |
| 5081 | */ |
| 5082 | public static function updateMembershipBasedOnCompletionOfContribution($contributionID, $changeDate) { |
| 5083 | $memberships = self::getRelatedMemberships($contributionID); |
| 5084 | foreach ($memberships as $membership) { |
| 5085 | $membershipParams = [ |
| 5086 | 'id' => $membership['id'], |
| 5087 | 'contact_id' => $membership['contact_id'], |
| 5088 | 'is_test' => $membership['is_test'], |
| 5089 | 'membership_type_id' => $membership['membership_type_id'], |
| 5090 | 'membership_activity_status' => 'Completed', |
| 5091 | ]; |
| 5092 | |
| 5093 | $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'], |
| 5094 | $membershipParams['membership_type_id'], |
| 5095 | $membershipParams['is_test'], |
| 5096 | $membershipParams['id'] |
| 5097 | ); |
| 5098 | |
| 5099 | // CRM-8141 update the membership type with the value recorded in log when membership created/renewed |
| 5100 | // this picks up membership type changes during renewals |
| 5101 | // @todo this is almost certainly an obsolete sql call, the pre-change |
| 5102 | // membership is accessible via $this->_relatedObjects |
| 5103 | $sql = " |
| 5104 | SELECT membership_type_id |
| 5105 | FROM civicrm_membership_log |
| 5106 | WHERE membership_id={$membershipParams['id']} |
| 5107 | ORDER BY id DESC |
| 5108 | LIMIT 1;"; |
| 5109 | $dao = CRM_Core_DAO::executeQuery($sql); |
| 5110 | if ($dao->fetch()) { |
| 5111 | if (!empty($dao->membership_type_id)) { |
| 5112 | $membershipParams['membership_type_id'] = $dao->membership_type_id; |
| 5113 | } |
| 5114 | } |
| 5115 | if (empty($membership['end_date']) || (int) $membership['status_id'] !== CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) { |
| 5116 | // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated. |
| 5117 | // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too? |
| 5118 | // The api assumes num_terms is a special sauce for 'is_renewal' so we need to not pass it when updating a pending to completed. |
| 5119 | // ... except testCompleteTransactionMembershipPriceSetTwoTerms hits this line so the above is obviously not true.... |
| 5120 | // @todo once apiv4 ships with core switch to that & find sanity. |
| 5121 | $membershipParams['num_terms'] = self::getNumTermsByContributionAndMembershipType( |
| 5122 | $membershipParams['membership_type_id'], |
| 5123 | $contributionID |
| 5124 | ); |
| 5125 | } |
| 5126 | // @todo remove all this stuff in favour of letting the api call further down handle in |
| 5127 | // (it is a duplication of what the api does). |
| 5128 | $dates = array_fill_keys([ |
| 5129 | 'join_date', |
| 5130 | 'start_date', |
| 5131 | 'end_date', |
| 5132 | ], NULL); |
| 5133 | if ($currentMembership) { |
| 5134 | /* |
| 5135 | * Fixed FOR CRM-4433 |
| 5136 | * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status |
| 5137 | * when Contribution mode is notify and membership is for renewal ) |
| 5138 | */ |
| 5139 | // Test cover for this is in testRepeattransactionRenewMembershipOldMembership |
| 5140 | // Be afraid. |
| 5141 | CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate); |
| 5142 | |
| 5143 | // @todo - we should pass membership_type_id instead of null here but not |
| 5144 | // adding as not sure of testing |
| 5145 | $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'], |
| 5146 | $changeDate, NULL, $membershipParams['num_terms'] |
| 5147 | ); |
| 5148 | $dates['join_date'] = $currentMembership['join_date']; |
| 5149 | } |
| 5150 | |
| 5151 | //get the status for membership. |
| 5152 | $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], |
| 5153 | $dates['end_date'], |
| 5154 | $dates['join_date'], |
| 5155 | 'today', |
| 5156 | TRUE, |
| 5157 | $membershipParams['membership_type_id'], |
| 5158 | $membershipParams |
| 5159 | ); |
| 5160 | |
| 5161 | unset($dates['end_date']); |
| 5162 | $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New'); |
| 5163 | //we might be renewing membership, |
| 5164 | //so make status override false. |
| 5165 | $membershipParams['is_override'] = FALSE; |
| 5166 | $membershipParams['status_override_end_date'] = 'null'; |
| 5167 | civicrm_api3('Membership', 'create', $membershipParams); |
| 5168 | } |
| 5169 | } |
| 5170 | |
| 5171 | /** |
| 5172 | * Get payment links as they relate to a contribution. |
| 5173 | * |
| 5174 | * If a payment can be made then include a payment link & if a refund is appropriate |
| 5175 | * then a refund link. |
| 5176 | * |
| 5177 | * @param int $id |
| 5178 | * @param float $balance |
| 5179 | * @param string $contributionStatus |
| 5180 | * |
| 5181 | * @return array |
| 5182 | * $actionLinks Links array containing: |
| 5183 | * -url |
| 5184 | * -title |
| 5185 | */ |
| 5186 | protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) { |
| 5187 | if ($contributionStatus === 'Failed' || !CRM_Core_Permission::check('edit contributions')) { |
| 5188 | // In general the balance is the best way to determine if a payment can be added or not, |
| 5189 | // but not for Failed contributions, where we don't accept additional payments at the moment. |
| 5190 | // (in some cases the contribution is 'Pending' and only the payment is failed. In those we |
| 5191 | // do accept more payments agains them. |
| 5192 | return []; |
| 5193 | } |
| 5194 | $actionLinks = []; |
| 5195 | $actionLinks[] = [ |
| 5196 | 'url' => CRM_Utils_System::url('civicrm/payment', [ |
| 5197 | 'action' => 'add', |
| 5198 | 'reset' => 1, |
| 5199 | 'id' => $id, |
| 5200 | 'is_refund' => 0, |
| 5201 | ]), |
| 5202 | 'title' => ts('Record Payment'), |
| 5203 | ]; |
| 5204 | |
| 5205 | if ((int) $balance > 0) { |
| 5206 | // @todo - this should be possible even if not > 0 - test & remove this if. |
| 5207 | // it is possible to 'overpay' in the real world & we honor that. |
| 5208 | if (CRM_Core_Config::isEnabledBackOfficeCreditCardPayments()) { |
| 5209 | $actionLinks[] = [ |
| 5210 | 'url' => CRM_Utils_System::url('civicrm/payment', [ |
| 5211 | 'action' => 'add', |
| 5212 | 'reset' => 1, |
| 5213 | 'is_refund' => 0, |
| 5214 | 'id' => $id, |
| 5215 | 'mode' => 'live', |
| 5216 | ]), |
| 5217 | 'title' => ts('Submit Credit Card payment'), |
| 5218 | ]; |
| 5219 | } |
| 5220 | } |
| 5221 | elseif ((int) $balance < 0) { |
| 5222 | // @todo - in the future remove this IF - OK to refund money even when not due since |
| 5223 | // ... life. |
| 5224 | $actionLinks[] = [ |
| 5225 | 'url' => CRM_Utils_System::url('civicrm/payment', [ |
| 5226 | 'action' => 'add', |
| 5227 | 'reset' => 1, |
| 5228 | 'id' => $id, |
| 5229 | 'is_refund' => 1, |
| 5230 | ]), |
| 5231 | 'title' => ts('Record Refund'), |
| 5232 | ]; |
| 5233 | } |
| 5234 | return $actionLinks; |
| 5235 | } |
| 5236 | |
| 5237 | /** |
| 5238 | * Get a query to determine the amount donated by the contact/s in the current financial year. |
| 5239 | * |
| 5240 | * @param array $contactIDs |
| 5241 | * |
| 5242 | * @return string |
| 5243 | */ |
| 5244 | public static function getAnnualQuery($contactIDs) { |
| 5245 | $contactIDs = implode(',', $contactIDs); |
| 5246 | $config = CRM_Core_Config::singleton(); |
| 5247 | $currentMonth = date('m'); |
| 5248 | $currentDay = date('d'); |
| 5249 | if ( |
| 5250 | (int) $config->fiscalYearStart['M'] > $currentMonth || |
| 5251 | ( |
| 5252 | (int) $config->fiscalYearStart['M'] == $currentMonth && |
| 5253 | (int) $config->fiscalYearStart['d'] > $currentDay |
| 5254 | ) |
| 5255 | ) { |
| 5256 | $year = date('Y') - 1; |
| 5257 | } |
| 5258 | else { |
| 5259 | $year = date('Y'); |
| 5260 | } |
| 5261 | $nextYear = $year + 1; |
| 5262 | |
| 5263 | if ($config->fiscalYearStart) { |
| 5264 | $newFiscalYearStart = $config->fiscalYearStart; |
| 5265 | if ($newFiscalYearStart['M'] < 10) { |
| 5266 | // This is just a clumsy way of adding padding. |
| 5267 | // @todo next round look for a nicer way. |
| 5268 | $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M']; |
| 5269 | } |
| 5270 | if ($newFiscalYearStart['d'] < 10) { |
| 5271 | // This is just a clumsy way of adding padding. |
| 5272 | // @todo next round look for a nicer way. |
| 5273 | $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d']; |
| 5274 | } |
| 5275 | $config->fiscalYearStart = $newFiscalYearStart; |
| 5276 | $monthDay = $config->fiscalYearStart['M'] . $config->fiscalYearStart['d']; |
| 5277 | } |
| 5278 | else { |
| 5279 | // First of January. |
| 5280 | $monthDay = '0101'; |
| 5281 | } |
| 5282 | $startDate = "$year$monthDay"; |
| 5283 | $endDate = "$nextYear$monthDay"; |
| 5284 | |
| 5285 | $whereClauses = [ |
| 5286 | 'contact_id' => 'IN (' . $contactIDs . ')', |
| 5287 | 'is_test' => ' = 0', |
| 5288 | 'receive_date' => ['>=' . $startDate, '< ' . $endDate], |
| 5289 | ]; |
| 5290 | $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'); |
| 5291 | CRM_Financial_BAO_FinancialType::addACLClausesToWhereClauses($whereClauses); |
| 5292 | |
| 5293 | $clauses = []; |
| 5294 | foreach ($whereClauses as $key => $clause) { |
| 5295 | $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause); |
| 5296 | } |
| 5297 | $whereClauseString = implode(' AND ', $clauses); |
| 5298 | |
| 5299 | // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how |
| 5300 | // this group by + having on contribution_status_id improves performance |
| 5301 | $query = " |
| 5302 | SELECT COUNT(*) as count, |
| 5303 | SUM(total_amount) as amount, |
| 5304 | AVG(total_amount) as average, |
| 5305 | currency |
| 5306 | FROM civicrm_contribution b |
| 5307 | WHERE " . $whereClauseString . " |
| 5308 | GROUP BY currency, contribution_status_id |
| 5309 | HAVING $havingClause |
| 5310 | "; |
| 5311 | return $query; |
| 5312 | } |
| 5313 | |
| 5314 | /** |
| 5315 | * Assign Test Value. |
| 5316 | * |
| 5317 | * @param string $fieldName |
| 5318 | * @param array $fieldDef |
| 5319 | * @param int $counter |
| 5320 | */ |
| 5321 | protected function assignTestValue($fieldName, &$fieldDef, $counter) { |
| 5322 | if ($fieldName == 'tax_amount') { |
| 5323 | $this->{$fieldName} = "0.00"; |
| 5324 | } |
| 5325 | elseif ($fieldName == 'net_amount') { |
| 5326 | $this->{$fieldName} = "2.00"; |
| 5327 | } |
| 5328 | elseif ($fieldName == 'total_amount') { |
| 5329 | $this->{$fieldName} = "3.00"; |
| 5330 | } |
| 5331 | elseif ($fieldName == 'fee_amount') { |
| 5332 | $this->{$fieldName} = "1.00"; |
| 5333 | } |
| 5334 | else { |
| 5335 | parent::assignTestValues($fieldName, $fieldDef, $counter); |
| 5336 | } |
| 5337 | } |
| 5338 | |
| 5339 | /** |
| 5340 | * Check if contribution has participant/membership payment. |
| 5341 | * |
| 5342 | * @param int $contributionId |
| 5343 | * Contribution ID |
| 5344 | * |
| 5345 | * @return bool |
| 5346 | */ |
| 5347 | public static function allowUpdateRevenueRecognitionDate($contributionId) { |
| 5348 | // get line item for contribution |
| 5349 | $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionId); |
| 5350 | // check if line item is for membership or participant |
| 5351 | foreach ($lineItems as $items) { |
| 5352 | if ($items['entity_table'] == 'civicrm_participant') { |
| 5353 | $flag = FALSE; |
| 5354 | break; |
| 5355 | } |
| 5356 | elseif ($items['entity_table'] == 'civicrm_membership') { |
| 5357 | $flag = FALSE; |
| 5358 | } |
| 5359 | else { |
| 5360 | $flag = TRUE; |
| 5361 | break; |
| 5362 | } |
| 5363 | } |
| 5364 | return $flag; |
| 5365 | } |
| 5366 | |
| 5367 | /** |
| 5368 | * Create Accounts Receivable financial trxn entry for Completed Contribution. |
| 5369 | * |
| 5370 | * @param array $trxnParams |
| 5371 | * Financial trxn params |
| 5372 | * @param array $contributionParams |
| 5373 | * Contribution Params |
| 5374 | * |
| 5375 | * @return null |
| 5376 | */ |
| 5377 | public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) { |
| 5378 | if (!Civi::settings()->get('always_post_to_accounts_receivable')) { |
| 5379 | return NULL; |
| 5380 | } |
| 5381 | $statusId = $contributionParams['contribution']->contribution_status_id; |
| 5382 | $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
| 5383 | $contributionStatus = empty($statusId) ? NULL : $contributionStatuses[$statusId]; |
| 5384 | $previousContributionStatus = empty($contributionParams['prevContribution']) ? NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id]; |
| 5385 | // Return if contribution status is not completed. |
| 5386 | if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus) |
| 5387 | || (!empty($previousContributionStatus) && $previousContributionStatus == 'Pending' |
| 5388 | && $contributionParams['prevContribution']->is_pay_later == 0 |
| 5389 | ))) |
| 5390 | ) { |
| 5391 | return NULL; |
| 5392 | } |
| 5393 | |
| 5394 | $params = $trxnParams; |
| 5395 | $financialTypeID = !empty($contributionParams['financial_type_id']) ? $contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id; |
| 5396 | $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is'); |
| 5397 | $params['to_financial_account_id'] = $arAccountId; |
| 5398 | $params['status_id'] = array_search('Pending', $contributionStatuses); |
| 5399 | $params['is_payment'] = FALSE; |
| 5400 | $trxn = CRM_Core_BAO_FinancialTrxn::create($params); |
| 5401 | self::$_trxnIDs[] = $trxn->id; |
| 5402 | $trxnParams['from_financial_account_id'] = $params['to_financial_account_id']; |
| 5403 | } |
| 5404 | |
| 5405 | /** |
| 5406 | * Calculate financial item amount when contribution is updated. |
| 5407 | * |
| 5408 | * @param array $params |
| 5409 | * contribution params |
| 5410 | * @param array $amountParams |
| 5411 | * |
| 5412 | * @param string $context |
| 5413 | * |
| 5414 | * @return float |
| 5415 | */ |
| 5416 | public static function calculateFinancialItemAmount($params, $amountParams, $context) { |
| 5417 | if (!empty($params['is_quick_config'])) { |
| 5418 | $amount = $amountParams['item_amount']; |
| 5419 | if (!$amount) { |
| 5420 | $amount = $params['total_amount']; |
| 5421 | if ($context === NULL) { |
| 5422 | $amount -= CRM_Utils_Array::value('tax_amount', $params, 0); |
| 5423 | } |
| 5424 | } |
| 5425 | } |
| 5426 | else { |
| 5427 | $amount = $amountParams['line_total']; |
| 5428 | if ($context == 'changedAmount') { |
| 5429 | $amount -= $amountParams['previous_line_total']; |
| 5430 | } |
| 5431 | $amount *= $amountParams['diff']; |
| 5432 | } |
| 5433 | return $amount; |
| 5434 | } |
| 5435 | |
| 5436 | /** |
| 5437 | * Retrieve Sales Tax Financial Accounts. |
| 5438 | * |
| 5439 | * |
| 5440 | * @return array |
| 5441 | * |
| 5442 | */ |
| 5443 | public static function getSalesTaxFinancialAccounts() { |
| 5444 | $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce |
| 5445 | INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id |
| 5446 | WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id"; |
| 5447 | $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")); |
| 5448 | $queryParams = [1 => [$accountRel, 'Integer']]; |
| 5449 | $dao = CRM_Core_DAO::executeQuery($query, $queryParams); |
| 5450 | $financialAccount = []; |
| 5451 | while ($dao->fetch()) { |
| 5452 | $financialAccount[$dao->id] = $dao->id; |
| 5453 | } |
| 5454 | return $financialAccount; |
| 5455 | } |
| 5456 | |
| 5457 | /** |
| 5458 | * Create tax entry in civicrm_entity_financial_trxn table. |
| 5459 | * |
| 5460 | * @param array $entityParams |
| 5461 | * |
| 5462 | * @param array $eftParams |
| 5463 | * |
| 5464 | * @throws \CiviCRM_API3_Exception |
| 5465 | */ |
| 5466 | public static function createProportionalEntry($entityParams, $eftParams) { |
| 5467 | $paid = 0; |
| 5468 | if ($entityParams['contribution_total_amount'] != 0) { |
| 5469 | $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']); |
| 5470 | } |
| 5471 | // Record Entity Financial Trxn; CRM-20145 |
| 5472 | $eftParams['amount'] = $paid; |
| 5473 | civicrm_api3('EntityFinancialTrxn', 'create', $eftParams); |
| 5474 | } |
| 5475 | |
| 5476 | /** |
| 5477 | * Create array of last financial item id's. |
| 5478 | * |
| 5479 | * @param int $contributionId |
| 5480 | * |
| 5481 | * @return array |
| 5482 | */ |
| 5483 | public static function getLastFinancialItemIds($contributionId) { |
| 5484 | $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id |
| 5485 | FROM civicrm_financial_item fi |
| 5486 | INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item' |
| 5487 | WHERE li.contribution_id = %1"; |
| 5488 | $dao = CRM_Core_DAO::executeQuery($sql, [ |
| 5489 | 1 => [ |
| 5490 | $contributionId, |
| 5491 | 'Integer', |
| 5492 | ], |
| 5493 | ]); |
| 5494 | $ftIds = $taxItems = []; |
| 5495 | $salesTaxFinancialAccount = self::getSalesTaxFinancialAccounts(); |
| 5496 | while ($dao->fetch()) { |
| 5497 | /* if sales tax item*/ |
| 5498 | if (in_array($dao->financial_account_id, $salesTaxFinancialAccount)) { |
| 5499 | $taxItems[$dao->price_field_value_id] = [ |
| 5500 | 'financial_item_id' => $dao->id, |
| 5501 | 'amount' => $dao->tax_amount, |
| 5502 | ]; |
| 5503 | } |
| 5504 | else { |
| 5505 | $ftIds[$dao->price_field_value_id] = $dao->id; |
| 5506 | } |
| 5507 | } |
| 5508 | return [$ftIds, $taxItems]; |
| 5509 | } |
| 5510 | |
| 5511 | /** |
| 5512 | * Create proportional entries in civicrm_entity_financial_trxn. |
| 5513 | * |
| 5514 | * @param array $entityParams |
| 5515 | * |
| 5516 | * @param array $lineItems |
| 5517 | * |
| 5518 | * @param array $ftIds |
| 5519 | * |
| 5520 | * @param array $taxItems |
| 5521 | * |
| 5522 | * @throws \CiviCRM_API3_Exception |
| 5523 | */ |
| 5524 | public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) { |
| 5525 | $eftParams = [ |
| 5526 | 'entity_table' => 'civicrm_financial_item', |
| 5527 | 'financial_trxn_id' => $entityParams['trxn_id'], |
| 5528 | ]; |
| 5529 | foreach ($lineItems as $key => $value) { |
| 5530 | if ($value['qty'] == 0) { |
| 5531 | continue; |
| 5532 | } |
| 5533 | $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']]; |
| 5534 | $entityParams['line_item_amount'] = $value['line_total']; |
| 5535 | self::createProportionalEntry($entityParams, $eftParams); |
| 5536 | if (array_key_exists($value['price_field_value_id'], $taxItems)) { |
| 5537 | $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount']; |
| 5538 | $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id']; |
| 5539 | self::createProportionalEntry($entityParams, $eftParams); |
| 5540 | } |
| 5541 | } |
| 5542 | } |
| 5543 | |
| 5544 | /** |
| 5545 | * Load entities related to the contribution into $this->_relatedObjects. |
| 5546 | * |
| 5547 | * @param array $ids |
| 5548 | * |
| 5549 | * @throws \CRM_Core_Exception |
| 5550 | */ |
| 5551 | protected function loadRelatedEntitiesByID($ids) { |
| 5552 | $entities = [ |
| 5553 | 'contact' => 'CRM_Contact_BAO_Contact', |
| 5554 | 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur', |
| 5555 | 'contributionType' => 'CRM_Financial_BAO_FinancialType', |
| 5556 | 'financialType' => 'CRM_Financial_BAO_FinancialType', |
| 5557 | 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage', |
| 5558 | ]; |
| 5559 | foreach ($entities as $entity => $bao) { |
| 5560 | if (!empty($ids[$entity])) { |
| 5561 | $this->_relatedObjects[$entity] = new $bao(); |
| 5562 | $this->_relatedObjects[$entity]->id = $ids[$entity]; |
| 5563 | if (!$this->_relatedObjects[$entity]->find(TRUE)) { |
| 5564 | throw new CRM_Core_Exception($entity . ' could not be loaded'); |
| 5565 | } |
| 5566 | } |
| 5567 | } |
| 5568 | } |
| 5569 | |
| 5570 | /** |
| 5571 | * Function to replace contribution tokens. |
| 5572 | * |
| 5573 | * @param array $contributionIds |
| 5574 | * |
| 5575 | * @param string $subject |
| 5576 | * |
| 5577 | * @param array $subjectToken |
| 5578 | * |
| 5579 | * @param string $text |
| 5580 | * |
| 5581 | * @param string $html |
| 5582 | * |
| 5583 | * @param array $messageToken |
| 5584 | * |
| 5585 | * @param bool $escapeSmarty |
| 5586 | * |
| 5587 | * @return array |
| 5588 | * @throws \CiviCRM_API3_Exception |
| 5589 | */ |
| 5590 | public static function replaceContributionTokens( |
| 5591 | $contributionIds, |
| 5592 | $subject, |
| 5593 | $subjectToken, |
| 5594 | $text, |
| 5595 | $html, |
| 5596 | $messageToken, |
| 5597 | $escapeSmarty |
| 5598 | ) { |
| 5599 | if (empty($contributionIds)) { |
| 5600 | return []; |
| 5601 | } |
| 5602 | $contributionDetails = []; |
| 5603 | foreach ($contributionIds as $id) { |
| 5604 | $result = self::getContributionTokenValues($id, $messageToken); |
| 5605 | $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty); |
| 5606 | $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty); |
| 5607 | $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty); |
| 5608 | } |
| 5609 | return $contributionDetails; |
| 5610 | } |
| 5611 | |
| 5612 | /** |
| 5613 | * Get the contribution fields for $id and display labels where |
| 5614 | * appropriate (if the token is present). |
| 5615 | * |
| 5616 | * @param int $id |
| 5617 | * @param array $messageToken |
| 5618 | * @return array |
| 5619 | */ |
| 5620 | public static function getContributionTokenValues($id, $messageToken) { |
| 5621 | if (empty($id)) { |
| 5622 | return []; |
| 5623 | } |
| 5624 | $result = civicrm_api3('Contribution', 'get', ['id' => $id]); |
| 5625 | // lab.c.o mail#46 - show labels, not values, for custom fields with option values. |
| 5626 | if (!empty($messageToken)) { |
| 5627 | foreach ($result['values'][$id] as $fieldName => $fieldValue) { |
| 5628 | if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) { |
| 5629 | $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField::displayValue($result['values'][$id][$fieldName], $fieldName); |
| 5630 | } |
| 5631 | } |
| 5632 | } |
| 5633 | return $result; |
| 5634 | } |
| 5635 | |
| 5636 | /** |
| 5637 | * Get invoice_number for contribution. |
| 5638 | * |
| 5639 | * @param int $contributionID |
| 5640 | * |
| 5641 | * @return string |
| 5642 | */ |
| 5643 | public static function getInvoiceNumber($contributionID) { |
| 5644 | if ($invoicePrefix = self::checkContributeSettings('invoice_prefix')) { |
| 5645 | return $invoicePrefix . $contributionID; |
| 5646 | } |
| 5647 | |
| 5648 | return NULL; |
| 5649 | } |
| 5650 | |
| 5651 | /** |
| 5652 | * Load the values needed for the event message. |
| 5653 | * |
| 5654 | * @param int $eventID |
| 5655 | * @param int $participantID |
| 5656 | * @param int|null $contributionID |
| 5657 | * |
| 5658 | * @return array |
| 5659 | * @throws \CRM_Core_Exception |
| 5660 | */ |
| 5661 | protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array { |
| 5662 | |
| 5663 | $eventParams = [ |
| 5664 | 'id' => $eventID, |
| 5665 | ]; |
| 5666 | $values = ['event' => []]; |
| 5667 | |
| 5668 | CRM_Event_BAO_Event::retrieve($eventParams, $values['event']); |
| 5669 | // add custom fields for event |
| 5670 | $eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Event', NULL, $eventID); |
| 5671 | |
| 5672 | $eventCustomGroup = []; |
| 5673 | foreach ($eventGroupTree as $key => $group) { |
| 5674 | if ($key === 'info') { |
| 5675 | continue; |
| 5676 | } |
| 5677 | |
| 5678 | foreach ($group['fields'] as $k => $customField) { |
| 5679 | $groupLabel = $group['title']; |
| 5680 | if (!empty($customField['customValue'])) { |
| 5681 | foreach ($customField['customValue'] as $customFieldValues) { |
| 5682 | $eventCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ?? NULL; |
| 5683 | } |
| 5684 | } |
| 5685 | } |
| 5686 | } |
| 5687 | $values['event']['customGroup'] = $eventCustomGroup; |
| 5688 | |
| 5689 | //get participant details |
| 5690 | $participantParams = [ |
| 5691 | 'id' => $participantID, |
| 5692 | ]; |
| 5693 | |
| 5694 | $values['participant'] = []; |
| 5695 | |
| 5696 | CRM_Event_BAO_Participant::getValues($participantParams, $values['participant'], $participantIds); |
| 5697 | // add custom fields for event |
| 5698 | $participantGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', NULL, $participantID); |
| 5699 | $participantCustomGroup = []; |
| 5700 | foreach ($participantGroupTree as $key => $group) { |
| 5701 | if ($key === 'info') { |
| 5702 | continue; |
| 5703 | } |
| 5704 | |
| 5705 | foreach ($group['fields'] as $k => $customField) { |
| 5706 | $groupLabel = $group['title']; |
| 5707 | if (!empty($customField['customValue'])) { |
| 5708 | foreach ($customField['customValue'] as $customFieldValues) { |
| 5709 | $participantCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ?? NULL; |
| 5710 | } |
| 5711 | } |
| 5712 | } |
| 5713 | } |
| 5714 | $values['participant']['customGroup'] = $participantCustomGroup; |
| 5715 | |
| 5716 | //get location details |
| 5717 | $locationParams = [ |
| 5718 | 'entity_id' => $eventID, |
| 5719 | 'entity_table' => 'civicrm_event', |
| 5720 | ]; |
| 5721 | $values['location'] = CRM_Core_BAO_Location::getValues($locationParams); |
| 5722 | |
| 5723 | $ufJoinParams = [ |
| 5724 | 'entity_table' => 'civicrm_event', |
| 5725 | 'entity_id' => $eventID, |
| 5726 | 'module' => 'CiviEvent', |
| 5727 | ]; |
| 5728 | |
| 5729 | list($custom_pre_id, |
| 5730 | $custom_post_ids |
| 5731 | ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); |
| 5732 | |
| 5733 | $values['custom_pre_id'] = $custom_pre_id; |
| 5734 | $values['custom_post_id'] = $custom_post_ids; |
| 5735 | |
| 5736 | // set lineItem for event contribution |
| 5737 | if ($contributionID) { |
| 5738 | $participantIds = CRM_Event_BAO_Participant::getParticipantIds($contributionID); |
| 5739 | if (!empty($participantIds)) { |
| 5740 | foreach ($participantIds as $pIDs) { |
| 5741 | $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs); |
| 5742 | if (!CRM_Utils_System::isNull($lineItem)) { |
| 5743 | $values['lineItem'][] = $lineItem; |
| 5744 | } |
| 5745 | } |
| 5746 | } |
| 5747 | } |
| 5748 | return $values; |
| 5749 | } |
| 5750 | |
| 5751 | } |