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