| 1 | <?php |
| 2 | /* |
| 3 | +--------------------------------------------------------------------+ |
| 4 | | CiviCRM version 4.7 | |
| 5 | +--------------------------------------------------------------------+ |
| 6 | | Copyright CiviCRM LLC (c) 2004-2015 | |
| 7 | +--------------------------------------------------------------------+ |
| 8 | | This file is a part of CiviCRM. | |
| 9 | | | |
| 10 | | CiviCRM is free software; you can copy, modify, and distribute it | |
| 11 | | under the terms of the GNU Affero General Public License | |
| 12 | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | |
| 13 | | | |
| 14 | | CiviCRM is distributed in the hope that it will be useful, but | |
| 15 | | WITHOUT ANY WARRANTY; without even the implied warranty of | |
| 16 | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | |
| 17 | | See the GNU Affero General Public License for more details. | |
| 18 | | | |
| 19 | | You should have received a copy of the GNU Affero General Public | |
| 20 | | License and the CiviCRM Licensing Exception along | |
| 21 | | with this program; if not, contact CiviCRM LLC | |
| 22 | | at info[AT]civicrm[DOT]org. If you have questions about the | |
| 23 | | GNU Affero General Public License or the licensing of CiviCRM, | |
| 24 | | see the CiviCRM license FAQ at http://civicrm.org/licensing | |
| 25 | +--------------------------------------------------------------------+ |
| 26 | */ |
| 27 | |
| 28 | /** |
| 29 | * |
| 30 | * @package CRM |
| 31 | * @copyright CiviCRM LLC (c) 2004-2015 |
| 32 | */ |
| 33 | class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution { |
| 34 | |
| 35 | /** |
| 36 | * Static field for all the contribution information that we can potentially import |
| 37 | * |
| 38 | * @var array |
| 39 | */ |
| 40 | static $_importableFields = NULL; |
| 41 | |
| 42 | /** |
| 43 | * Static field for all the contribution information that we can potentially export |
| 44 | * |
| 45 | * @var array |
| 46 | */ |
| 47 | static $_exportableFields = NULL; |
| 48 | |
| 49 | /** |
| 50 | * Field for all the objects related to this contribution |
| 51 | * @var array of objects (e.g membership object, participant object) |
| 52 | */ |
| 53 | public $_relatedObjects = array(); |
| 54 | |
| 55 | /** |
| 56 | * Field for the component - either 'event' (participant) or 'contribute' |
| 57 | * (any item related to a contribution page e.g. membership, pledge, contribution) |
| 58 | * This is used for composing messages because they have dependency on the |
| 59 | * contribution_page or event page - although over time we may eliminate that |
| 60 | * |
| 61 | * @var string component or event |
| 62 | */ |
| 63 | public $_component = NULL; |
| 64 | |
| 65 | /** |
| 66 | * Possibly obsolete variable. |
| 67 | * |
| 68 | * If you use it please explain why it is set in the create function here. |
| 69 | * |
| 70 | * @var string |
| 71 | */ |
| 72 | public $trxn_result_code; |
| 73 | |
| 74 | /** |
| 75 | * Class constructor. |
| 76 | * |
| 77 | * @return \CRM_Contribute_DAO_Contribution |
| 78 | */ |
| 79 | /** |
| 80 | */ |
| 81 | public function __construct() { |
| 82 | parent::__construct(); |
| 83 | } |
| 84 | |
| 85 | /** |
| 86 | * Takes an associative array and creates a contribution object. |
| 87 | * |
| 88 | * the function extract all the params it needs to initialize the create a |
| 89 | * contribution object. the params array could contain additional unused name/value |
| 90 | * pairs |
| 91 | * |
| 92 | * @param array $params |
| 93 | * (reference ) an assoc array of name/value pairs. |
| 94 | * @param array $ids |
| 95 | * The array that holds all the db ids. |
| 96 | * |
| 97 | * @return CRM_Contribute_BAO_Contribution|void |
| 98 | */ |
| 99 | public static function add(&$params, $ids = array()) { |
| 100 | if (empty($params)) { |
| 101 | return NULL; |
| 102 | } |
| 103 | //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array |
| 104 | $contributionID = CRM_Utils_Array::value('contribution', $ids, CRM_Utils_Array::value('id', $params)); |
| 105 | $duplicates = array(); |
| 106 | if (self::checkDuplicate($params, $duplicates, $contributionID)) { |
| 107 | $error = CRM_Core_Error::singleton(); |
| 108 | $d = implode(', ', $duplicates); |
| 109 | $error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION, |
| 110 | 'Fatal', |
| 111 | array($d), |
| 112 | "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d" |
| 113 | ); |
| 114 | return $error; |
| 115 | } |
| 116 | |
| 117 | // first clean up all the money fields |
| 118 | $moneyFields = array( |
| 119 | 'total_amount', |
| 120 | 'net_amount', |
| 121 | 'fee_amount', |
| 122 | 'non_deductible_amount', |
| 123 | ); |
| 124 | |
| 125 | //if priceset is used, no need to cleanup money |
| 126 | if (!empty($params['skipCleanMoney'])) { |
| 127 | unset($moneyFields[0]); |
| 128 | } |
| 129 | |
| 130 | foreach ($moneyFields as $field) { |
| 131 | if (isset($params[$field])) { |
| 132 | $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]); |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | //set defaults in create mode |
| 137 | if (!$contributionID) { |
| 138 | CRM_Core_DAO::setCreateDefaults($params, self::getDefaults()); |
| 139 | } |
| 140 | self::calculateMissingAmountParams($params, $contributionID); |
| 141 | |
| 142 | if (!empty($params['payment_instrument_id'])) { |
| 143 | $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name'); |
| 144 | if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) { |
| 145 | $params['check_number'] = 'null'; |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | $setPrevContribution = TRUE; |
| 150 | // CRM-13964 partial payment |
| 151 | if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) { |
| 152 | $partialAmtTotal = $params['partial_payment_total']; |
| 153 | $partialAmtPay = $params['partial_amount_pay']; |
| 154 | $params['total_amount'] = $partialAmtTotal; |
| 155 | if ($partialAmtPay < $partialAmtTotal) { |
| 156 | $params['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Partially paid', 'name'); |
| 157 | $params['is_pay_later'] = 0; |
| 158 | $setPrevContribution = FALSE; |
| 159 | } |
| 160 | } |
| 161 | if ($contributionID && $setPrevContribution) { |
| 162 | $params['prevContribution'] = self::getValues(array('id' => $contributionID), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray); |
| 163 | } |
| 164 | |
| 165 | if ($contributionID) { |
| 166 | CRM_Utils_Hook::pre('edit', 'Contribution', $contributionID, $params); |
| 167 | } |
| 168 | else { |
| 169 | CRM_Utils_Hook::pre('create', 'Contribution', NULL, $params); |
| 170 | } |
| 171 | $contribution = new CRM_Contribute_BAO_Contribution(); |
| 172 | $contribution->copyValues($params); |
| 173 | |
| 174 | $contribution->id = $contributionID; |
| 175 | |
| 176 | if (empty($contribution->id)) { |
| 177 | // (only) on 'create', make sure that a valid currency is set (CRM-16845) |
| 178 | if (!CRM_Utils_Rule::currencyCode($contribution->currency)) { |
| 179 | $config = CRM_Core_Config::singleton(); |
| 180 | $contribution->currency = $config->defaultCurrency; |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | $result = $contribution->save(); |
| 185 | |
| 186 | // Add financial_trxn details as part of fix for CRM-4724 |
| 187 | $contribution->trxn_result_code = CRM_Utils_Array::value('trxn_result_code', $params); |
| 188 | $contribution->payment_processor = CRM_Utils_Array::value('payment_processor', $params); |
| 189 | |
| 190 | //add Account details |
| 191 | $params['contribution'] = $contribution; |
| 192 | self::recordFinancialAccounts($params); |
| 193 | |
| 194 | // reset the group contact cache for this group |
| 195 | CRM_Contact_BAO_GroupContactCache::remove(); |
| 196 | |
| 197 | if ($contributionID) { |
| 198 | CRM_Utils_Hook::post('edit', 'Contribution', $contribution->id, $contribution); |
| 199 | } |
| 200 | else { |
| 201 | CRM_Utils_Hook::post('create', 'Contribution', $contribution->id, $contribution); |
| 202 | } |
| 203 | |
| 204 | return $result; |
| 205 | } |
| 206 | |
| 207 | /** |
| 208 | * Get defaults for new entity. |
| 209 | * @return array |
| 210 | */ |
| 211 | public static function getDefaults() { |
| 212 | return array( |
| 213 | 'payment_instrument_id' => key(CRM_Core_OptionGroup::values('payment_instrument', |
| 214 | FALSE, FALSE, FALSE, 'AND is_default = 1') |
| 215 | ), |
| 216 | 'contribution_status_id' => CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'), |
| 217 | ); |
| 218 | } |
| 219 | |
| 220 | /** |
| 221 | * Given the list of params in the params array, fetch the object |
| 222 | * and store the values in the values array |
| 223 | * |
| 224 | * @param array $params |
| 225 | * Input parameters to find object. |
| 226 | * @param array $values |
| 227 | * Output values of the object. |
| 228 | * @param array $ids |
| 229 | * The array that holds all the db ids. |
| 230 | * |
| 231 | * @return CRM_Contribute_BAO_Contribution|null |
| 232 | * The found object or null |
| 233 | */ |
| 234 | public static function getValues($params, &$values, &$ids) { |
| 235 | if (empty($params)) { |
| 236 | return NULL; |
| 237 | } |
| 238 | $contribution = new CRM_Contribute_BAO_Contribution(); |
| 239 | |
| 240 | $contribution->copyValues($params); |
| 241 | |
| 242 | if ($contribution->find(TRUE)) { |
| 243 | $ids['contribution'] = $contribution->id; |
| 244 | |
| 245 | CRM_Core_DAO::storeValues($contribution, $values); |
| 246 | |
| 247 | return $contribution; |
| 248 | } |
| 249 | $null = NULL; // return by reference |
| 250 | return $null; |
| 251 | } |
| 252 | |
| 253 | /** |
| 254 | * Calculate net_amount & fee_amount if they are not set. |
| 255 | * |
| 256 | * Net amount should be total - fee. |
| 257 | * This should only be called for new contributions. |
| 258 | * |
| 259 | * @param array $params |
| 260 | * Params for a new contribution before they are saved. |
| 261 | * @param int|null $contributionID |
| 262 | * Contribution ID if we are dealing with an update. |
| 263 | * |
| 264 | * @throws \CiviCRM_API3_Exception |
| 265 | */ |
| 266 | public static function calculateMissingAmountParams(&$params, $contributionID) { |
| 267 | if (!$contributionID && !isset($params['fee_amount'])) { |
| 268 | if (isset($params['total_amount']) && isset($params['net_amount'])) { |
| 269 | $params['fee_amount'] = $params['total_amount'] - $params['net_amount']; |
| 270 | } |
| 271 | else { |
| 272 | $params['fee_amount'] = 0; |
| 273 | } |
| 274 | } |
| 275 | if (!isset($params['net_amount'])) { |
| 276 | if (!$contributionID) { |
| 277 | $params['net_amount'] = $params['total_amount'] - $params['fee_amount']; |
| 278 | } |
| 279 | else { |
| 280 | if (isset($params['fee_amount']) || isset($params['total_amount'])) { |
| 281 | // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount. |
| 282 | // net_amount may need adjusting. |
| 283 | $contribution = civicrm_api3('Contribution', 'getsingle', array( |
| 284 | 'id' => $contributionID, |
| 285 | 'return' => array('total_amount', 'net_amount'), |
| 286 | )); |
| 287 | $totalAmount = isset($params['total_amount']) ? $params['total_amount'] : CRM_Utils_Array::value('total_amount', $contribution); |
| 288 | $feeAmount = isset($params['fee_amount']) ? $params['fee_amount'] : CRM_Utils_Array::value('fee_amount', $contribution); |
| 289 | $params['net_amount'] = $totalAmount - $feeAmount; |
| 290 | } |
| 291 | } |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | /** |
| 296 | * @param $params |
| 297 | * @param $billingLocationTypeID |
| 298 | * |
| 299 | * @return array |
| 300 | */ |
| 301 | protected static function getBillingAddressParams($params, $billingLocationTypeID) { |
| 302 | $hasBillingField = FALSE; |
| 303 | $billingFields = array( |
| 304 | 'street_address', |
| 305 | 'city', |
| 306 | 'state_province_id', |
| 307 | 'postal_code', |
| 308 | 'country_id', |
| 309 | ); |
| 310 | |
| 311 | //build address array |
| 312 | $addressParams = array(); |
| 313 | $addressParams['location_type_id'] = $billingLocationTypeID; |
| 314 | $addressParams['is_billing'] = 1; |
| 315 | |
| 316 | $billingFirstName = CRM_Utils_Array::value('billing_first_name', $params); |
| 317 | $billingMiddleName = CRM_Utils_Array::value('billing_middle_name', $params); |
| 318 | $billingLastName = CRM_Utils_Array::value('billing_last_name', $params); |
| 319 | $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingMiddleName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingLastName}"; |
| 320 | |
| 321 | foreach ($billingFields as $value) { |
| 322 | $addressParams[$value] = CRM_Utils_Array::value("billing_{$value}-{$billingLocationTypeID}", $params); |
| 323 | if (!empty($addressParams[$value])) { |
| 324 | $hasBillingField = TRUE; |
| 325 | } |
| 326 | } |
| 327 | return array($hasBillingField, $addressParams); |
| 328 | } |
| 329 | |
| 330 | /** |
| 331 | * Get address params ready to be passed to the payment processor. |
| 332 | * |
| 333 | * We need address params in a couple of formats. For the payment processor we wan state_province_id-5. |
| 334 | * To create an address we need state_province_id. |
| 335 | * |
| 336 | * @param array $params |
| 337 | * @param int $billingLocationTypeID |
| 338 | * |
| 339 | * @return array |
| 340 | */ |
| 341 | public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) { |
| 342 | list($hasBillingField, $addressParams) = self::getBillingAddressParams($params, $billingLocationTypeID); |
| 343 | foreach ($addressParams as $name => $field) { |
| 344 | if (substr($name, 0, 8) == 'billing_') { |
| 345 | $addressParams[substr($name, 9)] = $addressParams[$field]; |
| 346 | } |
| 347 | } |
| 348 | return array($hasBillingField, $addressParams); |
| 349 | } |
| 350 | |
| 351 | /** |
| 352 | * Get the number of terms for this contribution for a given membership type |
| 353 | * based on querying the line item table and relevant price field values |
| 354 | * Note that any one contribution should only be able to have one line item relating to a particular membership |
| 355 | * type |
| 356 | * |
| 357 | * @param int $membershipTypeID |
| 358 | * |
| 359 | * @param int $contributionID |
| 360 | * |
| 361 | * @return int |
| 362 | */ |
| 363 | public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) { |
| 364 | $numTerms = CRM_Core_DAO::singleValueQuery(" |
| 365 | SELECT membership_num_terms FROM civicrm_line_item li |
| 366 | LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id |
| 367 | WHERE contribution_id = %1 AND membership_type_id = %2", |
| 368 | array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer')) |
| 369 | ); |
| 370 | // default of 1 is precautionary |
| 371 | return empty($numTerms) ? 1 : $numTerms; |
| 372 | } |
| 373 | |
| 374 | /** |
| 375 | * Takes an associative array and creates a contribution object. |
| 376 | * |
| 377 | * @param array $params |
| 378 | * (reference ) an assoc array of name/value pairs. |
| 379 | * @param array $ids |
| 380 | * The array that holds all the db ids. |
| 381 | * |
| 382 | * @return CRM_Contribute_BAO_Contribution |
| 383 | */ |
| 384 | public static function create(&$params, $ids = array()) { |
| 385 | $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date'); |
| 386 | foreach ($dateFields as $df) { |
| 387 | if (isset($params[$df])) { |
| 388 | $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]); |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | $transaction = new CRM_Core_Transaction(); |
| 393 | |
| 394 | $contribution = self::add($params, $ids); |
| 395 | |
| 396 | if (is_a($contribution, 'CRM_Core_Error')) { |
| 397 | $transaction->rollback(); |
| 398 | return $contribution; |
| 399 | } |
| 400 | |
| 401 | $params['contribution_id'] = $contribution->id; |
| 402 | |
| 403 | if (!empty($params['custom']) && |
| 404 | is_array($params['custom']) |
| 405 | ) { |
| 406 | CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id); |
| 407 | } |
| 408 | |
| 409 | $session = CRM_Core_Session::singleton(); |
| 410 | |
| 411 | if (!empty($params['note'])) { |
| 412 | $noteParams = array( |
| 413 | 'entity_table' => 'civicrm_contribution', |
| 414 | 'note' => $params['note'], |
| 415 | 'entity_id' => $contribution->id, |
| 416 | 'contact_id' => $session->get('userID'), |
| 417 | 'modified_date' => date('Ymd'), |
| 418 | ); |
| 419 | if (!$noteParams['contact_id']) { |
| 420 | $noteParams['contact_id'] = $params['contact_id']; |
| 421 | } |
| 422 | CRM_Core_BAO_Note::add($noteParams); |
| 423 | } |
| 424 | |
| 425 | // make entry in batch entity batch table |
| 426 | if (!empty($params['batch_id'])) { |
| 427 | // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params |
| 428 | $titleFields = array( |
| 429 | 'contact_id', |
| 430 | 'total_amount', |
| 431 | 'currency', |
| 432 | 'financial_type_id', |
| 433 | ); |
| 434 | $retrieveRequired = 0; |
| 435 | foreach ($titleFields as $titleField) { |
| 436 | if (!isset($contribution->$titleField)) { |
| 437 | $retrieveRequired = 1; |
| 438 | break; |
| 439 | } |
| 440 | } |
| 441 | if ($retrieveRequired == 1) { |
| 442 | $contribution->find(TRUE); |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution); |
| 447 | |
| 448 | $transaction->commit(); |
| 449 | |
| 450 | // check if activity record exist for this contribution, if |
| 451 | // not add activity |
| 452 | $activity = new CRM_Activity_DAO_Activity(); |
| 453 | $activity->source_record_id = $contribution->id; |
| 454 | $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type', |
| 455 | 'Contribution', |
| 456 | 'name' |
| 457 | ); |
| 458 | if (!$activity->find(TRUE)) { |
| 459 | if (empty($contribution->contact_id)) { |
| 460 | $contribution->find(TRUE); |
| 461 | } |
| 462 | CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline'); |
| 463 | } |
| 464 | else { |
| 465 | // CRM-13237 : if activity record found, update it with campaign id of contribution |
| 466 | CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity->id, 'campaign_id', $contribution->campaign_id); |
| 467 | } |
| 468 | |
| 469 | // do not add to recent items for import, CRM-4399 |
| 470 | if (empty($params['skipRecentView'])) { |
| 471 | $url = CRM_Utils_System::url('civicrm/contact/view/contribution', |
| 472 | "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home" |
| 473 | ); |
| 474 | // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params |
| 475 | $titleFields = array( |
| 476 | 'contact_id', |
| 477 | 'total_amount', |
| 478 | 'currency', |
| 479 | 'financial_type_id', |
| 480 | ); |
| 481 | $retrieveRequired = 0; |
| 482 | foreach ($titleFields as $titleField) { |
| 483 | if (!isset($contribution->$titleField)) { |
| 484 | $retrieveRequired = 1; |
| 485 | break; |
| 486 | } |
| 487 | } |
| 488 | if ($retrieveRequired == 1) { |
| 489 | $contribution->find(TRUE); |
| 490 | } |
| 491 | $contributionTypes = CRM_Contribute_PseudoConstant::financialType(); |
| 492 | $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id] . ')'; |
| 493 | |
| 494 | $recentOther = array(); |
| 495 | if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) { |
| 496 | $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', |
| 497 | "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home" |
| 498 | ); |
| 499 | } |
| 500 | |
| 501 | if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) { |
| 502 | $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', |
| 503 | "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home" |
| 504 | ); |
| 505 | } |
| 506 | |
| 507 | // add the recently created Contribution |
| 508 | CRM_Utils_Recent::add($title, |
| 509 | $url, |
| 510 | $contribution->id, |
| 511 | 'Contribution', |
| 512 | $contribution->contact_id, |
| 513 | NULL, |
| 514 | $recentOther |
| 515 | ); |
| 516 | } |
| 517 | |
| 518 | return $contribution; |
| 519 | } |
| 520 | |
| 521 | /** |
| 522 | * Get the values for pseudoconstants for name->value and reverse. |
| 523 | * |
| 524 | * @param array $defaults |
| 525 | * (reference) the default values, some of which need to be resolved. |
| 526 | * @param bool $reverse |
| 527 | * True if we want to resolve the values in the reverse direction (value -> name). |
| 528 | */ |
| 529 | public static function resolveDefaults(&$defaults, $reverse = FALSE) { |
| 530 | self::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant::financialType(), $reverse); |
| 531 | self::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant::paymentInstrument(), $reverse); |
| 532 | self::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant::contributionStatus(), $reverse); |
| 533 | self::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant::pcPage(), $reverse); |
| 534 | } |
| 535 | |
| 536 | /** |
| 537 | * Convert associative array names to values and vice-versa. |
| 538 | * |
| 539 | * This function is used by both the web form layer and the api. Note that |
| 540 | * the api needs the name => value conversion, also the view layer typically |
| 541 | * requires value => name conversion |
| 542 | * |
| 543 | * @param array $defaults |
| 544 | * @param string $property |
| 545 | * @param array $lookup |
| 546 | * @param bool $reverse |
| 547 | * |
| 548 | * @return bool |
| 549 | */ |
| 550 | public static function lookupValue(&$defaults, $property, &$lookup, $reverse) { |
| 551 | $id = $property . '_id'; |
| 552 | |
| 553 | $src = $reverse ? $property : $id; |
| 554 | $dst = $reverse ? $id : $property; |
| 555 | |
| 556 | if (!array_key_exists($src, $defaults)) { |
| 557 | return FALSE; |
| 558 | } |
| 559 | |
| 560 | $look = $reverse ? array_flip($lookup) : $lookup; |
| 561 | |
| 562 | if (is_array($look)) { |
| 563 | if (!array_key_exists($defaults[$src], $look)) { |
| 564 | return FALSE; |
| 565 | } |
| 566 | } |
| 567 | $defaults[$dst] = $look[$defaults[$src]]; |
| 568 | return TRUE; |
| 569 | } |
| 570 | |
| 571 | /** |
| 572 | * Retrieve DB object based on input parameters. |
| 573 | * |
| 574 | * It also stores all the retrieved values in the default array. |
| 575 | * |
| 576 | * @param array $params |
| 577 | * (reference ) an assoc array of name/value pairs. |
| 578 | * @param array $defaults |
| 579 | * (reference ) an assoc array to hold the name / value pairs. |
| 580 | * in a hierarchical manner |
| 581 | * @param array $ids |
| 582 | * (reference) the array that holds all the db ids. |
| 583 | * |
| 584 | * @return CRM_Contribute_BAO_Contribution |
| 585 | */ |
| 586 | public static function retrieve(&$params, &$defaults, &$ids) { |
| 587 | $contribution = CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids); |
| 588 | return $contribution; |
| 589 | } |
| 590 | |
| 591 | /** |
| 592 | * Combine all the importable fields from the lower levels object. |
| 593 | * |
| 594 | * The ordering is important, since currently we do not have a weight |
| 595 | * scheme. Adding weight is super important and should be done in the |
| 596 | * next week or so, before this can be called complete. |
| 597 | * |
| 598 | * @param string $contactType |
| 599 | * @param bool $status |
| 600 | * |
| 601 | * @return array |
| 602 | * array of importable Fields |
| 603 | */ |
| 604 | public static function &importableFields($contactType = 'Individual', $status = TRUE) { |
| 605 | if (!self::$_importableFields) { |
| 606 | if (!self::$_importableFields) { |
| 607 | self::$_importableFields = array(); |
| 608 | } |
| 609 | |
| 610 | if (!$status) { |
| 611 | $fields = array('' => array('title' => ts('- do not import -'))); |
| 612 | } |
| 613 | else { |
| 614 | $fields = array('' => array('title' => ts('- Contribution Fields -'))); |
| 615 | } |
| 616 | |
| 617 | $note = CRM_Core_DAO_Note::import(); |
| 618 | $tmpFields = CRM_Contribute_DAO_Contribution::import(); |
| 619 | unset($tmpFields['option_value']); |
| 620 | $optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute'); |
| 621 | $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL); |
| 622 | |
| 623 | // Using new Dedupe rule. |
| 624 | $ruleParams = array( |
| 625 | 'contact_type' => $contactType, |
| 626 | 'used' => 'Unsupervised', |
| 627 | ); |
| 628 | $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams); |
| 629 | $tmpContactField = array(); |
| 630 | if (is_array($fieldsArray)) { |
| 631 | foreach ($fieldsArray as $value) { |
| 632 | //skip if there is no dupe rule |
| 633 | if ($value == 'none') { |
| 634 | continue; |
| 635 | } |
| 636 | $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', |
| 637 | $value, |
| 638 | 'id', |
| 639 | 'column_name' |
| 640 | ); |
| 641 | $value = $customFieldId ? 'custom_' . $customFieldId : $value; |
| 642 | $tmpContactField[trim($value)] = $contactFields[trim($value)]; |
| 643 | if (!$status) { |
| 644 | $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)'); |
| 645 | } |
| 646 | else { |
| 647 | $title = $tmpContactField[trim($value)]['title']; |
| 648 | } |
| 649 | $tmpContactField[trim($value)]['title'] = $title; |
| 650 | } |
| 651 | } |
| 652 | |
| 653 | $tmpContactField['external_identifier'] = $contactFields['external_identifier']; |
| 654 | $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)'); |
| 655 | $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)'); |
| 656 | $fields = array_merge($fields, $tmpContactField); |
| 657 | $fields = array_merge($fields, $tmpFields); |
| 658 | $fields = array_merge($fields, $note); |
| 659 | $fields = array_merge($fields, $optionFields); |
| 660 | $fields = array_merge($fields, CRM_Financial_DAO_FinancialType::export()); |
| 661 | $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution')); |
| 662 | self::$_importableFields = $fields; |
| 663 | } |
| 664 | return self::$_importableFields; |
| 665 | } |
| 666 | |
| 667 | /** |
| 668 | * @return array |
| 669 | */ |
| 670 | public static function &exportableFields() { |
| 671 | if (!self::$_exportableFields) { |
| 672 | if (!self::$_exportableFields) { |
| 673 | self::$_exportableFields = array(); |
| 674 | } |
| 675 | |
| 676 | $impFields = CRM_Contribute_DAO_Contribution::export(); |
| 677 | $expFieldProduct = CRM_Contribute_DAO_Product::export(); |
| 678 | $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct::export(); |
| 679 | $typeField = CRM_Financial_DAO_FinancialType::export(); |
| 680 | $financialAccount = CRM_Financial_DAO_FinancialAccount::export(); |
| 681 | $optionField = CRM_Core_OptionValue::getFields($mode = 'contribute'); |
| 682 | $contributionStatus = array( |
| 683 | 'contribution_status' => array( |
| 684 | 'title' => ts('Contribution Status'), |
| 685 | 'name' => 'contribution_status', |
| 686 | 'data_type' => CRM_Utils_Type::T_STRING, |
| 687 | ), |
| 688 | ); |
| 689 | |
| 690 | $contributionPage = array( |
| 691 | 'contribution_page' => array( |
| 692 | 'title' => ts('Contribution Page'), |
| 693 | 'name' => 'contribution_page', |
| 694 | 'where' => 'civicrm_contribution_page.title', |
| 695 | 'data_type' => CRM_Utils_Type::T_STRING, |
| 696 | ), |
| 697 | ); |
| 698 | |
| 699 | $contributionNote = array( |
| 700 | 'contribution_note' => array( |
| 701 | 'title' => ts('Contribution Note'), |
| 702 | 'name' => 'contribution_note', |
| 703 | 'data_type' => CRM_Utils_Type::T_TEXT, |
| 704 | ), |
| 705 | ); |
| 706 | |
| 707 | $contributionRecurId = array( |
| 708 | 'contribution_recur_id' => array( |
| 709 | 'title' => ts('Recurring Contributions ID'), |
| 710 | 'name' => 'contribution_recur_id', |
| 711 | 'where' => 'civicrm_contribution.contribution_recur_id', |
| 712 | 'data_type' => CRM_Utils_Type::T_INT, |
| 713 | ), |
| 714 | ); |
| 715 | |
| 716 | $extraFields = array( |
| 717 | 'contribution_batch' => array( |
| 718 | 'title' => ts('Batch Name'), |
| 719 | ), |
| 720 | ); |
| 721 | |
| 722 | $softCreditFields = array( |
| 723 | 'contribution_soft_credit_name' => array( |
| 724 | 'name' => 'contribution_soft_credit_name', |
| 725 | 'title' => 'Soft Credit For', |
| 726 | 'where' => 'civicrm_contact_d.display_name', |
| 727 | 'data_type' => CRM_Utils_Type::T_STRING, |
| 728 | ), |
| 729 | 'contribution_soft_credit_amount' => array( |
| 730 | 'name' => 'contribution_soft_credit_amount', |
| 731 | 'title' => 'Soft Credit Amount', |
| 732 | 'where' => 'civicrm_contribution_soft.amount', |
| 733 | 'data_type' => CRM_Utils_Type::T_MONEY, |
| 734 | ), |
| 735 | 'contribution_soft_credit_type' => array( |
| 736 | 'name' => 'contribution_soft_credit_type', |
| 737 | 'title' => 'Soft Credit Type', |
| 738 | 'where' => 'contribution_softcredit_type.label', |
| 739 | 'data_type' => CRM_Utils_Type::T_STRING, |
| 740 | ), |
| 741 | 'contribution_soft_credit_contribution_id' => array( |
| 742 | 'name' => 'contribution_soft_credit_contribution_id', |
| 743 | 'title' => 'Soft Credit For Contribution ID', |
| 744 | 'where' => 'civicrm_contribution_soft.contribution_id', |
| 745 | 'data_type' => CRM_Utils_Type::T_INT, |
| 746 | ), |
| 747 | ); |
| 748 | |
| 749 | // CRM-16713 - contribution search by Premiums on 'Find Contribution' form. |
| 750 | $premiums = array( |
| 751 | 'contribution_product_id' => array( |
| 752 | 'title' => ts('Premium'), |
| 753 | 'name' => 'contribution_product_id', |
| 754 | 'where' => 'civicrm_product.id', |
| 755 | 'data_type' => CRM_Utils_Type::T_INT, |
| 756 | ), |
| 757 | ); |
| 758 | |
| 759 | $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct, |
| 760 | $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums, |
| 761 | CRM_Core_BAO_CustomField::getFieldsForImport('Contribution') |
| 762 | ); |
| 763 | |
| 764 | self::$_exportableFields = $fields; |
| 765 | } |
| 766 | |
| 767 | return self::$_exportableFields; |
| 768 | } |
| 769 | |
| 770 | /** |
| 771 | * @param null $status |
| 772 | * @param null $startDate |
| 773 | * @param null $endDate |
| 774 | * |
| 775 | * @return array|null |
| 776 | */ |
| 777 | public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) { |
| 778 | $where = array(); |
| 779 | switch ($status) { |
| 780 | case 'Valid': |
| 781 | $where[] = 'contribution_status_id = 1'; |
| 782 | break; |
| 783 | |
| 784 | case 'Cancelled': |
| 785 | $where[] = 'contribution_status_id = 3'; |
| 786 | break; |
| 787 | } |
| 788 | |
| 789 | if ($startDate) { |
| 790 | $where[] = "receive_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'"; |
| 791 | } |
| 792 | if ($endDate) { |
| 793 | $where[] = "receive_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'"; |
| 794 | } |
| 795 | CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes); |
| 796 | if ($financialTypes) { |
| 797 | $where[] = "c.financial_type_id IN (" . implode(',' , array_keys($financialTypes)) . ")"; |
| 798 | $where[] = "i.financial_type_id IN (" . implode(',' , array_keys($financialTypes)) . ")"; |
| 799 | } |
| 800 | else { |
| 801 | $where[] = "c.financial_type_id IN (0)"; |
| 802 | } |
| 803 | |
| 804 | $whereCond = implode(' AND ', $where); |
| 805 | |
| 806 | $query = " |
| 807 | SELECT sum( total_amount ) as total_amount, |
| 808 | count( c.id ) as total_count, |
| 809 | currency |
| 810 | FROM civicrm_contribution c |
| 811 | INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id ) |
| 812 | LEFT JOIN civicrm_line_item i ON ( i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution' ) |
| 813 | WHERE $whereCond |
| 814 | AND ( is_test = 0 OR is_test IS NULL ) |
| 815 | AND contact.is_deleted = 0 |
| 816 | GROUP BY currency |
| 817 | "; |
| 818 | |
| 819 | $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); |
| 820 | $amount = array(); |
| 821 | $count = 0; |
| 822 | while ($dao->fetch()) { |
| 823 | $count += $dao->total_count; |
| 824 | $amount[] = CRM_Utils_Money::format($dao->total_amount, $dao->currency); |
| 825 | } |
| 826 | if ($count) { |
| 827 | return array( |
| 828 | 'amount' => implode(', ', $amount), |
| 829 | 'count' => $count, |
| 830 | ); |
| 831 | } |
| 832 | return NULL; |
| 833 | } |
| 834 | |
| 835 | /** |
| 836 | * Delete the indirect records associated with this contribution first. |
| 837 | * |
| 838 | * @param int $id |
| 839 | * |
| 840 | * @return mixed|null |
| 841 | * $results no of deleted Contribution on success, false otherwise |
| 842 | */ |
| 843 | public static function deleteContribution($id) { |
| 844 | CRM_Utils_Hook::pre('delete', 'Contribution', $id, CRM_Core_DAO::$_nullArray); |
| 845 | |
| 846 | $transaction = new CRM_Core_Transaction(); |
| 847 | |
| 848 | $results = NULL; |
| 849 | //delete activity record |
| 850 | $params = array( |
| 851 | 'source_record_id' => $id, |
| 852 | // activity type id for contribution |
| 853 | 'activity_type_id' => 6, |
| 854 | ); |
| 855 | |
| 856 | CRM_Activity_BAO_Activity::deleteActivity($params); |
| 857 | |
| 858 | //delete billing address if exists for this contribution. |
| 859 | self::deleteAddress($id); |
| 860 | |
| 861 | //update pledge and pledge payment, CRM-3961 |
| 862 | CRM_Pledge_BAO_PledgePayment::resetPledgePayment($id); |
| 863 | |
| 864 | // remove entry from civicrm_price_set_entity, CRM-5095 |
| 865 | if (CRM_Price_BAO_PriceSet::getFor('civicrm_contribution', $id)) { |
| 866 | CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution', $id); |
| 867 | } |
| 868 | // cleanup line items. |
| 869 | $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id'); |
| 870 | |
| 871 | // delete any related entity_financial_trxn, financial_trxn and financial_item records. |
| 872 | CRM_Core_BAO_FinancialTrxn::deleteFinancialTrxn($id); |
| 873 | |
| 874 | if ($participantId) { |
| 875 | CRM_Price_BAO_LineItem::deleteLineItems($participantId, 'civicrm_participant'); |
| 876 | } |
| 877 | else { |
| 878 | CRM_Price_BAO_LineItem::deleteLineItems($id, 'civicrm_contribution'); |
| 879 | } |
| 880 | |
| 881 | //delete note. |
| 882 | $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_contribution'); |
| 883 | $noteId = key($note); |
| 884 | if ($noteId) { |
| 885 | CRM_Core_BAO_Note::del($noteId, FALSE); |
| 886 | } |
| 887 | |
| 888 | $dao = new CRM_Contribute_DAO_Contribution(); |
| 889 | $dao->id = $id; |
| 890 | |
| 891 | $results = $dao->delete(); |
| 892 | |
| 893 | $transaction->commit(); |
| 894 | |
| 895 | CRM_Utils_Hook::post('delete', 'Contribution', $dao->id, $dao); |
| 896 | |
| 897 | // delete the recently created Contribution |
| 898 | $contributionRecent = array( |
| 899 | 'id' => $id, |
| 900 | 'type' => 'Contribution', |
| 901 | ); |
| 902 | CRM_Utils_Recent::del($contributionRecent); |
| 903 | |
| 904 | return $results; |
| 905 | } |
| 906 | |
| 907 | /** |
| 908 | * React to a financial transaction (payment) failure. |
| 909 | * |
| 910 | * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted |
| 911 | * payments is important for forensic and outreach reasons. |
| 912 | * |
| 913 | * @param int $contributionID |
| 914 | * @param string $message |
| 915 | */ |
| 916 | public static function failPayment($contributionID, $contactID, $message) { |
| 917 | civicrm_api3('activity', 'create', array( |
| 918 | 'activity_type_id' => 'Failed Payment', |
| 919 | 'details' => $message, |
| 920 | 'subject' => ts('Payment failed at payment processor'), |
| 921 | 'source_record_id' => $contributionID, |
| 922 | 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() : |
| 923 | $contactID, |
| 924 | )); |
| 925 | } |
| 926 | |
| 927 | /** |
| 928 | * Check if there is a contribution with the same trxn_id or invoice_id. |
| 929 | * |
| 930 | * @param array $input |
| 931 | * An assoc array of name/value pairs. |
| 932 | * @param array $duplicates |
| 933 | * (reference) store ids of duplicate contribs. |
| 934 | * @param int $id |
| 935 | * |
| 936 | * @return bool |
| 937 | * true if duplicate, false otherwise |
| 938 | */ |
| 939 | public static function checkDuplicate($input, &$duplicates, $id = NULL) { |
| 940 | if (!$id) { |
| 941 | $id = CRM_Utils_Array::value('id', $input); |
| 942 | } |
| 943 | $trxn_id = CRM_Utils_Array::value('trxn_id', $input); |
| 944 | $invoice_id = CRM_Utils_Array::value('invoice_id', $input); |
| 945 | |
| 946 | $clause = array(); |
| 947 | $input = array(); |
| 948 | |
| 949 | if ($trxn_id) { |
| 950 | $clause[] = "trxn_id = %1"; |
| 951 | $input[1] = array($trxn_id, 'String'); |
| 952 | } |
| 953 | |
| 954 | if ($invoice_id) { |
| 955 | $clause[] = "invoice_id = %2"; |
| 956 | $input[2] = array($invoice_id, 'String'); |
| 957 | } |
| 958 | |
| 959 | if (empty($clause)) { |
| 960 | return FALSE; |
| 961 | } |
| 962 | |
| 963 | $clause = implode(' OR ', $clause); |
| 964 | if ($id) { |
| 965 | $clause = "( $clause ) AND id != %3"; |
| 966 | $input[3] = array($id, 'Integer'); |
| 967 | } |
| 968 | |
| 969 | $query = "SELECT id FROM civicrm_contribution WHERE $clause"; |
| 970 | $dao = CRM_Core_DAO::executeQuery($query, $input); |
| 971 | $result = FALSE; |
| 972 | while ($dao->fetch()) { |
| 973 | $duplicates[] = $dao->id; |
| 974 | $result = TRUE; |
| 975 | } |
| 976 | return $result; |
| 977 | } |
| 978 | |
| 979 | /** |
| 980 | * Takes an associative array and creates a contribution_product object. |
| 981 | * |
| 982 | * the function extract all the params it needs to initialize the create a |
| 983 | * contribution_product object. the params array could contain additional unused name/value |
| 984 | * pairs |
| 985 | * |
| 986 | * @param array $params |
| 987 | * (reference) an assoc array of name/value pairs. |
| 988 | * |
| 989 | * @return CRM_Contribute_DAO_ContributionProduct |
| 990 | */ |
| 991 | public static function addPremium(&$params) { |
| 992 | $contributionProduct = new CRM_Contribute_DAO_ContributionProduct(); |
| 993 | $contributionProduct->copyValues($params); |
| 994 | return $contributionProduct->save(); |
| 995 | } |
| 996 | |
| 997 | /** |
| 998 | * Get list of contribution fields for profile. |
| 999 | * For now we only allow custom contribution fields to be in |
| 1000 | * profile |
| 1001 | * |
| 1002 | * @param bool $addExtraFields |
| 1003 | * True if special fields needs to be added. |
| 1004 | * |
| 1005 | * @return array |
| 1006 | * the list of contribution fields |
| 1007 | */ |
| 1008 | public static function getContributionFields($addExtraFields = TRUE) { |
| 1009 | $contributionFields = CRM_Contribute_DAO_Contribution::export(); |
| 1010 | $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue::getFields($mode = 'contribute')); |
| 1011 | |
| 1012 | if ($addExtraFields) { |
| 1013 | $contributionFields = array_merge($contributionFields, self::getSpecialContributionFields()); |
| 1014 | } |
| 1015 | |
| 1016 | $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType::export()); |
| 1017 | |
| 1018 | foreach ($contributionFields as $key => $var) { |
| 1019 | if ($key == 'contribution_contact_id') { |
| 1020 | continue; |
| 1021 | } |
| 1022 | elseif ($key == 'contribution_campaign_id') { |
| 1023 | $var['title'] = ts('Campaign'); |
| 1024 | } |
| 1025 | $fields[$key] = $var; |
| 1026 | } |
| 1027 | |
| 1028 | $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution')); |
| 1029 | return $fields; |
| 1030 | } |
| 1031 | |
| 1032 | /** |
| 1033 | * Add extra fields specific to contribution. |
| 1034 | */ |
| 1035 | public static function getSpecialContributionFields() { |
| 1036 | $extraFields = array( |
| 1037 | 'contribution_soft_credit_name' => array( |
| 1038 | 'name' => 'contribution_soft_credit_name', |
| 1039 | 'title' => 'Soft Credit Name', |
| 1040 | 'headerPattern' => '/^soft_credit_name$/i', |
| 1041 | 'where' => 'civicrm_contact_d.display_name', |
| 1042 | ), |
| 1043 | 'contribution_soft_credit_email' => array( |
| 1044 | 'name' => 'contribution_soft_credit_email', |
| 1045 | 'title' => 'Soft Credit Email', |
| 1046 | 'headerPattern' => '/^soft_credit_email$/i', |
| 1047 | 'where' => 'soft_email.email', |
| 1048 | ), |
| 1049 | 'contribution_soft_credit_phone' => array( |
| 1050 | 'name' => 'contribution_soft_credit_phone', |
| 1051 | 'title' => 'Soft Credit Phone', |
| 1052 | 'headerPattern' => '/^soft_credit_phone$/i', |
| 1053 | 'where' => 'soft_phone.phone', |
| 1054 | ), |
| 1055 | 'contribution_soft_credit_contact_id' => array( |
| 1056 | 'name' => 'contribution_soft_credit_contact_id', |
| 1057 | 'title' => 'Soft Credit Contact ID', |
| 1058 | 'headerPattern' => '/^soft_credit_contact_id$/i', |
| 1059 | 'where' => 'civicrm_contribution_soft.contact_id', |
| 1060 | ), |
| 1061 | ); |
| 1062 | |
| 1063 | return $extraFields; |
| 1064 | } |
| 1065 | |
| 1066 | /** |
| 1067 | * @param int $pageID |
| 1068 | * |
| 1069 | * @return array |
| 1070 | */ |
| 1071 | public static function getCurrentandGoalAmount($pageID) { |
| 1072 | $query = " |
| 1073 | SELECT p.goal_amount as goal, sum( c.total_amount ) as total |
| 1074 | FROM civicrm_contribution_page p, |
| 1075 | civicrm_contribution c |
| 1076 | WHERE p.id = c.contribution_page_id |
| 1077 | AND p.id = %1 |
| 1078 | AND c.cancel_date is null |
| 1079 | GROUP BY p.id |
| 1080 | "; |
| 1081 | |
| 1082 | $config = CRM_Core_Config::singleton(); |
| 1083 | $params = array(1 => array($pageID, 'Integer')); |
| 1084 | $dao = CRM_Core_DAO::executeQuery($query, $params); |
| 1085 | |
| 1086 | if ($dao->fetch()) { |
| 1087 | return array($dao->goal, $dao->total); |
| 1088 | } |
| 1089 | else { |
| 1090 | return array(NULL, NULL); |
| 1091 | } |
| 1092 | } |
| 1093 | |
| 1094 | /** |
| 1095 | * Get list of contribution In Honor of contact Ids. |
| 1096 | * |
| 1097 | * @param int $honorId |
| 1098 | * In Honor of Contact ID. |
| 1099 | * |
| 1100 | * @return array |
| 1101 | * list of contribution fields |
| 1102 | */ |
| 1103 | public static function getHonorContacts($honorId) { |
| 1104 | $params = array(); |
| 1105 | $honorDAO = new CRM_Contribute_DAO_ContributionSoft(); |
| 1106 | $honorDAO->contact_id = $honorId; |
| 1107 | $honorDAO->find(); |
| 1108 | |
| 1109 | $type = CRM_Contribute_PseudoConstant::financialType(); |
| 1110 | |
| 1111 | while ($honorDAO->fetch()) { |
| 1112 | $contributionDAO = new CRM_Contribute_DAO_Contribution(); |
| 1113 | $contributionDAO->id = $honorDAO->contribution_id; |
| 1114 | |
| 1115 | if ($contributionDAO->find(TRUE)) { |
| 1116 | $params[$contributionDAO->id]['honor_type'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id); |
| 1117 | $params[$contributionDAO->id]['honorId'] = $contributionDAO->contact_id; |
| 1118 | $params[$contributionDAO->id]['display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id, 'display_name'); |
| 1119 | $params[$contributionDAO->id]['type'] = $type[$contributionDAO->financial_type_id]; |
| 1120 | $params[$contributionDAO->id]['type_id'] = $contributionDAO->financial_type_id; |
| 1121 | $params[$contributionDAO->id]['amount'] = CRM_Utils_Money::format($contributionDAO->total_amount, $contributionDAO->currency); |
| 1122 | $params[$contributionDAO->id]['source'] = $contributionDAO->source; |
| 1123 | $params[$contributionDAO->id]['receive_date'] = $contributionDAO->receive_date; |
| 1124 | $params[$contributionDAO->id]['contribution_status'] = CRM_Contribute_PseudoConstant::contributionStatus($contributionDAO->contribution_status_id); |
| 1125 | } |
| 1126 | } |
| 1127 | |
| 1128 | return $params; |
| 1129 | } |
| 1130 | |
| 1131 | /** |
| 1132 | * Get the sort name of a contact for a particular contribution. |
| 1133 | * |
| 1134 | * @param int $id |
| 1135 | * Id of the contribution. |
| 1136 | * |
| 1137 | * @return null|string |
| 1138 | * sort name of the contact if found |
| 1139 | */ |
| 1140 | public static function sortName($id) { |
| 1141 | $id = CRM_Utils_Type::escape($id, 'Integer'); |
| 1142 | |
| 1143 | $query = " |
| 1144 | SELECT civicrm_contact.sort_name |
| 1145 | FROM civicrm_contribution, civicrm_contact |
| 1146 | WHERE civicrm_contribution.contact_id = civicrm_contact.id |
| 1147 | AND civicrm_contribution.id = {$id} |
| 1148 | "; |
| 1149 | return CRM_Core_DAO::singleValueQuery($query, CRM_Core_DAO::$_nullArray); |
| 1150 | } |
| 1151 | |
| 1152 | /** |
| 1153 | * @param int $contactID |
| 1154 | * |
| 1155 | * @return array |
| 1156 | */ |
| 1157 | public static function annual($contactID) { |
| 1158 | if (is_array($contactID)) { |
| 1159 | $contactIDs = implode(',', $contactID); |
| 1160 | } |
| 1161 | else { |
| 1162 | $contactIDs = $contactID; |
| 1163 | } |
| 1164 | |
| 1165 | $config = CRM_Core_Config::singleton(); |
| 1166 | $startDate = $endDate = NULL; |
| 1167 | |
| 1168 | $currentMonth = date('m'); |
| 1169 | $currentDay = date('d'); |
| 1170 | if ((int ) $config->fiscalYearStart['M'] > $currentMonth || |
| 1171 | ((int ) $config->fiscalYearStart['M'] == $currentMonth && |
| 1172 | (int ) $config->fiscalYearStart['d'] > $currentDay |
| 1173 | ) |
| 1174 | ) { |
| 1175 | $year = date('Y') - 1; |
| 1176 | } |
| 1177 | else { |
| 1178 | $year = date('Y'); |
| 1179 | } |
| 1180 | $nextYear = $year + 1; |
| 1181 | |
| 1182 | if ($config->fiscalYearStart) { |
| 1183 | if ($config->fiscalYearStart['M'] < 10) { |
| 1184 | $config->fiscalYearStart['M'] = '0' . $config->fiscalYearStart['M']; |
| 1185 | } |
| 1186 | if ($config->fiscalYearStart['d'] < 10) { |
| 1187 | $config->fiscalYearStart['d'] = '0' . $config->fiscalYearStart['d']; |
| 1188 | } |
| 1189 | $monthDay = $config->fiscalYearStart['M'] . $config->fiscalYearStart['d']; |
| 1190 | } |
| 1191 | else { |
| 1192 | $monthDay = '0101'; |
| 1193 | } |
| 1194 | $startDate = "$year$monthDay"; |
| 1195 | $endDate = "$nextYear$monthDay"; |
| 1196 | CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes); |
| 1197 | $additionalWhere = " AND b.financial_type_id IN (0)"; |
| 1198 | $liWhere = " AND i.financial_type_id IN (0)"; |
| 1199 | if (!empty($financialTypes)) { |
| 1200 | $additionalWhere = " AND b.financial_type_id IN (" . implode(',' , array_keys($financialTypes)) . ")"; |
| 1201 | $liWhere = " AND i.financial_type_id NOT IN (" . implode(',' , array_keys($financialTypes)) . ")"; |
| 1202 | } |
| 1203 | $query = " |
| 1204 | SELECT count(*) as count, |
| 1205 | sum(total_amount) as amount, |
| 1206 | avg(total_amount) as average, |
| 1207 | currency |
| 1208 | FROM civicrm_contribution b |
| 1209 | WHERE b.contact_id IN ( $contactIDs ) |
| 1210 | AND b.contribution_status_id = 1 |
| 1211 | AND b.is_test = 0 |
| 1212 | AND b.receive_date >= $startDate |
| 1213 | AND b.receive_date < $endDate |
| 1214 | GROUP BY currency |
| 1215 | "; |
| 1216 | $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); |
| 1217 | $count = 0; |
| 1218 | $amount = $average = array(); |
| 1219 | while ($dao->fetch()) { |
| 1220 | if ($dao->count > 0 && $dao->amount > 0) { |
| 1221 | $count += $dao->count; |
| 1222 | $amount[] = CRM_Utils_Money::format($dao->amount, $dao->currency); |
| 1223 | $average[] = CRM_Utils_Money::format($dao->average, $dao->currency); |
| 1224 | } |
| 1225 | } |
| 1226 | if ($count > 0) { |
| 1227 | return array( |
| 1228 | $count, |
| 1229 | implode(', ', $amount), |
| 1230 | implode(', ', $average), |
| 1231 | ); |
| 1232 | } |
| 1233 | return array(0, 0, 0); |
| 1234 | } |
| 1235 | |
| 1236 | /** |
| 1237 | * Check if there is a contribution with the params passed in. |
| 1238 | * |
| 1239 | * Used for trxn_id,invoice_id and contribution_id |
| 1240 | * |
| 1241 | * @param array $params |
| 1242 | * An assoc array of name/value pairs. |
| 1243 | * |
| 1244 | * @return array |
| 1245 | * contribution id if success else NULL |
| 1246 | */ |
| 1247 | public static function checkDuplicateIds($params) { |
| 1248 | $dao = new CRM_Contribute_DAO_Contribution(); |
| 1249 | |
| 1250 | $clause = array(); |
| 1251 | $input = array(); |
| 1252 | foreach ($params as $k => $v) { |
| 1253 | if ($v) { |
| 1254 | $clause[] = "$k = '$v'"; |
| 1255 | } |
| 1256 | } |
| 1257 | $clause = implode(' AND ', $clause); |
| 1258 | $query = "SELECT id FROM civicrm_contribution WHERE $clause"; |
| 1259 | $dao = CRM_Core_DAO::executeQuery($query, $input); |
| 1260 | |
| 1261 | while ($dao->fetch()) { |
| 1262 | $result = $dao->id; |
| 1263 | return $result; |
| 1264 | } |
| 1265 | return NULL; |
| 1266 | } |
| 1267 | |
| 1268 | /** |
| 1269 | * Get the contribution details for component export. |
| 1270 | * |
| 1271 | * @param int $exportMode |
| 1272 | * Export mode. |
| 1273 | * @param string $componentIds |
| 1274 | * Component ids. |
| 1275 | * |
| 1276 | * @return array |
| 1277 | * associated array |
| 1278 | */ |
| 1279 | public static function getContributionDetails($exportMode, $componentIds) { |
| 1280 | $paymentDetails = array(); |
| 1281 | $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) '; |
| 1282 | |
| 1283 | if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) { |
| 1284 | $componentSelect = " civicrm_participant_payment.participant_id id"; |
| 1285 | $additionalClause = " |
| 1286 | INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id |
| 1287 | AND civicrm_participant_payment.participant_id {$componentClause} ) |
| 1288 | "; |
| 1289 | } |
| 1290 | elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) { |
| 1291 | $componentSelect = " civicrm_membership_payment.membership_id id"; |
| 1292 | $additionalClause = " |
| 1293 | INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id |
| 1294 | AND civicrm_membership_payment.membership_id {$componentClause} ) |
| 1295 | "; |
| 1296 | } |
| 1297 | elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) { |
| 1298 | $componentSelect = " civicrm_pledge_payment.id id"; |
| 1299 | $additionalClause = " |
| 1300 | INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id |
| 1301 | AND civicrm_pledge_payment.pledge_id {$componentClause} ) |
| 1302 | "; |
| 1303 | } |
| 1304 | |
| 1305 | $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date, |
| 1306 | trxn_id, {$componentSelect} |
| 1307 | FROM civicrm_contribution |
| 1308 | LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument') |
| 1309 | LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value |
| 1310 | AND option_group_payment_instrument.id = payment_instrument.option_group_id ) |
| 1311 | LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status') |
| 1312 | LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value |
| 1313 | AND option_group_contribution_status.id = contribution_status.option_group_id ) |
| 1314 | {$additionalClause} |
| 1315 | "; |
| 1316 | |
| 1317 | $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); |
| 1318 | |
| 1319 | while ($dao->fetch()) { |
| 1320 | $paymentDetails[$dao->id] = array( |
| 1321 | 'total_amount' => $dao->total_amount, |
| 1322 | 'contribution_status' => $dao->status, |
| 1323 | 'receive_date' => $dao->receive_date, |
| 1324 | 'pay_instru' => $dao->payment_instrument, |
| 1325 | 'trxn_id' => $dao->trxn_id, |
| 1326 | ); |
| 1327 | } |
| 1328 | |
| 1329 | return $paymentDetails; |
| 1330 | } |
| 1331 | |
| 1332 | /** |
| 1333 | * Create address associated with contribution record. |
| 1334 | * |
| 1335 | * As long as there is one or more billing field in the parameters we will create the address. |
| 1336 | * |
| 1337 | * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once |
| 1338 | * thought). |
| 1339 | * |
| 1340 | * @param array $params |
| 1341 | * @param int $billingLocationTypeID |
| 1342 | * |
| 1343 | * @return int |
| 1344 | * address id |
| 1345 | */ |
| 1346 | public static function createAddress($params, $billingLocationTypeID) { |
| 1347 | list($hasBillingField, $addressParams) = self::getBillingAddressParams($params, $billingLocationTypeID); |
| 1348 | if ($hasBillingField) { |
| 1349 | $address = CRM_Core_BAO_Address::add($addressParams, FALSE); |
| 1350 | return $address->id; |
| 1351 | } |
| 1352 | return NULL; |
| 1353 | |
| 1354 | } |
| 1355 | |
| 1356 | /** |
| 1357 | * Delete billing address record related contribution. |
| 1358 | * |
| 1359 | * @param int $contributionId |
| 1360 | * @param int $contactId |
| 1361 | */ |
| 1362 | public static function deleteAddress($contributionId = NULL, $contactId = NULL) { |
| 1363 | $clauses = array(); |
| 1364 | $contactJoin = NULL; |
| 1365 | |
| 1366 | if ($contributionId) { |
| 1367 | $clauses[] = "cc.id = {$contributionId}"; |
| 1368 | } |
| 1369 | |
| 1370 | if ($contactId) { |
| 1371 | $clauses[] = "cco.id = {$contactId}"; |
| 1372 | $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id"; |
| 1373 | } |
| 1374 | |
| 1375 | if (empty($clauses)) { |
| 1376 | CRM_Core_Error::fatal(); |
| 1377 | } |
| 1378 | |
| 1379 | $condition = implode(' OR ', $clauses); |
| 1380 | |
| 1381 | $query = " |
| 1382 | SELECT ca.id |
| 1383 | FROM civicrm_address ca |
| 1384 | INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id |
| 1385 | $contactJoin |
| 1386 | WHERE $condition |
| 1387 | "; |
| 1388 | $dao = CRM_Core_DAO::executeQuery($query); |
| 1389 | |
| 1390 | while ($dao->fetch()) { |
| 1391 | $params = array('id' => $dao->id); |
| 1392 | CRM_Core_BAO_Block::blockDelete('Address', $params); |
| 1393 | } |
| 1394 | } |
| 1395 | |
| 1396 | /** |
| 1397 | * This function check online pending contribution associated w/ |
| 1398 | * Online Event Registration or Online Membership signup. |
| 1399 | * |
| 1400 | * @param int $componentId |
| 1401 | * Participant/membership id. |
| 1402 | * @param string $componentName |
| 1403 | * Event/Membership. |
| 1404 | * |
| 1405 | * @return int |
| 1406 | * pending contribution id. |
| 1407 | */ |
| 1408 | public static function checkOnlinePendingContribution($componentId, $componentName) { |
| 1409 | $contributionId = NULL; |
| 1410 | if (!$componentId || |
| 1411 | !in_array($componentName, array('Event', 'Membership')) |
| 1412 | ) { |
| 1413 | return $contributionId; |
| 1414 | } |
| 1415 | |
| 1416 | if ($componentName == 'Event') { |
| 1417 | $idName = 'participant_id'; |
| 1418 | $componentTable = 'civicrm_participant'; |
| 1419 | $paymentTable = 'civicrm_participant_payment'; |
| 1420 | $source = ts('Online Event Registration'); |
| 1421 | } |
| 1422 | |
| 1423 | if ($componentName == 'Membership') { |
| 1424 | $idName = 'membership_id'; |
| 1425 | $componentTable = 'civicrm_membership'; |
| 1426 | $paymentTable = 'civicrm_membership_payment'; |
| 1427 | $source = ts('Online Contribution'); |
| 1428 | } |
| 1429 | |
| 1430 | $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')); |
| 1431 | |
| 1432 | $query = " |
| 1433 | SELECT component.id as {$idName}, |
| 1434 | componentPayment.contribution_id as contribution_id, |
| 1435 | contribution.source source, |
| 1436 | contribution.contribution_status_id as contribution_status_id, |
| 1437 | contribution.is_pay_later as is_pay_later |
| 1438 | FROM $componentTable component |
| 1439 | LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id ) |
| 1440 | LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id ) |
| 1441 | WHERE component.id = {$componentId}"; |
| 1442 | |
| 1443 | $dao = CRM_Core_DAO::executeQuery($query); |
| 1444 | |
| 1445 | while ($dao->fetch()) { |
| 1446 | if ($dao->contribution_id && |
| 1447 | $dao->is_pay_later && |
| 1448 | $dao->contribution_status_id == $pendingStatusId && |
| 1449 | strpos($dao->source, $source) !== FALSE |
| 1450 | ) { |
| 1451 | $contributionId = $dao->contribution_id; |
| 1452 | $dao->free(); |
| 1453 | } |
| 1454 | } |
| 1455 | |
| 1456 | return $contributionId; |
| 1457 | } |
| 1458 | |
| 1459 | /** |
| 1460 | * Update contribution as well as related objects. |
| 1461 | * |
| 1462 | * This function by-passes hooks - to address this - don't use this function. |
| 1463 | * |
| 1464 | * @deprecated |
| 1465 | * |
| 1466 | * Use api contribute.completetransaction |
| 1467 | * For failures use failPayment (preferably exposing by api in the process). |
| 1468 | * |
| 1469 | * @param array $params |
| 1470 | * @param bool $processContributionObject |
| 1471 | * |
| 1472 | * @return array |
| 1473 | * @throws \Exception |
| 1474 | */ |
| 1475 | public static function transitionComponents($params, $processContributionObject = FALSE) { |
| 1476 | // get minimum required values. |
| 1477 | $contactId = CRM_Utils_Array::value('contact_id', $params); |
| 1478 | $componentId = CRM_Utils_Array::value('component_id', $params); |
| 1479 | $componentName = CRM_Utils_Array::value('componentName', $params); |
| 1480 | $contributionId = CRM_Utils_Array::value('contribution_id', $params); |
| 1481 | $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params); |
| 1482 | |
| 1483 | // if we already processed contribution object pass previous status id. |
| 1484 | $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params); |
| 1485 | |
| 1486 | $updateResult = array(); |
| 1487 | |
| 1488 | $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
| 1489 | |
| 1490 | // we process only ( Completed, Cancelled, or Failed ) contributions. |
| 1491 | if (!$contributionId || |
| 1492 | !in_array($contributionStatusId, array( |
| 1493 | array_search('Completed', $contributionStatuses), |
| 1494 | array_search('Cancelled', $contributionStatuses), |
| 1495 | array_search('Failed', $contributionStatuses), |
| 1496 | )) |
| 1497 | ) { |
| 1498 | return $updateResult; |
| 1499 | } |
| 1500 | |
| 1501 | if (!$componentName || !$componentId) { |
| 1502 | // get the related component details. |
| 1503 | $componentDetails = self::getComponentDetails($contributionId); |
| 1504 | } |
| 1505 | else { |
| 1506 | $componentDetails['contact_id'] = $contactId; |
| 1507 | $componentDetails['component'] = $componentName; |
| 1508 | |
| 1509 | if ($componentName == 'event') { |
| 1510 | $componentDetails['participant'] = $componentId; |
| 1511 | } |
| 1512 | else { |
| 1513 | $componentDetails['membership'] = $componentId; |
| 1514 | } |
| 1515 | } |
| 1516 | |
| 1517 | if (!empty($componentDetails['contact_id'])) { |
| 1518 | $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', |
| 1519 | $contributionId, |
| 1520 | 'contact_id' |
| 1521 | ); |
| 1522 | } |
| 1523 | |
| 1524 | // do check for required ids. |
| 1525 | if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) || empty($componentDetails['contact_id'])) { |
| 1526 | return $updateResult; |
| 1527 | } |
| 1528 | |
| 1529 | //now we are ready w/ required ids, start processing. |
| 1530 | |
| 1531 | $baseIPN = new CRM_Core_Payment_BaseIPN(); |
| 1532 | |
| 1533 | $input = $ids = $objects = array(); |
| 1534 | |
| 1535 | $input['component'] = CRM_Utils_Array::value('component', $componentDetails); |
| 1536 | $ids['contribution'] = $contributionId; |
| 1537 | $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails); |
| 1538 | $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails); |
| 1539 | $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails); |
| 1540 | $ids['event'] = CRM_Utils_Array::value('event', $componentDetails); |
| 1541 | $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails); |
| 1542 | $ids['contributionRecur'] = NULL; |
| 1543 | $ids['contributionPage'] = NULL; |
| 1544 | |
| 1545 | if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) { |
| 1546 | CRM_Core_Error::fatal(); |
| 1547 | } |
| 1548 | |
| 1549 | $memberships = &$objects['membership']; |
| 1550 | $participant = &$objects['participant']; |
| 1551 | $pledgePayment = &$objects['pledge_payment']; |
| 1552 | $contribution = &$objects['contribution']; |
| 1553 | |
| 1554 | if ($pledgePayment) { |
| 1555 | $pledgePaymentIDs = array(); |
| 1556 | foreach ($pledgePayment as $key => $object) { |
| 1557 | $pledgePaymentIDs[] = $object->id; |
| 1558 | } |
| 1559 | $pledgeID = $pledgePayment[0]->pledge_id; |
| 1560 | } |
| 1561 | |
| 1562 | $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus(); |
| 1563 | |
| 1564 | if ($participant) { |
| 1565 | $participantStatuses = CRM_Event_PseudoConstant::participantStatus(); |
| 1566 | $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', |
| 1567 | $participant->id, |
| 1568 | 'status_id' |
| 1569 | ); |
| 1570 | } |
| 1571 | // we might want to process contribution object. |
| 1572 | $processContribution = FALSE; |
| 1573 | if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) { |
| 1574 | if (is_array($memberships)) { |
| 1575 | foreach ($memberships as $membership) { |
| 1576 | if ($membership) { |
| 1577 | $membership->status_id = array_search('Cancelled', $membershipStatuses); |
| 1578 | $membership->save(); |
| 1579 | |
| 1580 | $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; |
| 1581 | if ($processContributionObject) { |
| 1582 | $processContribution = TRUE; |
| 1583 | } |
| 1584 | } |
| 1585 | } |
| 1586 | } |
| 1587 | |
| 1588 | if ($participant) { |
| 1589 | $updatedStatusId = array_search('Cancelled', $participantStatuses); |
| 1590 | CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE); |
| 1591 | |
| 1592 | $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; |
| 1593 | if ($processContributionObject) { |
| 1594 | $processContribution = TRUE; |
| 1595 | } |
| 1596 | } |
| 1597 | |
| 1598 | if ($pledgePayment) { |
| 1599 | CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); |
| 1600 | |
| 1601 | $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; |
| 1602 | if ($processContributionObject) { |
| 1603 | $processContribution = TRUE; |
| 1604 | } |
| 1605 | } |
| 1606 | } |
| 1607 | elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) { |
| 1608 | if (is_array($memberships)) { |
| 1609 | foreach ($memberships as $membership) { |
| 1610 | if ($membership) { |
| 1611 | $membership->status_id = array_search('Expired', $membershipStatuses); |
| 1612 | $membership->save(); |
| 1613 | |
| 1614 | $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; |
| 1615 | if ($processContributionObject) { |
| 1616 | $processContribution = TRUE; |
| 1617 | } |
| 1618 | } |
| 1619 | } |
| 1620 | } |
| 1621 | if ($participant) { |
| 1622 | $updatedStatusId = array_search('Cancelled', $participantStatuses); |
| 1623 | CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE); |
| 1624 | |
| 1625 | $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; |
| 1626 | if ($processContributionObject) { |
| 1627 | $processContribution = TRUE; |
| 1628 | } |
| 1629 | } |
| 1630 | |
| 1631 | if ($pledgePayment) { |
| 1632 | CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); |
| 1633 | |
| 1634 | $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; |
| 1635 | if ($processContributionObject) { |
| 1636 | $processContribution = TRUE; |
| 1637 | } |
| 1638 | } |
| 1639 | } |
| 1640 | elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) { |
| 1641 | |
| 1642 | // only pending contribution related object processed. |
| 1643 | if ($previousContriStatusId && |
| 1644 | ($previousContriStatusId != array_search('Pending', $contributionStatuses)) |
| 1645 | ) { |
| 1646 | // this is case when we already processed contribution object. |
| 1647 | return $updateResult; |
| 1648 | } |
| 1649 | elseif (!$previousContriStatusId && |
| 1650 | $contribution->contribution_status_id != array_search('Pending', $contributionStatuses) |
| 1651 | ) { |
| 1652 | // this is case when we are going to process contribution object later. |
| 1653 | return $updateResult; |
| 1654 | } |
| 1655 | |
| 1656 | if (is_array($memberships)) { |
| 1657 | foreach ($memberships as $membership) { |
| 1658 | if ($membership) { |
| 1659 | $format = '%Y%m%d'; |
| 1660 | |
| 1661 | //CRM-4523 |
| 1662 | $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, |
| 1663 | $membership->membership_type_id, |
| 1664 | $membership->is_test, $membership->id |
| 1665 | ); |
| 1666 | |
| 1667 | // CRM-8141 update the membership type with the value recorded in log when membership created/renewed |
| 1668 | // this picks up membership type changes during renewals |
| 1669 | $sql = " |
| 1670 | SELECT membership_type_id |
| 1671 | FROM civicrm_membership_log |
| 1672 | WHERE membership_id=$membership->id |
| 1673 | ORDER BY id DESC |
| 1674 | LIMIT 1;"; |
| 1675 | $dao = new CRM_Core_DAO(); |
| 1676 | $dao->query($sql); |
| 1677 | if ($dao->fetch()) { |
| 1678 | if (!empty($dao->membership_type_id)) { |
| 1679 | $membership->membership_type_id = $dao->membership_type_id; |
| 1680 | $membership->save(); |
| 1681 | } |
| 1682 | } |
| 1683 | // else fall back to using current membership type |
| 1684 | $dao->free(); |
| 1685 | |
| 1686 | // Figure out number of terms |
| 1687 | $numterms = 1; |
| 1688 | $lineitems = CRM_Price_BAO_LineItem::getLineItems($contributionId, 'contribution'); |
| 1689 | foreach ($lineitems as $lineitem) { |
| 1690 | if ($membership->membership_type_id == CRM_Utils_Array::value('membership_type_id', $lineitem)) { |
| 1691 | $numterms = CRM_Utils_Array::value('membership_num_terms', $lineitem); |
| 1692 | |
| 1693 | // in case membership_num_terms comes through as null or zero |
| 1694 | $numterms = $numterms >= 1 ? $numterms : 1; |
| 1695 | break; |
| 1696 | } |
| 1697 | } |
| 1698 | |
| 1699 | // CRM-15735-to update the membership status as per the contribution receive date |
| 1700 | $joinDate = NULL; |
| 1701 | if (!empty($params['receive_date'])) { |
| 1702 | $joinDate = $params['receive_date']; |
| 1703 | $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($membership->start_date, |
| 1704 | $membership->end_date, |
| 1705 | $membership->join_date, |
| 1706 | $params['receive_date'], |
| 1707 | FALSE, |
| 1708 | $membership->membership_type_id, |
| 1709 | (array) $membership |
| 1710 | ); |
| 1711 | $membership->status_id = CRM_Utils_Array::value('id', $status, $membership->status_id); |
| 1712 | $membership->save(); |
| 1713 | } |
| 1714 | |
| 1715 | if ($currentMembership) { |
| 1716 | CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL); |
| 1717 | $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms); |
| 1718 | $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format); |
| 1719 | } |
| 1720 | else { |
| 1721 | $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, $joinDate, NULL, NULL, $numterms); |
| 1722 | } |
| 1723 | |
| 1724 | //get the status for membership. |
| 1725 | $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], |
| 1726 | $dates['end_date'], |
| 1727 | $dates['join_date'], |
| 1728 | 'today', |
| 1729 | TRUE, |
| 1730 | $membership->membership_type_id, |
| 1731 | (array) $membership |
| 1732 | ); |
| 1733 | |
| 1734 | $formattedParams = array( |
| 1735 | 'status_id' => CRM_Utils_Array::value('id', $calcStatus, |
| 1736 | array_search('Current', $membershipStatuses) |
| 1737 | ), |
| 1738 | 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format), |
| 1739 | 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format), |
| 1740 | 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format), |
| 1741 | ); |
| 1742 | |
| 1743 | CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams); |
| 1744 | |
| 1745 | $membership->copyValues($formattedParams); |
| 1746 | $membership->save(); |
| 1747 | |
| 1748 | //updating the membership log |
| 1749 | $membershipLog = array(); |
| 1750 | $membershipLog = $formattedParams; |
| 1751 | $logStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format); |
| 1752 | $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date']; |
| 1753 | |
| 1754 | $membershipLog['start_date'] = $logStartDate; |
| 1755 | $membershipLog['membership_id'] = $membership->id; |
| 1756 | $membershipLog['modified_id'] = $membership->contact_id; |
| 1757 | $membershipLog['modified_date'] = date('Ymd'); |
| 1758 | $membershipLog['membership_type_id'] = $membership->membership_type_id; |
| 1759 | |
| 1760 | CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray); |
| 1761 | |
| 1762 | //update related Memberships. |
| 1763 | CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams); |
| 1764 | |
| 1765 | $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'], |
| 1766 | '%B %E%f, %Y' |
| 1767 | ); |
| 1768 | $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; |
| 1769 | if ($processContributionObject) { |
| 1770 | $processContribution = TRUE; |
| 1771 | } |
| 1772 | |
| 1773 | CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership); |
| 1774 | } |
| 1775 | } |
| 1776 | } |
| 1777 | |
| 1778 | if ($participant) { |
| 1779 | $updatedStatusId = array_search('Registered', $participantStatuses); |
| 1780 | CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE); |
| 1781 | |
| 1782 | $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; |
| 1783 | if ($processContributionObject) { |
| 1784 | $processContribution = TRUE; |
| 1785 | } |
| 1786 | } |
| 1787 | |
| 1788 | if ($pledgePayment) { |
| 1789 | CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); |
| 1790 | |
| 1791 | $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; |
| 1792 | if ($processContributionObject) { |
| 1793 | $processContribution = TRUE; |
| 1794 | } |
| 1795 | } |
| 1796 | } |
| 1797 | |
| 1798 | // process contribution object. |
| 1799 | if ($processContribution) { |
| 1800 | $contributionParams = array(); |
| 1801 | $fields = array( |
| 1802 | 'contact_id', |
| 1803 | 'total_amount', |
| 1804 | 'receive_date', |
| 1805 | 'is_test', |
| 1806 | 'campaign_id', |
| 1807 | 'payment_instrument_id', |
| 1808 | 'trxn_id', |
| 1809 | 'invoice_id', |
| 1810 | 'financial_type_id', |
| 1811 | 'contribution_status_id', |
| 1812 | 'non_deductible_amount', |
| 1813 | 'receipt_date', |
| 1814 | 'check_number', |
| 1815 | ); |
| 1816 | foreach ($fields as $field) { |
| 1817 | if (empty($params[$field])) { |
| 1818 | continue; |
| 1819 | } |
| 1820 | $contributionParams[$field] = $params[$field]; |
| 1821 | } |
| 1822 | |
| 1823 | $ids = array('contribution' => $contributionId); |
| 1824 | $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids); |
| 1825 | } |
| 1826 | |
| 1827 | return $updateResult; |
| 1828 | } |
| 1829 | |
| 1830 | /** |
| 1831 | * Returns all contribution related object ids. |
| 1832 | * |
| 1833 | * @param $contributionId |
| 1834 | * |
| 1835 | * @return array |
| 1836 | */ |
| 1837 | public static function getComponentDetails($contributionId) { |
| 1838 | $componentDetails = $pledgePayment = array(); |
| 1839 | if (!$contributionId) { |
| 1840 | return $componentDetails; |
| 1841 | } |
| 1842 | |
| 1843 | $query = " |
| 1844 | SELECT c.id as contribution_id, |
| 1845 | c.contact_id as contact_id, |
| 1846 | c.contribution_recur_id, |
| 1847 | mp.membership_id as membership_id, |
| 1848 | m.membership_type_id as membership_type_id, |
| 1849 | pp.participant_id as participant_id, |
| 1850 | p.event_id as event_id, |
| 1851 | pgp.id as pledge_payment_id |
| 1852 | FROM civicrm_contribution c |
| 1853 | LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id |
| 1854 | LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id |
| 1855 | LEFT JOIN civicrm_participant p ON pp.participant_id = p.id |
| 1856 | LEFT JOIN civicrm_membership m ON m.id = mp.membership_id |
| 1857 | LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id |
| 1858 | WHERE c.id = $contributionId"; |
| 1859 | |
| 1860 | $dao = CRM_Core_DAO::executeQuery($query); |
| 1861 | $componentDetails = array(); |
| 1862 | |
| 1863 | while ($dao->fetch()) { |
| 1864 | $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute'; |
| 1865 | $componentDetails['contact_id'] = $dao->contact_id; |
| 1866 | if ($dao->event_id) { |
| 1867 | $componentDetails['event'] = $dao->event_id; |
| 1868 | } |
| 1869 | if ($dao->participant_id) { |
| 1870 | $componentDetails['participant'] = $dao->participant_id; |
| 1871 | } |
| 1872 | if ($dao->membership_id) { |
| 1873 | if (!isset($componentDetails['membership'])) { |
| 1874 | $componentDetails['membership'] = $componentDetails['membership_type'] = array(); |
| 1875 | } |
| 1876 | $componentDetails['membership'][] = $dao->membership_id; |
| 1877 | $componentDetails['membership_type'][] = $dao->membership_type_id; |
| 1878 | } |
| 1879 | if ($dao->pledge_payment_id) { |
| 1880 | $pledgePayment[] = $dao->pledge_payment_id; |
| 1881 | } |
| 1882 | if ($dao->contribution_recur_id) { |
| 1883 | $componentDetails['contributionRecur'] = $dao->contribution_recur_id; |
| 1884 | } |
| 1885 | } |
| 1886 | |
| 1887 | if ($pledgePayment) { |
| 1888 | $componentDetails['pledge_payment'] = $pledgePayment; |
| 1889 | } |
| 1890 | |
| 1891 | return $componentDetails; |
| 1892 | } |
| 1893 | |
| 1894 | /** |
| 1895 | * @param int $contactId |
| 1896 | * @param bool $includeSoftCredit |
| 1897 | * |
| 1898 | * @return null|string |
| 1899 | */ |
| 1900 | public static function contributionCount($contactId, $includeSoftCredit = TRUE) { |
| 1901 | if (!$contactId) { |
| 1902 | return 0; |
| 1903 | } |
| 1904 | CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes); |
| 1905 | $additionalWhere = " AND contribution.financial_type_id IN (0)"; |
| 1906 | $liWhere = " AND i.financial_type_id IN (0)"; |
| 1907 | if (!empty($financialTypes)) { |
| 1908 | $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',' , array_keys($financialTypes)) . ")"; |
| 1909 | $liWhere = " AND i.financial_type_id NOT IN (" . implode(',' , array_keys($financialTypes)) . ")"; |
| 1910 | } |
| 1911 | $contactContributionsSQL = " |
| 1912 | SELECT contribution.id AS id |
| 1913 | FROM civicrm_contribution contribution |
| 1914 | LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere |
| 1915 | WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} |
| 1916 | $additionalWhere |
| 1917 | AND i.id IS NULL"; |
| 1918 | |
| 1919 | $contactSoftCreditContributionsSQL = " |
| 1920 | SELECT contribution.id |
| 1921 | FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution |
| 1922 | ON ( contribution.id = softContribution.contribution_id ) |
| 1923 | WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} "; |
| 1924 | $query = "SELECT count( x.id ) count FROM ( "; |
| 1925 | $query .= $contactContributionsSQL; |
| 1926 | |
| 1927 | if ($includeSoftCredit) { |
| 1928 | $query .= " UNION "; |
| 1929 | $query .= $contactSoftCreditContributionsSQL; |
| 1930 | } |
| 1931 | |
| 1932 | $query .= ") x"; |
| 1933 | |
| 1934 | return CRM_Core_DAO::singleValueQuery($query); |
| 1935 | } |
| 1936 | |
| 1937 | /** |
| 1938 | * Repeat a transaction as part of a recurring series. |
| 1939 | * |
| 1940 | * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function |
| 1941 | * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a |
| 1942 | * subsequent call to the contribution.completetransaction api. |
| 1943 | * |
| 1944 | * The completeTransaction functionality has historically been overloaded to both complete and repeat payments. |
| 1945 | * |
| 1946 | * @param CRM_Contribute_BAO_Contribution $contribution |
| 1947 | * @param array $input |
| 1948 | * @param array $contributionParams |
| 1949 | * |
| 1950 | * @return array |
| 1951 | */ |
| 1952 | protected static function repeatTransaction(&$contribution, &$input, $contributionParams) { |
| 1953 | if (!empty($contribution->id)) { |
| 1954 | return FALSE; |
| 1955 | } |
| 1956 | if (empty($contribution->id)) { |
| 1957 | // Unclear why this would only be set for repeats. |
| 1958 | if (!empty($input['amount'])) { |
| 1959 | $contribution->total_amount = $contributionParams['total_amount'] = $input['amount']; |
| 1960 | } |
| 1961 | $templateContribution = civicrm_api3('Contribution', 'getsingle', array( |
| 1962 | 'contribution_recur_id' => $contributionParams['contribution_recur_id'], |
| 1963 | 'options' => array('limit' => 1), |
| 1964 | )); |
| 1965 | $contributionParams['skipLineItem'] = TRUE; |
| 1966 | $contributionParams['status_id'] = 'Pending'; |
| 1967 | $contributionParams['financial_type_id'] = $templateContribution['financial_type_id']; |
| 1968 | $contributionParams['contact_id'] = $templateContribution['contact_id']; |
| 1969 | $contributionParams['source'] = empty($templateContribution['source']) ? ts('Recurring contribution') : $templateContribution['source']; |
| 1970 | $createContribution = civicrm_api3('Contribution', 'create', $contributionParams); |
| 1971 | $contribution->id = $createContribution['id']; |
| 1972 | $input['line_item'] = CRM_Contribute_BAO_ContributionRecur::addRecurLineItems($contribution->contribution_recur_id, $contribution); |
| 1973 | CRM_Contribute_BAO_ContributionRecur::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id); |
| 1974 | return TRUE; |
| 1975 | } |
| 1976 | } |
| 1977 | |
| 1978 | /** |
| 1979 | * Get individual id for onbehalf contribution. |
| 1980 | * |
| 1981 | * @param int $contributionId |
| 1982 | * Contribution id. |
| 1983 | * @param int $contributorId |
| 1984 | * Contributor id. |
| 1985 | * |
| 1986 | * @return array |
| 1987 | * containing organization id and individual id |
| 1988 | */ |
| 1989 | public static function getOnbehalfIds($contributionId, $contributorId = NULL) { |
| 1990 | |
| 1991 | $ids = array(); |
| 1992 | |
| 1993 | if (!$contributionId) { |
| 1994 | return $ids; |
| 1995 | } |
| 1996 | |
| 1997 | // fetch contributor id if null |
| 1998 | if (!$contributorId) { |
| 1999 | $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', |
| 2000 | $contributionId, 'contact_id' |
| 2001 | ); |
| 2002 | } |
| 2003 | |
| 2004 | $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name'); |
| 2005 | $activityTypeId = array_search('Contribution', $activityTypeIds); |
| 2006 | |
| 2007 | if ($activityTypeId && $contributorId) { |
| 2008 | $activityQuery = " |
| 2009 | SELECT civicrm_activity_contact.contact_id |
| 2010 | FROM civicrm_activity_contact |
| 2011 | INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id |
| 2012 | WHERE civicrm_activity.activity_type_id = %1 |
| 2013 | AND civicrm_activity.source_record_id = %2 |
| 2014 | AND civicrm_activity_contact.record_type_id = %3 |
| 2015 | "; |
| 2016 | |
| 2017 | $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); |
| 2018 | $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); |
| 2019 | |
| 2020 | $params = array( |
| 2021 | 1 => array($activityTypeId, 'Integer'), |
| 2022 | 2 => array($contributionId, 'Integer'), |
| 2023 | 3 => array($sourceID, 'Integer'), |
| 2024 | ); |
| 2025 | |
| 2026 | $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params); |
| 2027 | |
| 2028 | // for on behalf contribution source is individual and contributor is organization |
| 2029 | if ($sourceContactId && $sourceContactId != $contributorId) { |
| 2030 | $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name'); |
| 2031 | // get rel type id for employee of relation |
| 2032 | foreach ($relationshipTypeIds as $id => $typeVals) { |
| 2033 | if ($typeVals['name_a_b'] == 'Employee of') { |
| 2034 | $relationshipTypeId = $id; |
| 2035 | break; |
| 2036 | } |
| 2037 | } |
| 2038 | |
| 2039 | $rel = new CRM_Contact_DAO_Relationship(); |
| 2040 | $rel->relationship_type_id = $relationshipTypeId; |
| 2041 | $rel->contact_id_a = $sourceContactId; |
| 2042 | $rel->contact_id_b = $contributorId; |
| 2043 | if ($rel->find(TRUE)) { |
| 2044 | $ids['individual_id'] = $rel->contact_id_a; |
| 2045 | $ids['organization_id'] = $rel->contact_id_b; |
| 2046 | } |
| 2047 | } |
| 2048 | } |
| 2049 | |
| 2050 | return $ids; |
| 2051 | } |
| 2052 | |
| 2053 | /** |
| 2054 | * @return array |
| 2055 | */ |
| 2056 | public static function getContributionDates() { |
| 2057 | $config = CRM_Core_Config::singleton(); |
| 2058 | $currentMonth = date('m'); |
| 2059 | $currentDay = date('d'); |
| 2060 | if ((int ) $config->fiscalYearStart['M'] > $currentMonth || |
| 2061 | ((int ) $config->fiscalYearStart['M'] == $currentMonth && |
| 2062 | (int ) $config->fiscalYearStart['d'] > $currentDay |
| 2063 | ) |
| 2064 | ) { |
| 2065 | $year = date('Y') - 1; |
| 2066 | } |
| 2067 | else { |
| 2068 | $year = date('Y'); |
| 2069 | } |
| 2070 | $year = array('Y' => $year); |
| 2071 | $yearDate = $config->fiscalYearStart; |
| 2072 | $yearDate = array_merge($year, $yearDate); |
| 2073 | $yearDate = CRM_Utils_Date::format($yearDate); |
| 2074 | |
| 2075 | $monthDate = date('Ym') . '01'; |
| 2076 | |
| 2077 | $now = date('Ymd'); |
| 2078 | |
| 2079 | return array( |
| 2080 | 'now' => $now, |
| 2081 | 'yearDate' => $yearDate, |
| 2082 | 'monthDate' => $monthDate, |
| 2083 | ); |
| 2084 | } |
| 2085 | |
| 2086 | /** |
| 2087 | * Load objects relations to contribution object. |
| 2088 | * Objects are stored in the $_relatedObjects property |
| 2089 | * In the first instance we are just moving functionality from BASEIpn - |
| 2090 | * @see http://issues.civicrm.org/jira/browse/CRM-9996 |
| 2091 | * |
| 2092 | * Note that the unit test for the BaseIPN class tests this function |
| 2093 | * |
| 2094 | * @param array $input |
| 2095 | * Input as delivered from Payment Processor. |
| 2096 | * @param array $ids |
| 2097 | * Ids as Loaded by Payment Processor. |
| 2098 | * @param bool $loadAll |
| 2099 | * Load all related objects - even where id not passed in? (allows API to call this). |
| 2100 | * |
| 2101 | * @return bool |
| 2102 | * @throws Exception |
| 2103 | */ |
| 2104 | public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) { |
| 2105 | if ($loadAll) { |
| 2106 | $ids = array_merge($this->getComponentDetails($this->id), $ids); |
| 2107 | if (empty($ids['contact']) && isset($this->contact_id)) { |
| 2108 | $ids['contact'] = $this->contact_id; |
| 2109 | } |
| 2110 | } |
| 2111 | if (empty($this->_component)) { |
| 2112 | if (!empty($ids['event'])) { |
| 2113 | $this->_component = 'event'; |
| 2114 | } |
| 2115 | else { |
| 2116 | $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute')); |
| 2117 | } |
| 2118 | } |
| 2119 | |
| 2120 | // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious |
| 2121 | // refactoring than anything else, and has unit test coverage. |
| 2122 | if (empty($this->financial_type_id)) { |
| 2123 | $this->find(TRUE); |
| 2124 | } |
| 2125 | |
| 2126 | $paymentProcessorID = CRM_Utils_Array::value('payment_processor_id', $input, CRM_Utils_Array::value( |
| 2127 | 'paymentProcessor', |
| 2128 | $ids |
| 2129 | )); |
| 2130 | |
| 2131 | if (!$paymentProcessorID && $this->contribution_page_id) { |
| 2132 | $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', |
| 2133 | $this->contribution_page_id, |
| 2134 | 'payment_processor' |
| 2135 | ); |
| 2136 | if ($paymentProcessorID) { |
| 2137 | $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage; |
| 2138 | } |
| 2139 | } |
| 2140 | |
| 2141 | $ids['contributionType'] = $this->financial_type_id; |
| 2142 | $ids['financialType'] = $this->financial_type_id; |
| 2143 | |
| 2144 | $entities = array( |
| 2145 | 'contact' => 'CRM_Contact_BAO_Contact', |
| 2146 | 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur', |
| 2147 | 'contributionType' => 'CRM_Financial_BAO_FinancialType', |
| 2148 | 'financialType' => 'CRM_Financial_BAO_FinancialType', |
| 2149 | ); |
| 2150 | foreach ($entities as $entity => $bao) { |
| 2151 | if (!empty($ids[$entity])) { |
| 2152 | $this->_relatedObjects[$entity] = new $bao(); |
| 2153 | $this->_relatedObjects[$entity]->id = $ids[$entity]; |
| 2154 | if (!$this->_relatedObjects[$entity]->find(TRUE)) { |
| 2155 | throw new CRM_Core_Exception($entity . ' could not be loaded'); |
| 2156 | } |
| 2157 | } |
| 2158 | } |
| 2159 | |
| 2160 | if (!empty($ids['contributionRecur']) && !$paymentProcessorID) { |
| 2161 | $paymentProcessorID = $this->_relatedObjects['contributionRecur']->payment_processor_id; |
| 2162 | } |
| 2163 | |
| 2164 | if (!empty($ids['pledge_payment'])) { |
| 2165 | foreach ($ids['pledge_payment'] as $key => $paymentID) { |
| 2166 | if (empty($paymentID)) { |
| 2167 | continue; |
| 2168 | } |
| 2169 | $payment = new CRM_Pledge_BAO_PledgePayment(); |
| 2170 | $payment->id = $paymentID; |
| 2171 | if (!$payment->find(TRUE)) { |
| 2172 | throw new Exception("Could not find pledge payment record: " . $paymentID); |
| 2173 | } |
| 2174 | $this->_relatedObjects['pledge_payment'][] = $payment; |
| 2175 | } |
| 2176 | } |
| 2177 | |
| 2178 | if ($this->_component == 'contribute') { |
| 2179 | // retrieve the other optional objects first so |
| 2180 | // stuff down the line can use this info and do things |
| 2181 | // CRM-6056 |
| 2182 | //in any case get the memberships associated with the contribution |
| 2183 | //because we now support multiple memberships w/ price set |
| 2184 | // see if there are any other memberships to be considered for same contribution. |
| 2185 | $query = " |
| 2186 | SELECT membership_id |
| 2187 | FROM civicrm_membership_payment |
| 2188 | WHERE contribution_id = %1 "; |
| 2189 | $params = array(1 => array($this->id, 'Integer')); |
| 2190 | |
| 2191 | $dao = CRM_Core_DAO::executeQuery($query, $params); |
| 2192 | while ($dao->fetch()) { |
| 2193 | if ($dao->membership_id) { |
| 2194 | if (!is_array($ids['membership'])) { |
| 2195 | $ids['membership'] = array(); |
| 2196 | } |
| 2197 | $ids['membership'][] = $dao->membership_id; |
| 2198 | } |
| 2199 | } |
| 2200 | |
| 2201 | if (array_key_exists('membership', $ids) && is_array($ids['membership'])) { |
| 2202 | foreach ($ids['membership'] as $id) { |
| 2203 | if (!empty($id)) { |
| 2204 | $membership = new CRM_Member_BAO_Membership(); |
| 2205 | $membership->id = $id; |
| 2206 | if (!$membership->find(TRUE)) { |
| 2207 | throw new Exception("Could not find membership record: $id"); |
| 2208 | } |
| 2209 | $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date); |
| 2210 | $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date); |
| 2211 | $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date); |
| 2212 | $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership; |
| 2213 | $membership->free(); |
| 2214 | } |
| 2215 | } |
| 2216 | } |
| 2217 | } |
| 2218 | else { |
| 2219 | // we are in event mode |
| 2220 | // make sure event exists and is valid |
| 2221 | $event = new CRM_Event_BAO_Event(); |
| 2222 | $event->id = $ids['event']; |
| 2223 | if ($ids['event'] && |
| 2224 | !$event->find(TRUE) |
| 2225 | ) { |
| 2226 | throw new Exception("Could not find event: " . $ids['event']); |
| 2227 | } |
| 2228 | |
| 2229 | $this->_relatedObjects['event'] = &$event; |
| 2230 | |
| 2231 | $participant = new CRM_Event_BAO_Participant(); |
| 2232 | $participant->id = $ids['participant']; |
| 2233 | if ($ids['participant'] && |
| 2234 | !$participant->find(TRUE) |
| 2235 | ) { |
| 2236 | throw new Exception("Could not find participant: " . $ids['participant']); |
| 2237 | } |
| 2238 | $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date); |
| 2239 | |
| 2240 | $this->_relatedObjects['participant'] = &$participant; |
| 2241 | |
| 2242 | // get the payment processor id from event - this is inaccurate see CRM-16923 |
| 2243 | // in future we should look at throwing an exception here rather than an dubious guess. |
| 2244 | if (!$paymentProcessorID) { |
| 2245 | $paymentProcessorID = $this->_relatedObjects['event']->payment_processor; |
| 2246 | if ($paymentProcessorID) { |
| 2247 | $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent; |
| 2248 | } |
| 2249 | } |
| 2250 | } |
| 2251 | |
| 2252 | if ($paymentProcessorID) { |
| 2253 | $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID, |
| 2254 | $this->is_test ? 'test' : 'live' |
| 2255 | ); |
| 2256 | $ids['paymentProcessor'] = $paymentProcessorID; |
| 2257 | $this->_relatedObjects['paymentProcessor'] = $paymentProcessor; |
| 2258 | } |
| 2259 | return TRUE; |
| 2260 | } |
| 2261 | |
| 2262 | /** |
| 2263 | * Create array of message information - ie. return html version, txt version, to field |
| 2264 | * |
| 2265 | * @param array $input |
| 2266 | * Incoming information. |
| 2267 | * - is_recur - should this be treated as recurring (not sure why you wouldn't |
| 2268 | * just check presence of recur object but maintaining legacy approach |
| 2269 | * to be careful) |
| 2270 | * @param array $ids |
| 2271 | * IDs of related objects. |
| 2272 | * @param array $values |
| 2273 | * Any values that may have already been compiled by calling process. |
| 2274 | * This is augmented by values 'gathered' by gatherMessageValues |
| 2275 | * @param bool $recur |
| 2276 | * @param bool $returnMessageText |
| 2277 | * Distinguishes between whether to send message or return. |
| 2278 | * message text. We are working towards this function ALWAYS returning message text & calling |
| 2279 | * function doing emails / pdfs with it |
| 2280 | * |
| 2281 | * @return array |
| 2282 | * messages |
| 2283 | * @throws Exception |
| 2284 | */ |
| 2285 | public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) { |
| 2286 | $this->loadRelatedObjects($input, $ids); |
| 2287 | |
| 2288 | if (empty($this->_component)) { |
| 2289 | $this->_component = CRM_Utils_Array::value('component', $input); |
| 2290 | } |
| 2291 | |
| 2292 | //not really sure what params might be passed in but lets merge em into values |
| 2293 | $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values); |
| 2294 | $template = CRM_Core_Smarty::singleton(); |
| 2295 | $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText); |
| 2296 | //what does recur 'mean here - to do with payment processor return functionality but |
| 2297 | // what is the importance |
| 2298 | if ($recur && !empty($this->_relatedObjects['paymentProcessor'])) { |
| 2299 | $paymentObject = Civi\Payment\System::singleton()->getByProcessor($this->_relatedObjects['paymentProcessor']); |
| 2300 | |
| 2301 | $entityID = $entity = NULL; |
| 2302 | if (isset($ids['contribution'])) { |
| 2303 | $entity = 'contribution'; |
| 2304 | $entityID = $ids['contribution']; |
| 2305 | } |
| 2306 | if (!empty($ids['membership'])) { |
| 2307 | //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 |
| 2308 | // 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 |
| 2309 | // line having loaded an array |
| 2310 | $ids['membership'] = (array) $ids['membership']; |
| 2311 | $entity = 'membership'; |
| 2312 | $entityID = $ids['membership'][0]; |
| 2313 | } |
| 2314 | |
| 2315 | $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity)); |
| 2316 | $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing')); |
| 2317 | $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update')); |
| 2318 | |
| 2319 | if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) { |
| 2320 | //direct mode showing billing block, so use directIPN for temporary |
| 2321 | $template->assign('contributeMode', 'directIPN'); |
| 2322 | } |
| 2323 | } |
| 2324 | // todo remove strtolower - check consistency |
| 2325 | if (strtolower($this->_component) == 'event') { |
| 2326 | $eventParams = array('id' => $this->_relatedObjects['participant']->event_id); |
| 2327 | $values['event'] = array(); |
| 2328 | |
| 2329 | CRM_Event_BAO_Event::retrieve($eventParams, $values['event']); |
| 2330 | |
| 2331 | //get location details |
| 2332 | $locationParams = array('entity_id' => $this->_relatedObjects['participant']->event_id, 'entity_table' => 'civicrm_event'); |
| 2333 | $values['location'] = CRM_Core_BAO_Location::getValues($locationParams); |
| 2334 | |
| 2335 | $ufJoinParams = array( |
| 2336 | 'entity_table' => 'civicrm_event', |
| 2337 | 'entity_id' => $ids['event'], |
| 2338 | 'module' => 'CiviEvent', |
| 2339 | ); |
| 2340 | |
| 2341 | list($custom_pre_id, |
| 2342 | $custom_post_ids |
| 2343 | ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); |
| 2344 | |
| 2345 | $values['custom_pre_id'] = $custom_pre_id; |
| 2346 | $values['custom_post_id'] = $custom_post_ids; |
| 2347 | //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case |
| 2348 | //and cases involving status updation through ipn |
| 2349 | // whatever that means! |
| 2350 | // total_amount appears to be the preferred input param & it is unclear why we support amount here |
| 2351 | // perhaps we should throw an e-notice if amount is set & force total_amount? |
| 2352 | if (!empty($input['amount'])) { |
| 2353 | $values['totalAmount'] = $input['amount']; |
| 2354 | } |
| 2355 | |
| 2356 | if ($values['event']['is_email_confirm']) { |
| 2357 | $values['is_email_receipt'] = 1; |
| 2358 | } |
| 2359 | return CRM_Event_BAO_Event::sendMail($ids['contact'], $values, |
| 2360 | $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText |
| 2361 | ); |
| 2362 | } |
| 2363 | else { |
| 2364 | $values['contribution_id'] = $this->id; |
| 2365 | if (!empty($ids['related_contact'])) { |
| 2366 | $values['related_contact'] = $ids['related_contact']; |
| 2367 | if (isset($ids['onbehalf_dupe_alert'])) { |
| 2368 | $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert']; |
| 2369 | } |
| 2370 | $entityBlock = array( |
| 2371 | 'contact_id' => $ids['contact'], |
| 2372 | 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', |
| 2373 | 'Home', 'id', 'name' |
| 2374 | ), |
| 2375 | ); |
| 2376 | $address = CRM_Core_BAO_Address::getValues($entityBlock); |
| 2377 | $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']); |
| 2378 | } |
| 2379 | $isTest = FALSE; |
| 2380 | if ($this->is_test) { |
| 2381 | $isTest = TRUE; |
| 2382 | } |
| 2383 | if (!empty($this->_relatedObjects['membership'])) { |
| 2384 | foreach ($this->_relatedObjects['membership'] as $membership) { |
| 2385 | if ($membership->id) { |
| 2386 | $values['isMembership'] = TRUE; |
| 2387 | |
| 2388 | // need to set the membership values here |
| 2389 | $template->assign('membership_assign', 1); |
| 2390 | $template->assign('membership_name', |
| 2391 | CRM_Member_PseudoConstant::membershipType($membership->membership_type_id) |
| 2392 | ); |
| 2393 | $template->assign('mem_start_date', $membership->start_date); |
| 2394 | $template->assign('mem_join_date', $membership->join_date); |
| 2395 | $template->assign('mem_end_date', $membership->end_date); |
| 2396 | $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label'); |
| 2397 | $template->assign('mem_status', $membership_status); |
| 2398 | if ($membership_status == 'Pending' && $membership->is_pay_later == 1) { |
| 2399 | $template->assign('is_pay_later', 1); |
| 2400 | } |
| 2401 | |
| 2402 | // if separate payment there are two contributions recorded and the |
| 2403 | // admin will need to send a receipt for each of them separately. |
| 2404 | // we dont link the two in the db (but can potentially infer it if needed) |
| 2405 | $template->assign('is_separate_payment', 0); |
| 2406 | |
| 2407 | if ($recur && $paymentObject) { |
| 2408 | $url = $paymentObject->subscriptionURL($membership->id, 'membership'); |
| 2409 | $template->assign('cancelSubscriptionUrl', $url); |
| 2410 | $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing'); |
| 2411 | $template->assign('updateSubscriptionBillingUrl', $url); |
| 2412 | $url = $paymentObject->subscriptionURL($entityID, $entity, 'update'); |
| 2413 | $template->assign('updateSubscriptionUrl', $url); |
| 2414 | } |
| 2415 | |
| 2416 | $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText); |
| 2417 | |
| 2418 | return $result; |
| 2419 | // otherwise if its about sending emails, continue sending without return, as we |
| 2420 | // don't want to exit the loop. |
| 2421 | } |
| 2422 | } |
| 2423 | } |
| 2424 | else { |
| 2425 | return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText); |
| 2426 | } |
| 2427 | } |
| 2428 | } |
| 2429 | |
| 2430 | /** |
| 2431 | * Gather values for contribution mail - this function has been created |
| 2432 | * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function |
| 2433 | * Values related to the contribution in question are gathered |
| 2434 | * |
| 2435 | * @param array $input |
| 2436 | * Input into function (probably from payment processor). |
| 2437 | * @param array $values |
| 2438 | * @param array $ids |
| 2439 | * The set of ids related to the input. |
| 2440 | * |
| 2441 | * @return array |
| 2442 | */ |
| 2443 | public function _gatherMessageValues($input, &$values, $ids = array()) { |
| 2444 | // set display address of contributor |
| 2445 | if ($this->address_id) { |
| 2446 | $addressParams = array('id' => $this->address_id); |
| 2447 | $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id'); |
| 2448 | $addressDetails = array_values($addressDetails); |
| 2449 | $values['address'] = $addressDetails[0]['display']; |
| 2450 | } |
| 2451 | if ($this->_component == 'contribute') { |
| 2452 | //get soft contributions |
| 2453 | $softContributions = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id, TRUE); |
| 2454 | if (!empty($softContributions)) { |
| 2455 | $values['softContributions'] = $softContributions['soft_credit']; |
| 2456 | } |
| 2457 | if (isset($this->contribution_page_id)) { |
| 2458 | CRM_Contribute_BAO_ContributionPage::setValues( |
| 2459 | $this->contribution_page_id, |
| 2460 | $values |
| 2461 | ); |
| 2462 | if ($this->contribution_page_id) { |
| 2463 | // CRM-8254 - override default currency if applicable |
| 2464 | $config = CRM_Core_Config::singleton(); |
| 2465 | $config->defaultCurrency = CRM_Utils_Array::value( |
| 2466 | 'currency', |
| 2467 | $values, |
| 2468 | $config->defaultCurrency |
| 2469 | ); |
| 2470 | } |
| 2471 | } |
| 2472 | // no contribution page -probably back office |
| 2473 | else { |
| 2474 | // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id) |
| 2475 | $values['is_email_receipt'] = 1; |
| 2476 | $values['title'] = 'Contribution'; |
| 2477 | } |
| 2478 | // set lineItem for contribution |
| 2479 | if ($this->id) { |
| 2480 | $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->id, 'contribution', 1); |
| 2481 | if (!empty($lineItem)) { |
| 2482 | $itemId = key($lineItem); |
| 2483 | foreach ($lineItem as &$eachItem) { |
| 2484 | if (is_array($this->_relatedObjects['membership']) && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership'])) { |
| 2485 | $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date); |
| 2486 | $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date); |
| 2487 | $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date); |
| 2488 | } |
| 2489 | } |
| 2490 | $values['lineItem'][0] = $lineItem; |
| 2491 | $values['priceSetID'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id'); |
| 2492 | } |
| 2493 | } |
| 2494 | |
| 2495 | $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds( |
| 2496 | $this->id, |
| 2497 | $this->contact_id |
| 2498 | ); |
| 2499 | // if this is onbehalf of contribution then set related contact |
| 2500 | if (!empty($relatedContact['individual_id'])) { |
| 2501 | $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id']; |
| 2502 | } |
| 2503 | } |
| 2504 | else { |
| 2505 | // event |
| 2506 | $eventParams = array( |
| 2507 | 'id' => $this->_relatedObjects['event']->id, |
| 2508 | ); |
| 2509 | $values['event'] = array(); |
| 2510 | |
| 2511 | CRM_Event_BAO_Event::retrieve($eventParams, $values['event']); |
| 2512 | // add custom fields for event |
| 2513 | $eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Event', $this->_relatedObjects['event'], $this->_relatedObjects['event']->id); |
| 2514 | |
| 2515 | $eventCustomGroup = array(); |
| 2516 | foreach ($eventGroupTree as $key => $group) { |
| 2517 | if ($key === 'info') { |
| 2518 | continue; |
| 2519 | } |
| 2520 | |
| 2521 | foreach ($group['fields'] as $k => $customField) { |
| 2522 | $groupLabel = $group['title']; |
| 2523 | if (!empty($customField['customValue'])) { |
| 2524 | foreach ($customField['customValue'] as $customFieldValues) { |
| 2525 | $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues); |
| 2526 | } |
| 2527 | } |
| 2528 | } |
| 2529 | } |
| 2530 | $values['event']['customGroup'] = $eventCustomGroup; |
| 2531 | |
| 2532 | //get participant details |
| 2533 | $participantParams = array( |
| 2534 | 'id' => $this->_relatedObjects['participant']->id, |
| 2535 | ); |
| 2536 | |
| 2537 | $values['participant'] = array(); |
| 2538 | |
| 2539 | CRM_Event_BAO_Participant::getValues($participantParams, $values['participant'], $participantIds); |
| 2540 | // add custom fields for event |
| 2541 | $participantGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this->_relatedObjects['participant'], $this->_relatedObjects['participant']->id); |
| 2542 | $participantCustomGroup = array(); |
| 2543 | foreach ($participantGroupTree as $key => $group) { |
| 2544 | if ($key === 'info') { |
| 2545 | continue; |
| 2546 | } |
| 2547 | |
| 2548 | foreach ($group['fields'] as $k => $customField) { |
| 2549 | $groupLabel = $group['title']; |
| 2550 | if (!empty($customField['customValue'])) { |
| 2551 | foreach ($customField['customValue'] as $customFieldValues) { |
| 2552 | $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues); |
| 2553 | } |
| 2554 | } |
| 2555 | } |
| 2556 | } |
| 2557 | $values['participant']['customGroup'] = $participantCustomGroup; |
| 2558 | |
| 2559 | //get location details |
| 2560 | $locationParams = array( |
| 2561 | 'entity_id' => $this->_relatedObjects['event']->id, |
| 2562 | 'entity_table' => 'civicrm_event', |
| 2563 | ); |
| 2564 | $values['location'] = CRM_Core_BAO_Location::getValues($locationParams); |
| 2565 | |
| 2566 | $ufJoinParams = array( |
| 2567 | 'entity_table' => 'civicrm_event', |
| 2568 | 'entity_id' => $ids['event'], |
| 2569 | 'module' => 'CiviEvent', |
| 2570 | ); |
| 2571 | |
| 2572 | list($custom_pre_id, |
| 2573 | $custom_post_ids |
| 2574 | ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); |
| 2575 | |
| 2576 | $values['custom_pre_id'] = $custom_pre_id; |
| 2577 | $values['custom_post_id'] = $custom_post_ids; |
| 2578 | |
| 2579 | // set lineItem for event contribution |
| 2580 | if ($this->id) { |
| 2581 | $participantIds = CRM_Event_BAO_Participant::getParticipantIds($this->id); |
| 2582 | if (!empty($participantIds)) { |
| 2583 | foreach ($participantIds as $pIDs) { |
| 2584 | $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs); |
| 2585 | if (!CRM_Utils_System::isNull($lineItem)) { |
| 2586 | $values['lineItem'][] = $lineItem; |
| 2587 | } |
| 2588 | } |
| 2589 | } |
| 2590 | } |
| 2591 | } |
| 2592 | |
| 2593 | $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', $this, $this->id); |
| 2594 | |
| 2595 | $customGroup = array(); |
| 2596 | foreach ($groupTree as $key => $group) { |
| 2597 | if ($key === 'info') { |
| 2598 | continue; |
| 2599 | } |
| 2600 | |
| 2601 | foreach ($group['fields'] as $k => $customField) { |
| 2602 | $groupLabel = $group['title']; |
| 2603 | if (!empty($customField['customValue'])) { |
| 2604 | foreach ($customField['customValue'] as $customFieldValues) { |
| 2605 | $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues); |
| 2606 | } |
| 2607 | } |
| 2608 | } |
| 2609 | } |
| 2610 | $values['customGroup'] = $customGroup; |
| 2611 | |
| 2612 | return $values; |
| 2613 | } |
| 2614 | |
| 2615 | /** |
| 2616 | * Apply variables for message to smarty template - this function is part of analysing what is in the huge |
| 2617 | * function & breaking it down into manageable chunks. Eventually it will be refactored into something else |
| 2618 | * Note we send directly from this function in some cases because it is only partly refactored |
| 2619 | * Don't call this function directly as the signature will change |
| 2620 | * |
| 2621 | * @param $values |
| 2622 | * @param $input |
| 2623 | * @param CRM_Core_SMARTY $template |
| 2624 | * @param bool $recur |
| 2625 | * @param bool $returnMessageText |
| 2626 | * |
| 2627 | * @return mixed |
| 2628 | */ |
| 2629 | public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) { |
| 2630 | $template->assign('first_name', $this->_relatedObjects['contact']->first_name); |
| 2631 | $template->assign('last_name', $this->_relatedObjects['contact']->last_name); |
| 2632 | $template->assign('displayName', $this->_relatedObjects['contact']->display_name); |
| 2633 | if (!empty($values['lineItem']) && !empty($this->_relatedObjects['membership'])) { |
| 2634 | $template->assign('useForMember', TRUE); |
| 2635 | } |
| 2636 | //assign honor information to receipt message |
| 2637 | $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id); |
| 2638 | |
| 2639 | if (isset($softRecord['soft_credit'])) { |
| 2640 | //if id of contribution page is present |
| 2641 | if (!empty($values['id'])) { |
| 2642 | $values['honor'] = array( |
| 2643 | 'honor_profile_values' => array(), |
| 2644 | 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'), |
| 2645 | 'honor_id' => $softRecord['soft_credit'][1]['contact_id'], |
| 2646 | ); |
| 2647 | $softCreditTypes = CRM_Core_OptionGroup::values('soft_credit_type'); |
| 2648 | |
| 2649 | $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']); |
| 2650 | $template->assign('honor_block_is_active', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id')); |
| 2651 | } |
| 2652 | else { |
| 2653 | //offline contribution |
| 2654 | $softCreditTypes = $softCredits = array(); |
| 2655 | foreach ($softRecord['soft_credit'] as $key => $softCredit) { |
| 2656 | $softCreditTypes[$key] = $softCredit['soft_credit_type_label']; |
| 2657 | $softCredits[$key] = array( |
| 2658 | 'Name' => $softCredit['contact_name'], |
| 2659 | 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']), |
| 2660 | ); |
| 2661 | } |
| 2662 | $template->assign('softCreditTypes', $softCreditTypes); |
| 2663 | $template->assign('softCredits', $softCredits); |
| 2664 | } |
| 2665 | } |
| 2666 | |
| 2667 | $dao = new CRM_Contribute_DAO_ContributionProduct(); |
| 2668 | $dao->contribution_id = $this->id; |
| 2669 | if ($dao->find(TRUE)) { |
| 2670 | $premiumId = $dao->product_id; |
| 2671 | $template->assign('option', $dao->product_option); |
| 2672 | |
| 2673 | $productDAO = new CRM_Contribute_DAO_Product(); |
| 2674 | $productDAO->id = $premiumId; |
| 2675 | $productDAO->find(TRUE); |
| 2676 | $template->assign('selectPremium', TRUE); |
| 2677 | $template->assign('product_name', $productDAO->name); |
| 2678 | $template->assign('price', $productDAO->price); |
| 2679 | $template->assign('sku', $productDAO->sku); |
| 2680 | } |
| 2681 | $template->assign('title', CRM_Utils_Array::value('title', $values)); |
| 2682 | $amount = CRM_Utils_Array::value('total_amount', $input, (CRM_Utils_Array::value('amount', $input)), NULL); |
| 2683 | if (empty($amount) && isset($this->total_amount)) { |
| 2684 | $amount = $this->total_amount; |
| 2685 | } |
| 2686 | $template->assign('amount', $amount); |
| 2687 | // add the new contribution values |
| 2688 | if (strtolower($this->_component) == 'contribute') { |
| 2689 | //PCP Info |
| 2690 | $softDAO = new CRM_Contribute_DAO_ContributionSoft(); |
| 2691 | $softDAO->contribution_id = $this->id; |
| 2692 | if ($softDAO->find(TRUE)) { |
| 2693 | $template->assign('pcpBlock', TRUE); |
| 2694 | $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll); |
| 2695 | $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname); |
| 2696 | $template->assign('pcp_personal_note', $softDAO->pcp_personal_note); |
| 2697 | |
| 2698 | //assign the pcp page title for email subject |
| 2699 | $pcpDAO = new CRM_PCP_DAO_PCP(); |
| 2700 | $pcpDAO->id = $softDAO->pcp_id; |
| 2701 | if ($pcpDAO->find(TRUE)) { |
| 2702 | $template->assign('title', $pcpDAO->title); |
| 2703 | } |
| 2704 | } |
| 2705 | } |
| 2706 | |
| 2707 | if ($this->financial_type_id) { |
| 2708 | $values['financial_type_id'] = $this->financial_type_id; |
| 2709 | } |
| 2710 | |
| 2711 | $template->assign('trxn_id', $this->trxn_id); |
| 2712 | $template->assign('receive_date', |
| 2713 | CRM_Utils_Date::mysqlToIso($this->receive_date) |
| 2714 | ); |
| 2715 | $template->assign('contributeMode', 'notify'); |
| 2716 | $template->assign('action', $this->is_test ? 1024 : 1); |
| 2717 | $template->assign('receipt_text', |
| 2718 | CRM_Utils_Array::value('receipt_text', |
| 2719 | $values |
| 2720 | ) |
| 2721 | ); |
| 2722 | $template->assign('is_monetary', 1); |
| 2723 | $template->assign('is_recur', (bool) $recur); |
| 2724 | $template->assign('currency', $this->currency); |
| 2725 | $template->assign('address', CRM_Utils_Address::format($input)); |
| 2726 | if (!empty($values['customGroup'])) { |
| 2727 | $template->assign('customGroup', $values['customGroup']); |
| 2728 | } |
| 2729 | if (!empty($values['softContributions'])) { |
| 2730 | $template->assign('softContributions', $values['softContributions']); |
| 2731 | } |
| 2732 | if ($this->_component == 'event') { |
| 2733 | $template->assign('title', $values['event']['title']); |
| 2734 | $participantRoles = CRM_Event_PseudoConstant::participantRole(); |
| 2735 | $viewRoles = array(); |
| 2736 | foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) { |
| 2737 | $viewRoles[] = $participantRoles[$v]; |
| 2738 | } |
| 2739 | $values['event']['participant_role'] = implode(', ', $viewRoles); |
| 2740 | $template->assign('event', $values['event']); |
| 2741 | $template->assign('participant', $values['participant']); |
| 2742 | $template->assign('location', $values['location']); |
| 2743 | $template->assign('customPre', $values['custom_pre_id']); |
| 2744 | $template->assign('customPost', $values['custom_post_id']); |
| 2745 | |
| 2746 | $isTest = FALSE; |
| 2747 | if ($this->_relatedObjects['participant']->is_test) { |
| 2748 | $isTest = TRUE; |
| 2749 | } |
| 2750 | |
| 2751 | $values['params'] = array(); |
| 2752 | //to get email of primary participant. |
| 2753 | $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id'); |
| 2754 | $primaryAmount[] = array( |
| 2755 | 'label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail, |
| 2756 | 'amount' => $this->_relatedObjects['participant']->fee_amount, |
| 2757 | ); |
| 2758 | //build an array of cId/pId of participants |
| 2759 | $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE); |
| 2760 | unset($additionalIDs[$this->_relatedObjects['participant']->id]); |
| 2761 | //send receipt to additional participant if exists |
| 2762 | if (count($additionalIDs)) { |
| 2763 | $template->assign('isPrimary', 0); |
| 2764 | $template->assign('customProfile', NULL); |
| 2765 | //set additionalParticipant true |
| 2766 | $values['params']['additionalParticipant'] = TRUE; |
| 2767 | foreach ($additionalIDs as $pId => $cId) { |
| 2768 | $amount = array(); |
| 2769 | //to change the status pending to completed |
| 2770 | $additional = new CRM_Event_DAO_Participant(); |
| 2771 | $additional->id = $pId; |
| 2772 | $additional->contact_id = $cId; |
| 2773 | $additional->find(TRUE); |
| 2774 | $additional->register_date = $this->_relatedObjects['participant']->register_date; |
| 2775 | $additional->status_id = 1; |
| 2776 | $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id'); |
| 2777 | //if additional participant dont have email |
| 2778 | //use display name. |
| 2779 | if (!$additionalParticipantInfo) { |
| 2780 | $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id); |
| 2781 | } |
| 2782 | $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount); |
| 2783 | $primaryAmount[] = array( |
| 2784 | 'label' => $additional->fee_level . ' - ' . $additionalParticipantInfo, |
| 2785 | 'amount' => $additional->fee_amount, |
| 2786 | ); |
| 2787 | $additional->save(); |
| 2788 | $additional->free(); |
| 2789 | $template->assign('amount', $amount); |
| 2790 | CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText); |
| 2791 | } |
| 2792 | } |
| 2793 | |
| 2794 | //build an array of custom profile and assigning it to template |
| 2795 | $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest); |
| 2796 | |
| 2797 | if (count($customProfile)) { |
| 2798 | $template->assign('customProfile', $customProfile); |
| 2799 | } |
| 2800 | |
| 2801 | // for primary contact |
| 2802 | $values['params']['additionalParticipant'] = FALSE; |
| 2803 | $template->assign('isPrimary', 1); |
| 2804 | $template->assign('amount', $primaryAmount); |
| 2805 | $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date)); |
| 2806 | if ($this->payment_instrument_id) { |
| 2807 | $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); |
| 2808 | $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]); |
| 2809 | } |
| 2810 | // carry paylater, since we did not created billing, |
| 2811 | // so need to pull email from primary location, CRM-4395 |
| 2812 | $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later; |
| 2813 | } |
| 2814 | return $template; |
| 2815 | } |
| 2816 | |
| 2817 | /** |
| 2818 | * Check whether payment processor supports |
| 2819 | * cancellation of contribution subscription |
| 2820 | * |
| 2821 | * @param int $contributionId |
| 2822 | * Contribution id. |
| 2823 | * |
| 2824 | * @param bool $isNotCancelled |
| 2825 | * |
| 2826 | * @return bool |
| 2827 | */ |
| 2828 | public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) { |
| 2829 | $cacheKeyString = "$contributionId"; |
| 2830 | $cacheKeyString .= $isNotCancelled ? '_1' : '_0'; |
| 2831 | |
| 2832 | static $supportsCancel = array(); |
| 2833 | |
| 2834 | if (!array_key_exists($cacheKeyString, $supportsCancel)) { |
| 2835 | $supportsCancel[$cacheKeyString] = FALSE; |
| 2836 | $isCancelled = FALSE; |
| 2837 | |
| 2838 | if ($isNotCancelled) { |
| 2839 | $isCancelled = self::isSubscriptionCancelled($contributionId); |
| 2840 | } |
| 2841 | |
| 2842 | $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj'); |
| 2843 | if (!empty($paymentObject)) { |
| 2844 | $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled; |
| 2845 | } |
| 2846 | } |
| 2847 | return $supportsCancel[$cacheKeyString]; |
| 2848 | } |
| 2849 | |
| 2850 | /** |
| 2851 | * Check whether subscription is already cancelled. |
| 2852 | * |
| 2853 | * @param int $contributionId |
| 2854 | * Contribution id. |
| 2855 | * |
| 2856 | * @return string |
| 2857 | * contribution status |
| 2858 | */ |
| 2859 | public static function isSubscriptionCancelled($contributionId) { |
| 2860 | $sql = " |
| 2861 | SELECT cr.contribution_status_id |
| 2862 | FROM civicrm_contribution_recur cr |
| 2863 | LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id ) |
| 2864 | WHERE con.id = %1 LIMIT 1"; |
| 2865 | $params = array(1 => array($contributionId, 'Integer')); |
| 2866 | $statusId = CRM_Core_DAO::singleValueQuery($sql, $params); |
| 2867 | $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId); |
| 2868 | if ($status == 'Cancelled') { |
| 2869 | return TRUE; |
| 2870 | } |
| 2871 | return FALSE; |
| 2872 | } |
| 2873 | |
| 2874 | /** |
| 2875 | * Create all financial accounts entry. |
| 2876 | * |
| 2877 | * @param array $params |
| 2878 | * Contribution object, line item array and params for trxn. |
| 2879 | * |
| 2880 | * |
| 2881 | * @param array $financialTrxnValues |
| 2882 | * |
| 2883 | * @return null|object |
| 2884 | */ |
| 2885 | public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) { |
| 2886 | $skipRecords = $update = $return = $isRelatedId = FALSE; |
| 2887 | |
| 2888 | $additionalParticipantId = array(); |
| 2889 | $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
| 2890 | |
| 2891 | if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') { |
| 2892 | $entityId = $params['participant_id']; |
| 2893 | $entityTable = 'civicrm_participant'; |
| 2894 | $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId); |
| 2895 | } |
| 2896 | elseif (!empty($params['membership_id'])) { |
| 2897 | //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships |
| 2898 | // are created off one contribution should be handled elsewhere |
| 2899 | $entityId = $params['membership_id']; |
| 2900 | $entityTable = 'civicrm_membership'; |
| 2901 | } |
| 2902 | else { |
| 2903 | $entityId = $params['contribution']->id; |
| 2904 | $entityTable = 'civicrm_contribution'; |
| 2905 | } |
| 2906 | |
| 2907 | if (CRM_Utils_Array::value('contribution_mode', $params) == 'membership') { |
| 2908 | $isRelatedId = TRUE; |
| 2909 | } |
| 2910 | |
| 2911 | $entityID[] = $entityId; |
| 2912 | if (!empty($additionalParticipantId)) { |
| 2913 | $entityID += $additionalParticipantId; |
| 2914 | } |
| 2915 | // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated |
| 2916 | if (empty($params['prevContribution'])) { |
| 2917 | $entityID = NULL; |
| 2918 | } |
| 2919 | else { |
| 2920 | $update = TRUE; |
| 2921 | } |
| 2922 | |
| 2923 | $statusId = $params['contribution']->contribution_status_id; |
| 2924 | // CRM-13964 partial payment |
| 2925 | if (CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses) |
| 2926 | && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay']) |
| 2927 | ) { |
| 2928 | $partialAmtPay = $params['partial_amount_pay']; |
| 2929 | $partialAmtTotal = $params['partial_payment_total']; |
| 2930 | |
| 2931 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); |
| 2932 | $fromFinancialAccountId = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId); |
| 2933 | $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'); |
| 2934 | $params['total_amount'] = $partialAmtPay; |
| 2935 | |
| 2936 | $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($params['contribution']->id, $params['financial_type_id']); |
| 2937 | if (empty($balanceTrxnInfo['trxn_id'])) { |
| 2938 | // create new balance transaction record |
| 2939 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); |
| 2940 | $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId); |
| 2941 | |
| 2942 | $balanceTrxnParams['total_amount'] = $partialAmtTotal; |
| 2943 | $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount; |
| 2944 | $balanceTrxnParams['contribution_id'] = $params['contribution']->id; |
| 2945 | $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis'); |
| 2946 | $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params); |
| 2947 | $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('net_amount', $params); |
| 2948 | $balanceTrxnParams['currency'] = $params['contribution']->currency; |
| 2949 | $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id; |
| 2950 | $balanceTrxnParams['status_id'] = $statusId; |
| 2951 | $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id; |
| 2952 | $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params); |
| 2953 | if (!empty($params['payment_processor'])) { |
| 2954 | $balanceTrxnParams['payment_processor_id'] = $params['payment_processor']; |
| 2955 | } |
| 2956 | $financialTxn = CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams); |
| 2957 | } |
| 2958 | } |
| 2959 | |
| 2960 | // build line item array if its not set in $params |
| 2961 | if (empty($params['line_item']) || $additionalParticipantId) { |
| 2962 | CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId); |
| 2963 | } |
| 2964 | |
| 2965 | if (CRM_Utils_Array::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) && |
| 2966 | !(CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later) |
| 2967 | ) { |
| 2968 | $skipRecords = TRUE; |
| 2969 | $pendingStatus = array( |
| 2970 | array_search('Pending', $contributionStatuses), |
| 2971 | array_search('In Progress', $contributionStatuses), |
| 2972 | ); |
| 2973 | if (in_array(CRM_Utils_Array::value('contribution_status_id', $params), $pendingStatus)) { |
| 2974 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); |
| 2975 | $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId); |
| 2976 | } |
| 2977 | elseif (!empty($params['payment_processor'])) { |
| 2978 | $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id'); |
| 2979 | } |
| 2980 | elseif (!empty($params['payment_instrument_id'])) { |
| 2981 | $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']); |
| 2982 | } |
| 2983 | else { |
| 2984 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' ")); |
| 2985 | $queryParams = array(1 => array($relationTypeId, 'Integer')); |
| 2986 | $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); |
| 2987 | } |
| 2988 | |
| 2989 | $totalAmount = CRM_Utils_Array::value('total_amount', $params); |
| 2990 | if (!isset($totalAmount) && !empty($params['prevContribution'])) { |
| 2991 | $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount; |
| 2992 | } |
| 2993 | |
| 2994 | //build financial transaction params |
| 2995 | $trxnParams = array( |
| 2996 | 'contribution_id' => $params['contribution']->id, |
| 2997 | 'to_financial_account_id' => $params['to_financial_account_id'], |
| 2998 | 'trxn_date' => !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis'), |
| 2999 | 'total_amount' => $totalAmount, |
| 3000 | 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params), |
| 3001 | 'net_amount' => CRM_Utils_Array::value('net_amount', $params, $totalAmount), |
| 3002 | 'currency' => $params['contribution']->currency, |
| 3003 | 'trxn_id' => $params['contribution']->trxn_id, |
| 3004 | 'status_id' => $statusId, |
| 3005 | 'payment_instrument_id' => $params['contribution']->payment_instrument_id, |
| 3006 | 'check_number' => CRM_Utils_Array::value('check_number', $params), |
| 3007 | ); |
| 3008 | |
| 3009 | if (!empty($params['payment_processor'])) { |
| 3010 | $trxnParams['payment_processor_id'] = $params['payment_processor']; |
| 3011 | } |
| 3012 | |
| 3013 | if (isset($fromFinancialAccountId)) { |
| 3014 | $trxnParams['from_financial_account_id'] = $fromFinancialAccountId; |
| 3015 | } |
| 3016 | |
| 3017 | // consider external values passed for recording transaction entry |
| 3018 | if (!empty($financialTrxnValues)) { |
| 3019 | $trxnParams = array_merge($trxnParams, $financialTrxnValues); |
| 3020 | } |
| 3021 | |
| 3022 | $params['trxnParams'] = $trxnParams; |
| 3023 | |
| 3024 | if (!empty($params['prevContribution'])) { |
| 3025 | $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount; |
| 3026 | $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount; |
| 3027 | $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount; |
| 3028 | $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id; |
| 3029 | $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id; |
| 3030 | |
| 3031 | if (!(($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses) |
| 3032 | || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatuses)) |
| 3033 | && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses)) |
| 3034 | ) { |
| 3035 | $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id; |
| 3036 | $params['trxnParams']['check_number'] = $params['prevContribution']->check_number; |
| 3037 | } |
| 3038 | |
| 3039 | //if financial type is changed |
| 3040 | if (!empty($params['financial_type_id']) && |
| 3041 | $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id |
| 3042 | ) { |
| 3043 | $incomeTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' ")); |
| 3044 | $oldFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $incomeTypeId); |
| 3045 | $newFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $incomeTypeId); |
| 3046 | if ($oldFinancialAccount != $newFinancialAccount) { |
| 3047 | $params['total_amount'] = 0; |
| 3048 | if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) { |
| 3049 | $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType( |
| 3050 | $params['prevContribution']->financial_type_id, $relationTypeId); |
| 3051 | } |
| 3052 | else { |
| 3053 | $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC'); |
| 3054 | if (!empty($lastFinancialTrxnId['financialTrxnId'])) { |
| 3055 | $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id'); |
| 3056 | } |
| 3057 | } |
| 3058 | self::updateFinancialAccounts($params, 'changeFinancialType'); |
| 3059 | /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */ |
| 3060 | $params['financial_account_id'] = $newFinancialAccount; |
| 3061 | $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; |
| 3062 | self::updateFinancialAccounts($params); |
| 3063 | $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; |
| 3064 | } |
| 3065 | } |
| 3066 | |
| 3067 | //Update contribution status |
| 3068 | $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id; |
| 3069 | $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id; |
| 3070 | if (!empty($params['contribution_status_id']) && |
| 3071 | $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id |
| 3072 | ) { |
| 3073 | //Update Financial Records |
| 3074 | self::updateFinancialAccounts($params, 'changedStatus'); |
| 3075 | } |
| 3076 | |
| 3077 | // change Payment Instrument for a Completed contribution |
| 3078 | // first handle special case when contribution is changed from Pending to Completed status when initial payment |
| 3079 | // instrument is null and now new payment instrument is added along with the payment |
| 3080 | $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id; |
| 3081 | $params['trxnParams']['check_number'] = CRM_Utils_Array::value('check_number', $params); |
| 3082 | if (array_key_exists('payment_instrument_id', $params)) { |
| 3083 | $params['trxnParams']['total_amount'] = -$trxnParams['total_amount']; |
| 3084 | if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) && |
| 3085 | !CRM_Utils_System::isNull($params['contribution']->payment_instrument_id) |
| 3086 | ) { |
| 3087 | //check if status is changed from Pending to Completed |
| 3088 | // do not update payment instrument changes for Pending to Completed |
| 3089 | if (!($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses) && |
| 3090 | in_array($params['prevContribution']->contribution_status_id, $pendingStatus)) |
| 3091 | ) { |
| 3092 | // for all other statuses create new financial records |
| 3093 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); |
| 3094 | $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; |
| 3095 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); |
| 3096 | } |
| 3097 | } |
| 3098 | elseif ((!CRM_Utils_System::isNull($params['contribution']->payment_instrument_id) || |
| 3099 | !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) && |
| 3100 | $params['contribution']->payment_instrument_id != $params['prevContribution']->payment_instrument_id |
| 3101 | ) { |
| 3102 | // for any other payment instrument changes create new financial records |
| 3103 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); |
| 3104 | $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; |
| 3105 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); |
| 3106 | } |
| 3107 | elseif (!CRM_Utils_System::isNull($params['contribution']->check_number) && |
| 3108 | $params['contribution']->check_number != $params['prevContribution']->check_number |
| 3109 | ) { |
| 3110 | // another special case when check number is changed, create new financial records |
| 3111 | // create financial trxn with negative amount |
| 3112 | $params['trxnParams']['check_number'] = $params['prevContribution']->check_number; |
| 3113 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); |
| 3114 | // create financial trxn with positive amount |
| 3115 | $params['trxnParams']['check_number'] = $params['contribution']->check_number; |
| 3116 | $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; |
| 3117 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); |
| 3118 | } |
| 3119 | } |
| 3120 | |
| 3121 | //if Change contribution amount |
| 3122 | $params['trxnParams']['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params); |
| 3123 | $params['trxnParams']['net_amount'] = CRM_Utils_Array::value('net_amount', $params); |
| 3124 | $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount; |
| 3125 | $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id; |
| 3126 | if (isset($totalAmount) && |
| 3127 | $totalAmount != $params['prevContribution']->total_amount |
| 3128 | ) { |
| 3129 | //Update Financial Records |
| 3130 | $params['trxnParams']['from_financial_account_id'] = NULL; |
| 3131 | self::updateFinancialAccounts($params, 'changedAmount'); |
| 3132 | } |
| 3133 | } |
| 3134 | |
| 3135 | if (!$update) { |
| 3136 | // records finanical trxn and entity financial trxn |
| 3137 | // also make it available as return value |
| 3138 | $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams); |
| 3139 | $params['entity_id'] = $financialTxn->id; |
| 3140 | } |
| 3141 | } |
| 3142 | // record line items and financial items |
| 3143 | if (empty($params['skipLineItem'])) { |
| 3144 | CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $update); |
| 3145 | } |
| 3146 | |
| 3147 | // create batch entry if batch_id is passed and |
| 3148 | // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611 |
| 3149 | if (!empty($params['batch_id']) && !empty($financialTxn)) { |
| 3150 | $entityParams = array( |
| 3151 | 'batch_id' => $params['batch_id'], |
| 3152 | 'entity_table' => 'civicrm_financial_trxn', |
| 3153 | 'entity_id' => $financialTxn->id, |
| 3154 | ); |
| 3155 | CRM_Batch_BAO_Batch::addBatchEntity($entityParams); |
| 3156 | } |
| 3157 | |
| 3158 | // when a fee is charged |
| 3159 | if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) { |
| 3160 | CRM_Core_BAO_FinancialTrxn::recordFees($params); |
| 3161 | } |
| 3162 | |
| 3163 | if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant' |
| 3164 | && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id |
| 3165 | ) { |
| 3166 | $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id'); |
| 3167 | $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level); |
| 3168 | CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel); |
| 3169 | } |
| 3170 | unset($params['line_item']); |
| 3171 | |
| 3172 | return $return; |
| 3173 | } |
| 3174 | |
| 3175 | /** |
| 3176 | * Update all financial accounts entry. |
| 3177 | * |
| 3178 | * @param array $params |
| 3179 | * Contribution object, line item array and params for trxn. |
| 3180 | * |
| 3181 | * @param string $context |
| 3182 | * Update scenarios. |
| 3183 | * |
| 3184 | * @param null $skipTrxn |
| 3185 | * |
| 3186 | */ |
| 3187 | public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) { |
| 3188 | $itemAmount = $trxnID = NULL; |
| 3189 | //get all the statuses |
| 3190 | $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
| 3191 | if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus) |
| 3192 | || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus)) |
| 3193 | && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus) |
| 3194 | && $context == 'changePaymentInstrument' |
| 3195 | ) { |
| 3196 | return; |
| 3197 | } |
| 3198 | if (($params['prevContribution']->contribution_status_id == array_search('Partially paid', $contributionStatus)) |
| 3199 | && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus) |
| 3200 | && $context == 'changedStatus' |
| 3201 | ) { |
| 3202 | return; |
| 3203 | } |
| 3204 | if ($context == 'changedAmount' || $context == 'changeFinancialType') { |
| 3205 | $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount; |
| 3206 | } |
| 3207 | if ($context == 'changedStatus') { |
| 3208 | //get all the statuses |
| 3209 | $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
| 3210 | |
| 3211 | if ($params['prevContribution']->contribution_status_id == array_search('Completed', $contributionStatus) |
| 3212 | && ($params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus) |
| 3213 | || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) |
| 3214 | ) { |
| 3215 | $params['trxnParams']['total_amount'] = -$params['total_amount']; |
| 3216 | } |
| 3217 | elseif (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus) |
| 3218 | && $params['prevContribution']->is_pay_later) || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus) |
| 3219 | ) { |
| 3220 | $financialTypeID = CRM_Utils_Array::value('financial_type_id', $params) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id; |
| 3221 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); |
| 3222 | $arAccountId = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeID, $relationTypeId); |
| 3223 | |
| 3224 | if ($params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) { |
| 3225 | $params['trxnParams']['to_financial_account_id'] = $arAccountId; |
| 3226 | $params['trxnParams']['total_amount'] = -$params['total_amount']; |
| 3227 | } |
| 3228 | else { |
| 3229 | $params['trxnParams']['from_financial_account_id'] = $arAccountId; |
| 3230 | } |
| 3231 | } |
| 3232 | $itemAmount = $params['trxnParams']['total_amount']; |
| 3233 | } |
| 3234 | elseif ($context == 'changePaymentInstrument') { |
| 3235 | if ($params['trxnParams']['total_amount'] < 0) { |
| 3236 | $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC'); |
| 3237 | if (!empty($lastFinancialTrxnId['financialTrxnId'])) { |
| 3238 | $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id'); |
| 3239 | $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id; |
| 3240 | } |
| 3241 | } |
| 3242 | else { |
| 3243 | $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id']; |
| 3244 | $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id; |
| 3245 | } |
| 3246 | } |
| 3247 | $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']); |
| 3248 | $params['entity_id'] = $trxn->id; |
| 3249 | |
| 3250 | if ($context == 'changedStatus') { |
| 3251 | if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus) |
| 3252 | || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus)) |
| 3253 | && ($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus)) |
| 3254 | ) { |
| 3255 | $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'"; |
| 3256 | $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'"; |
| 3257 | |
| 3258 | $entityParams = array( |
| 3259 | 'entity_table' => 'civicrm_financial_item', |
| 3260 | 'financial_trxn_id' => $trxn->id, |
| 3261 | ); |
| 3262 | if (empty($params['line_item'])) { |
| 3263 | //CRM-15296 |
| 3264 | //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items |
| 3265 | // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed |
| 3266 | // & this can be removed |
| 3267 | return; |
| 3268 | } |
| 3269 | foreach ($params['line_item'] as $fieldId => $fields) { |
| 3270 | foreach ($fields as $fieldValueId => $fieldValues) { |
| 3271 | $fparams = array( |
| 3272 | 1 => array(CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'), 'Integer'), |
| 3273 | 2 => array($fieldValues['id'], 'Integer'), |
| 3274 | ); |
| 3275 | CRM_Core_DAO::executeQuery($query, $fparams); |
| 3276 | $fparams = array( |
| 3277 | 1 => array($fieldValues['id'], 'Integer'), |
| 3278 | ); |
| 3279 | $financialItem = CRM_Core_DAO::executeQuery($sql, $fparams); |
| 3280 | while ($financialItem->fetch()) { |
| 3281 | $entityParams['entity_id'] = $financialItem->id; |
| 3282 | $entityParams['amount'] = $financialItem->amount; |
| 3283 | CRM_Financial_BAO_FinancialItem::createEntityTrxn($entityParams); |
| 3284 | } |
| 3285 | } |
| 3286 | } |
| 3287 | return; |
| 3288 | } |
| 3289 | } |
| 3290 | if ($context != 'changePaymentInstrument') { |
| 3291 | $itemParams['entity_table'] = 'civicrm_line_item'; |
| 3292 | $trxnIds['id'] = $params['entity_id']; |
| 3293 | foreach ($params['line_item'] as $fieldId => $fields) { |
| 3294 | foreach ($fields as $fieldValueId => $fieldValues) { |
| 3295 | $prevParams['entity_id'] = $fieldValues['id']; |
| 3296 | $prevfinancialItem = CRM_Financial_BAO_FinancialItem::retrieve($prevParams, CRM_Core_DAO::$_nullArray); |
| 3297 | |
| 3298 | $receiveDate = CRM_Utils_Date::isoToMysql($params['prevContribution']->receive_date); |
| 3299 | if ($params['contribution']->receive_date) { |
| 3300 | $receiveDate = CRM_Utils_Date::isoToMysql($params['contribution']->receive_date); |
| 3301 | } |
| 3302 | |
| 3303 | $financialAccount = $prevfinancialItem->financial_account_id; |
| 3304 | if (!empty($params['financial_account_id'])) { |
| 3305 | $financialAccount = $params['financial_account_id']; |
| 3306 | } |
| 3307 | |
| 3308 | $currency = $params['prevContribution']->currency; |
| 3309 | if ($params['contribution']->currency) { |
| 3310 | $currency = $params['contribution']->currency; |
| 3311 | } |
| 3312 | $diff = 1; |
| 3313 | if (!empty($params['is_quick_config'])) { |
| 3314 | $amount = $itemAmount; |
| 3315 | if (!$amount) { |
| 3316 | $amount = $params['total_amount']; |
| 3317 | } |
| 3318 | } |
| 3319 | else { |
| 3320 | if ($context == 'changeFinancialType' || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus) |
| 3321 | || $params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus) |
| 3322 | ) { |
| 3323 | $diff = -1; |
| 3324 | } |
| 3325 | $amount = $diff * $fieldValues['line_total']; |
| 3326 | } |
| 3327 | |
| 3328 | $itemParams = array( |
| 3329 | 'transaction_date' => $receiveDate, |
| 3330 | 'contact_id' => $params['prevContribution']->contact_id, |
| 3331 | 'currency' => $currency, |
| 3332 | 'amount' => $amount, |
| 3333 | 'description' => $prevfinancialItem->description, |
| 3334 | 'status_id' => $prevfinancialItem->status_id, |
| 3335 | 'financial_account_id' => $financialAccount, |
| 3336 | 'entity_table' => 'civicrm_line_item', |
| 3337 | 'entity_id' => $fieldValues['id'], |
| 3338 | ); |
| 3339 | CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds); |
| 3340 | |
| 3341 | if ($fieldValues['tax_amount']) { |
| 3342 | $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); |
| 3343 | $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings); |
| 3344 | $itemParams['amount'] = $diff * $fieldValues['tax_amount']; |
| 3345 | $itemParams['description'] = $taxTerm; |
| 3346 | if ($fieldValues['financial_type_id']) { |
| 3347 | $itemParams['financial_account_id'] = self::getFinancialAccountId($fieldValues['financial_type_id']); |
| 3348 | } |
| 3349 | CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds); |
| 3350 | } |
| 3351 | } |
| 3352 | } |
| 3353 | } |
| 3354 | if ($context == 'changeFinancialType') { |
| 3355 | $params['skipLineItem'] = FALSE; |
| 3356 | foreach ($params['line_item'] as &$lineItems) { |
| 3357 | foreach ($lineItems as &$line) { |
| 3358 | $line['financial_type_id'] = $params['financial_type_id']; |
| 3359 | } |
| 3360 | } |
| 3361 | } |
| 3362 | } |
| 3363 | |
| 3364 | /** |
| 3365 | * Check status validation on update of a contribution. |
| 3366 | * |
| 3367 | * @param array $values |
| 3368 | * Previous form values before submit. |
| 3369 | * |
| 3370 | * @param array $fields |
| 3371 | * The input form values. |
| 3372 | * |
| 3373 | * @param array $errors |
| 3374 | * List of errors. |
| 3375 | * |
| 3376 | * @return bool |
| 3377 | */ |
| 3378 | public static function checkStatusValidation($values, &$fields, &$errors) { |
| 3379 | if (CRM_Utils_System::isNull($values) && !empty($fields['id'])) { |
| 3380 | $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id'); |
| 3381 | if ($values['contribution_status_id'] == $fields['contribution_status_id']) { |
| 3382 | return FALSE; |
| 3383 | } |
| 3384 | } |
| 3385 | $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
| 3386 | $checkStatus = array( |
| 3387 | 'Cancelled' => array('Completed', 'Refunded'), |
| 3388 | 'Completed' => array('Cancelled', 'Refunded'), |
| 3389 | 'Pending' => array('Cancelled', 'Completed', 'Failed'), |
| 3390 | 'In Progress' => array('Cancelled', 'Completed', 'Failed'), |
| 3391 | 'Refunded' => array('Cancelled', 'Completed'), |
| 3392 | 'Partially paid' => array('Completed'), |
| 3393 | ); |
| 3394 | |
| 3395 | if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) { |
| 3396 | $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array( |
| 3397 | 1 => $contributionStatuses[$values['contribution_status_id']], |
| 3398 | 2 => $contributionStatuses[$fields['contribution_status_id']], |
| 3399 | )); |
| 3400 | } |
| 3401 | } |
| 3402 | |
| 3403 | /** |
| 3404 | * Delete contribution of contact. |
| 3405 | * |
| 3406 | * CRM-12155 |
| 3407 | * |
| 3408 | * @param int $contactId |
| 3409 | * Contact id. |
| 3410 | * |
| 3411 | */ |
| 3412 | public static function deleteContactContribution($contactId) { |
| 3413 | $contribution = new CRM_Contribute_DAO_Contribution(); |
| 3414 | $contribution->contact_id = $contactId; |
| 3415 | $contribution->find(); |
| 3416 | while ($contribution->fetch()) { |
| 3417 | self::deleteContribution($contribution->id); |
| 3418 | } |
| 3419 | } |
| 3420 | |
| 3421 | /** |
| 3422 | * Get options for a given contribution field. |
| 3423 | * @see CRM_Core_DAO::buildOptions |
| 3424 | * |
| 3425 | * @param string $fieldName |
| 3426 | * @param string $context see CRM_Core_DAO::buildOptionsContext. |
| 3427 | * @param array $props whatever is known about this dao object. |
| 3428 | * |
| 3429 | * @return array|bool |
| 3430 | */ |
| 3431 | public static function buildOptions($fieldName, $context = NULL, $props = array()) { |
| 3432 | $className = __CLASS__; |
| 3433 | $params = array(); |
| 3434 | switch ($fieldName) { |
| 3435 | // This field is not part of this object but the api supports it |
| 3436 | case 'payment_processor': |
| 3437 | $className = 'CRM_Contribute_BAO_ContributionPage'; |
| 3438 | // Filter results by contribution page |
| 3439 | if (!empty($props['contribution_page_id'])) { |
| 3440 | $page = civicrm_api('contribution_page', 'getsingle', array( |
| 3441 | 'version' => 3, |
| 3442 | 'id' => ($props['contribution_page_id']), |
| 3443 | )); |
| 3444 | $types = (array) CRM_Utils_Array::value('payment_processor', $page, 0); |
| 3445 | $params['condition'] = 'id IN (' . implode(',', $types) . ')'; |
| 3446 | } |
| 3447 | break; |
| 3448 | |
| 3449 | // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it |
| 3450 | case 'honor_type_id': |
| 3451 | $className = 'CRM_Contribute_BAO_ContributionSoft'; |
| 3452 | $fieldName = 'soft_credit_type_id'; |
| 3453 | $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')"; |
| 3454 | break; |
| 3455 | } |
| 3456 | return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context); |
| 3457 | } |
| 3458 | |
| 3459 | /** |
| 3460 | * Validate financial type. |
| 3461 | * |
| 3462 | * CRM-13231 |
| 3463 | * |
| 3464 | * @param int $financialTypeId |
| 3465 | * Financial Type id. |
| 3466 | * |
| 3467 | * @param string $relationName |
| 3468 | * |
| 3469 | * @return array|bool |
| 3470 | */ |
| 3471 | public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') { |
| 3472 | $expenseTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' ")); |
| 3473 | $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $expenseTypeId); |
| 3474 | |
| 3475 | if (!$financialAccount) { |
| 3476 | return CRM_Contribute_PseudoConstant::financialType($financialTypeId); |
| 3477 | } |
| 3478 | return FALSE; |
| 3479 | } |
| 3480 | |
| 3481 | |
| 3482 | /** |
| 3483 | * Function to record additional payment for partial and refund contributions. |
| 3484 | * |
| 3485 | * @param int $contributionId |
| 3486 | * is the invoice contribution id (got created after processing participant payment). |
| 3487 | * @param array $trxnsData |
| 3488 | * to take user provided input of transaction details. |
| 3489 | * @param string $paymentType |
| 3490 | * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments. |
| 3491 | * @param int $participantId |
| 3492 | * |
| 3493 | * @return null|object |
| 3494 | */ |
| 3495 | public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) { |
| 3496 | $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'); |
| 3497 | $getInfoOf['id'] = $contributionId; |
| 3498 | $defaults = array(); |
| 3499 | $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray); |
| 3500 | |
| 3501 | if ($paymentType == 'owed') { |
| 3502 | // build params for recording financial trxn entry |
| 3503 | $params['contribution'] = $contributionDAO; |
| 3504 | $params = array_merge($defaults, $params); |
| 3505 | $params['skipLineItem'] = TRUE; |
| 3506 | $params['partial_payment_total'] = $contributionDAO->total_amount; |
| 3507 | $params['partial_amount_pay'] = $trxnsData['total_amount']; |
| 3508 | $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis'); |
| 3509 | $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ? $trxnsData['net_amount'] : $trxnsData['total_amount']; |
| 3510 | |
| 3511 | // record the entry |
| 3512 | $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData); |
| 3513 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); |
| 3514 | $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId); |
| 3515 | |
| 3516 | $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id); |
| 3517 | if (!empty($trxnId)) { |
| 3518 | $trxnId = $trxnId['trxn_id']; |
| 3519 | } |
| 3520 | elseif (!empty($contributionDAO->payment_instrument_id)) { |
| 3521 | $trxnId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id); |
| 3522 | } |
| 3523 | else { |
| 3524 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' ")); |
| 3525 | $queryParams = array(1 => array($relationTypeId, 'Integer')); |
| 3526 | $trxnId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams); |
| 3527 | } |
| 3528 | |
| 3529 | // update statuses |
| 3530 | // criteria for updates contribution total_amount == financial_trxns of partial_payments |
| 3531 | $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total |
| 3532 | FROM civicrm_financial_trxn ft |
| 3533 | LEFT JOIN civicrm_entity_financial_trxn eft |
| 3534 | ON (ft.id = eft.financial_trxn_id) |
| 3535 | WHERE eft.entity_table = 'civicrm_contribution' |
| 3536 | AND eft.entity_id = {$contributionId} |
| 3537 | AND ft.to_financial_account_id != {$toFinancialAccount} |
| 3538 | AND ft.status_id = {$statusId} |
| 3539 | "; |
| 3540 | $query = CRM_Core_DAO::executeQuery($sql); |
| 3541 | $query->fetch(); |
| 3542 | $sumOfPayments = $query->sum_of_payments; |
| 3543 | |
| 3544 | // update statuses |
| 3545 | if ($contributionDAO->total_amount == $sumOfPayments) { |
| 3546 | // update contribution status and |
| 3547 | // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed' |
| 3548 | $contributionDAO->contribution_status_id = $statusId; |
| 3549 | $contributionDAO->cancel_date = 'null'; |
| 3550 | $contributionDAO->cancel_reason = NULL; |
| 3551 | $netAmount = !empty($trxnsData['net_amount']) ? NULL : $trxnsData['total_amount']; |
| 3552 | $contributionDAO->net_amount = $query->net_amount_total + $netAmount; |
| 3553 | $contributionDAO->fee_amount = $contributionDAO->total_amount - $contributionDAO->net_amount; |
| 3554 | $contributionDAO->save(); |
| 3555 | |
| 3556 | //Change status of financial record too |
| 3557 | $financialTrxn->status_id = $statusId; |
| 3558 | $financialTrxn->save(); |
| 3559 | |
| 3560 | // note : not using the self::add method, |
| 3561 | // the reason because it performs 'status change' related code execution for financial records |
| 3562 | // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates |
| 3563 | // are coded below i.e. just updating financial_item status to 'Paid' |
| 3564 | |
| 3565 | if ($participantId) { |
| 3566 | // update participant status |
| 3567 | $participantStatuses = CRM_Event_PseudoConstant::participantStatus(); |
| 3568 | $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId); |
| 3569 | foreach ($ids as $val) { |
| 3570 | $participantUpdate['id'] = $val; |
| 3571 | $participantUpdate['status_id'] = array_search('Registered', $participantStatuses); |
| 3572 | CRM_Event_BAO_Participant::add($participantUpdate); |
| 3573 | } |
| 3574 | } |
| 3575 | |
| 3576 | // update financial item statuses |
| 3577 | $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id'); |
| 3578 | $paidStatus = array_search('Paid', $financialItemStatus); |
| 3579 | |
| 3580 | $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId); |
| 3581 | $sqlFinancialItemUpdate = " |
| 3582 | UPDATE civicrm_financial_item fi |
| 3583 | LEFT JOIN civicrm_entity_financial_trxn eft |
| 3584 | ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item') |
| 3585 | SET status_id = {$paidStatus} |
| 3586 | WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']}) |
| 3587 | "; |
| 3588 | CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate); |
| 3589 | } |
| 3590 | } |
| 3591 | elseif ($paymentType == 'refund') { |
| 3592 | // build params for recording financial trxn entry |
| 3593 | $params['contribution'] = $contributionDAO; |
| 3594 | $params = array_merge($defaults, $params); |
| 3595 | $params['skipLineItem'] = TRUE; |
| 3596 | $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis'); |
| 3597 | $trxnsData['total_amount'] = -$trxnsData['total_amount']; |
| 3598 | |
| 3599 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); |
| 3600 | $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId); |
| 3601 | $trxnsData['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name'); |
| 3602 | // record the entry |
| 3603 | $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData); |
| 3604 | |
| 3605 | // note : not using the self::add method, |
| 3606 | // the reason because it performs 'status change' related code execution for financial records |
| 3607 | // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates |
| 3608 | // are coded below i.e. just updating financial_item status to 'Paid' |
| 3609 | $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId); |
| 3610 | |
| 3611 | // add financial item entry |
| 3612 | $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id'); |
| 3613 | $getLine['entity_id'] = $contributionDAO->id; |
| 3614 | $getLine['entity_table'] = 'civicrm_contribution'; |
| 3615 | $lineItemId = CRM_Price_BAO_LineItem::retrieve($getLine, CRM_Core_DAO::$_nullArray); |
| 3616 | if (!empty($lineItemId->id)) { |
| 3617 | $addFinancialEntry = array( |
| 3618 | 'transaction_date' => $financialTrxn->trxn_date, |
| 3619 | 'contact_id' => $contributionDAO->contact_id, |
| 3620 | 'amount' => $financialTrxn->total_amount, |
| 3621 | 'status_id' => array_search('Paid', $financialItemStatus), |
| 3622 | 'entity_id' => $lineItemId->id, |
| 3623 | 'entity_table' => 'civicrm_line_item', |
| 3624 | ); |
| 3625 | $trxnIds['id'] = $financialTrxn->id; |
| 3626 | CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds); |
| 3627 | } |
| 3628 | if ($participantId) { |
| 3629 | // update participant status |
| 3630 | $participantStatuses = CRM_Event_PseudoConstant::participantStatus(); |
| 3631 | $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId); |
| 3632 | foreach ($ids as $val) { |
| 3633 | $participantUpdate['id'] = $val; |
| 3634 | $participantUpdate['status_id'] = array_search('Registered', $participantStatuses); |
| 3635 | CRM_Event_BAO_Participant::add($participantUpdate); |
| 3636 | } |
| 3637 | } |
| 3638 | } |
| 3639 | |
| 3640 | // activity creation |
| 3641 | if (!empty($financialTrxn)) { |
| 3642 | if ($participantId) { |
| 3643 | $inputParams['id'] = $participantId; |
| 3644 | $values = array(); |
| 3645 | $ids = array(); |
| 3646 | $component = 'event'; |
| 3647 | $entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids); |
| 3648 | $entityObj = $entityObj[$participantId]; |
| 3649 | } |
| 3650 | $activityType = ($paymentType == 'refund') ? 'Refund' : 'Payment'; |
| 3651 | |
| 3652 | self::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId); |
| 3653 | } |
| 3654 | return $financialTrxn; |
| 3655 | } |
| 3656 | |
| 3657 | /** |
| 3658 | * @param $entityObj |
| 3659 | * @param $trxnObj |
| 3660 | * @param $activityType |
| 3661 | * @param $component |
| 3662 | * @param int $contributionId |
| 3663 | * |
| 3664 | * @throws CRM_Core_Exception |
| 3665 | */ |
| 3666 | public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) { |
| 3667 | if ($component == 'event') { |
| 3668 | $date = CRM_Utils_Date::isoToMysql($trxnObj->trxn_date); |
| 3669 | $paymentAmount = CRM_Utils_Money::format($trxnObj->total_amount, $trxnObj->currency); |
| 3670 | $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id, 'title'); |
| 3671 | $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}"; |
| 3672 | $targetCid = $entityObj->contact_id; |
| 3673 | // source record id would be the contribution id |
| 3674 | $srcRecId = $contributionId; |
| 3675 | } |
| 3676 | |
| 3677 | // activity params |
| 3678 | $activityParams = array( |
| 3679 | 'source_contact_id' => $targetCid, |
| 3680 | 'source_record_id' => $srcRecId, |
| 3681 | 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', |
| 3682 | $activityType, |
| 3683 | 'name' |
| 3684 | ), |
| 3685 | 'subject' => $subject, |
| 3686 | 'activity_date_time' => $date, |
| 3687 | 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', |
| 3688 | 'Completed', |
| 3689 | 'name' |
| 3690 | ), |
| 3691 | 'skipRecentView' => TRUE, |
| 3692 | ); |
| 3693 | |
| 3694 | // create activity with target contacts |
| 3695 | $session = CRM_Core_Session::singleton(); |
| 3696 | $id = $session->get('userID'); |
| 3697 | if ($id) { |
| 3698 | $activityParams['source_contact_id'] = $id; |
| 3699 | $activityParams['target_contact_id'][] = $targetCid; |
| 3700 | } |
| 3701 | CRM_Activity_BAO_Activity::create($activityParams); |
| 3702 | } |
| 3703 | |
| 3704 | /** |
| 3705 | * Get list of payments displayed by Contribute_Page_PaymentInfo. |
| 3706 | * |
| 3707 | * @param int $id |
| 3708 | * @param $component |
| 3709 | * @param bool $getTrxnInfo |
| 3710 | * @param bool $usingLineTotal |
| 3711 | * |
| 3712 | * @return mixed |
| 3713 | */ |
| 3714 | public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) { |
| 3715 | if ($component == 'event') { |
| 3716 | $entity = 'participant'; |
| 3717 | $entityTable = 'civicrm_participant'; |
| 3718 | $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id'); |
| 3719 | |
| 3720 | if (!$contributionId) { |
| 3721 | if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) { |
| 3722 | $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id'); |
| 3723 | $id = $primaryParticipantId; |
| 3724 | } |
| 3725 | if (!$contributionId) { |
| 3726 | return; |
| 3727 | } |
| 3728 | } |
| 3729 | } |
| 3730 | $total = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId); |
| 3731 | $baseTrxnId = !empty($total['trxn_id']) ? $total['trxn_id'] : NULL; |
| 3732 | $isBalance = NULL; |
| 3733 | if ($baseTrxnId) { |
| 3734 | $isBalance = TRUE; |
| 3735 | } |
| 3736 | else { |
| 3737 | $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId); |
| 3738 | $baseTrxnId = $baseTrxnId['financialTrxnId']; |
| 3739 | $isBalance = FALSE; |
| 3740 | } |
| 3741 | if (!CRM_Utils_Array::value('total_amount', $total) || $usingLineTotal) { |
| 3742 | // for additional participants |
| 3743 | if ($entityTable == 'civicrm_participant') { |
| 3744 | $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId); |
| 3745 | $total = 0; |
| 3746 | foreach ($ids as $val) { |
| 3747 | $total += CRM_Price_BAO_LineItem::getLineTotal($val, $entityTable); |
| 3748 | } |
| 3749 | } |
| 3750 | else { |
| 3751 | $total = CRM_Price_BAO_LineItem::getLineTotal($id, $entityTable); |
| 3752 | } |
| 3753 | } |
| 3754 | else { |
| 3755 | $baseTrxnId = $total['trxn_id']; |
| 3756 | $total = $total['total_amount']; |
| 3757 | } |
| 3758 | |
| 3759 | $paymentBalance = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($id, $entity, FALSE, $total); |
| 3760 | $contributionIsPayLater = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later'); |
| 3761 | |
| 3762 | $feeRelationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' ")); |
| 3763 | $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id'); |
| 3764 | $feeFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $feeRelationTypeId); |
| 3765 | |
| 3766 | if ($paymentBalance == 0 && $contributionIsPayLater) { |
| 3767 | $paymentBalance = $total; |
| 3768 | } |
| 3769 | |
| 3770 | $info['total'] = $total; |
| 3771 | $info['paid'] = $total - $paymentBalance; |
| 3772 | $info['balance'] = $paymentBalance; |
| 3773 | $info['id'] = $id; |
| 3774 | $info['component'] = $component; |
| 3775 | $info['payLater'] = $contributionIsPayLater; |
| 3776 | $rows = array(); |
| 3777 | if ($getTrxnInfo && $baseTrxnId) { |
| 3778 | // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account |
| 3779 | $sql = " |
| 3780 | SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number |
| 3781 | FROM civicrm_contribution con |
| 3782 | LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution') |
| 3783 | INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount} |
| 3784 | WHERE con.id = {$contributionId} |
| 3785 | "; |
| 3786 | |
| 3787 | // conditioned WHERE clause |
| 3788 | if ($isBalance) { |
| 3789 | // if balance trxn exists don't include details of it in transaction info |
| 3790 | $sql .= " AND ft.id != {$baseTrxnId} "; |
| 3791 | } |
| 3792 | $resultDAO = CRM_Core_DAO::executeQuery($sql); |
| 3793 | |
| 3794 | $statuses = CRM_Contribute_PseudoConstant::contributionStatus(); |
| 3795 | $financialTypes = CRM_Contribute_PseudoConstant::financialType(); |
| 3796 | while ($resultDAO->fetch()) { |
| 3797 | $paidByLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id); |
| 3798 | $paidByName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id); |
| 3799 | $val = array( |
| 3800 | 'total_amount' => $resultDAO->total_amount, |
| 3801 | 'financial_type' => $financialTypes[$resultDAO->financial_type_id], |
| 3802 | 'payment_instrument' => $paidByLabel, |
| 3803 | 'receive_date' => $resultDAO->trxn_date, |
| 3804 | 'trxn_id' => $resultDAO->trxn_id, |
| 3805 | 'status' => $statuses[$resultDAO->status_id], |
| 3806 | ); |
| 3807 | if ($paidByName == 'Check') { |
| 3808 | $val['check_number'] = $resultDAO->check_number; |
| 3809 | } |
| 3810 | $rows[] = $val; |
| 3811 | } |
| 3812 | $info['transaction'] = $rows; |
| 3813 | } |
| 3814 | return $info; |
| 3815 | } |
| 3816 | |
| 3817 | /** |
| 3818 | * Get financial account id has 'Sales Tax Account is' |
| 3819 | * account relationship with financial type |
| 3820 | * |
| 3821 | * @param int $financialTypeId |
| 3822 | * |
| 3823 | * @return FinancialAccountId |
| 3824 | */ |
| 3825 | public static function getFinancialAccountId($financialTypeId) { |
| 3826 | $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")); |
| 3827 | $searchParams = array( |
| 3828 | 'entity_table' => 'civicrm_financial_type', |
| 3829 | 'entity_id' => $financialTypeId, |
| 3830 | 'account_relationship' => $accountRel, |
| 3831 | ); |
| 3832 | $result = array(); |
| 3833 | CRM_Financial_BAO_FinancialTypeAccount::retrieve($searchParams, $result); |
| 3834 | |
| 3835 | return CRM_Utils_Array::value('financial_account_id', $result); |
| 3836 | } |
| 3837 | |
| 3838 | /** |
| 3839 | * Check tax amount. |
| 3840 | * |
| 3841 | * @param array $params |
| 3842 | * @param bool $isLineItem |
| 3843 | * |
| 3844 | * @return mixed |
| 3845 | */ |
| 3846 | public static function checkTaxAmount($params, $isLineItem = FALSE) { |
| 3847 | $taxRates = CRM_Core_PseudoConstant::getTaxRates(); |
| 3848 | |
| 3849 | // Update contribution. |
| 3850 | if (!empty($params['id'])) { |
| 3851 | $id = $params['id']; |
| 3852 | $values = $ids = array(); |
| 3853 | $contrbutionParams = array('id' => $id); |
| 3854 | $prevContributionValue = CRM_Contribute_BAO_Contribution::getValues($contrbutionParams, $values, $ids); |
| 3855 | |
| 3856 | // To assign pervious finantial type on update of contribution |
| 3857 | if (!isset($params['financial_type_id'])) { |
| 3858 | $params['financial_type_id'] = $prevContributionValue->financial_type_id; |
| 3859 | } |
| 3860 | elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) { |
| 3861 | // Assisn tax Amount on update of contrbution |
| 3862 | if (!empty($prevContributionValue->tax_amount)) { |
| 3863 | $params['tax_amount'] = 'null'; |
| 3864 | CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id'])); |
| 3865 | foreach ($params['line_item'] as $setID => $priceField) { |
| 3866 | foreach ($priceField as $priceFieldID => $priceFieldValue) { |
| 3867 | $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount']; |
| 3868 | } |
| 3869 | } |
| 3870 | } |
| 3871 | } |
| 3872 | } |
| 3873 | |
| 3874 | // New Contrbution and update of contribution with tax rate financial type |
| 3875 | if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && |
| 3876 | empty($params['skipLineItem']) && !$isLineItem |
| 3877 | ) { |
| 3878 | $taxRateParams = $taxRates[$params['financial_type_id']]; |
| 3879 | $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['total_amount'], $taxRateParams); |
| 3880 | $params['tax_amount'] = round($taxAmount['tax_amount'], 2); |
| 3881 | |
| 3882 | // Get Line Item on update of contribution |
| 3883 | if (isset($params['id'])) { |
| 3884 | CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id'])); |
| 3885 | } |
| 3886 | else { |
| 3887 | CRM_Price_BAO_LineItem::getLineItemArray($params); |
| 3888 | } |
| 3889 | foreach ($params['line_item'] as $setID => $priceField) { |
| 3890 | foreach ($priceField as $priceFieldID => $priceFieldValue) { |
| 3891 | $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount']; |
| 3892 | } |
| 3893 | } |
| 3894 | $params['total_amount'] = $params['total_amount'] + $params['tax_amount']; |
| 3895 | } |
| 3896 | elseif (isset($params['api.line_item.create'])) { |
| 3897 | // Update total amount of contribution using lineItem |
| 3898 | $taxAmountArray = array(); |
| 3899 | foreach ($params['api.line_item.create'] as $key => $value) { |
| 3900 | if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) { |
| 3901 | $taxRate = $taxRates[$value['financial_type_id']]; |
| 3902 | $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($value['line_total'], $taxRate); |
| 3903 | $taxAmountArray[] = round($taxAmount['tax_amount'], 2); |
| 3904 | } |
| 3905 | } |
| 3906 | $params['tax_amount'] = array_sum($taxAmountArray); |
| 3907 | $params['total_amount'] = $params['total_amount'] + $params['tax_amount']; |
| 3908 | } |
| 3909 | else { |
| 3910 | // update line item of contrbution |
| 3911 | if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) { |
| 3912 | $taxRate = $taxRates[$params['financial_type_id']]; |
| 3913 | $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['line_total'], $taxRate); |
| 3914 | $params['tax_amount'] = round($taxAmount['tax_amount'], 2); |
| 3915 | } |
| 3916 | } |
| 3917 | return $params; |
| 3918 | } |
| 3919 | |
| 3920 | /** |
| 3921 | * Check financial type validation on update of a contribution. |
| 3922 | * |
| 3923 | * @param Integer $financialTypeId |
| 3924 | * Value of latest Financial Type. |
| 3925 | * |
| 3926 | * @param Integer $contributionId |
| 3927 | * Contribution Id. |
| 3928 | * |
| 3929 | * @param array $errors |
| 3930 | * List of errors. |
| 3931 | * |
| 3932 | * @return bool |
| 3933 | */ |
| 3934 | public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) { |
| 3935 | if (!empty($financialTypeId)) { |
| 3936 | $oldFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id'); |
| 3937 | if ($oldFinancialTypeId == $financialTypeId) { |
| 3938 | return FALSE; |
| 3939 | } |
| 3940 | } |
| 3941 | $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;'; |
| 3942 | $params = array( |
| 3943 | '1' => array($contributionId, 'Integer'), |
| 3944 | ); |
| 3945 | $result = CRM_Core_DAO::executeQuery($sql, $params); |
| 3946 | if ($result->N > 1) { |
| 3947 | $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.'); |
| 3948 | } |
| 3949 | } |
| 3950 | |
| 3951 | /** |
| 3952 | * Update related pledge payment payments. |
| 3953 | * |
| 3954 | * This function has been refactored out of the back office contribution form and may |
| 3955 | * still overlap with other functions. |
| 3956 | * |
| 3957 | * @param string $action |
| 3958 | * @param int $pledgePaymentID |
| 3959 | * @param int $contributionID |
| 3960 | * @param bool $adjustTotalAmount |
| 3961 | * @param float $total_amount |
| 3962 | * @param float $original_total_amount |
| 3963 | * @param int $contribution_status_id |
| 3964 | * @param int $original_contribution_status_id |
| 3965 | */ |
| 3966 | public static function updateRelatedPledge( |
| 3967 | $action, |
| 3968 | $pledgePaymentID, |
| 3969 | $contributionID, |
| 3970 | $adjustTotalAmount, |
| 3971 | $total_amount, |
| 3972 | $original_total_amount, |
| 3973 | $contribution_status_id, |
| 3974 | $original_contribution_status_id |
| 3975 | ) { |
| 3976 | if (!$pledgePaymentID || $action & CRM_Core_Action::ADD && !$contributionID) { |
| 3977 | return; |
| 3978 | } |
| 3979 | |
| 3980 | if ($pledgePaymentID) { |
| 3981 | //store contribution id in payment record. |
| 3982 | CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID); |
| 3983 | } |
| 3984 | else { |
| 3985 | $pledgePaymentID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', |
| 3986 | $contributionID, |
| 3987 | 'id', |
| 3988 | 'contribution_id' |
| 3989 | ); |
| 3990 | } |
| 3991 | $pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', |
| 3992 | $contributionID, |
| 3993 | 'pledge_id', |
| 3994 | 'contribution_id' |
| 3995 | ); |
| 3996 | |
| 3997 | $updatePledgePaymentStatus = FALSE; |
| 3998 | |
| 3999 | // If either the status or the amount has changed we update the pledge status. |
| 4000 | if ($action & CRM_Core_Action::ADD) { |
| 4001 | $updatePledgePaymentStatus = TRUE; |
| 4002 | } |
| 4003 | elseif ($action & CRM_Core_Action::UPDATE && (($original_contribution_status_id != $contribution_status_id) || |
| 4004 | ($original_total_amount != $total_amount)) |
| 4005 | ) { |
| 4006 | $updatePledgePaymentStatus = TRUE; |
| 4007 | } |
| 4008 | |
| 4009 | if ($updatePledgePaymentStatus) { |
| 4010 | CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, |
| 4011 | array($pledgePaymentID), |
| 4012 | $contribution_status_id, |
| 4013 | NULL, |
| 4014 | $total_amount, |
| 4015 | $adjustTotalAmount |
| 4016 | ); |
| 4017 | } |
| 4018 | } |
| 4019 | |
| 4020 | /** |
| 4021 | * Compute the stats values |
| 4022 | * |
| 4023 | * @param $stat either 'mode' or 'median' |
| 4024 | * @param $sql |
| 4025 | * @param $alias of civicrm_contribution |
| 4026 | */ |
| 4027 | public static function computeStats($stat, $sql, $alias = NULL) { |
| 4028 | $mode = $median = array(); |
| 4029 | switch ($stat) { |
| 4030 | case 'mode': |
| 4031 | $modeDAO = CRM_Core_DAO::executeQuery($sql); |
| 4032 | while ($modeDAO->fetch()) { |
| 4033 | if ($modeDAO->civicrm_contribution_total_amount_count > 1) { |
| 4034 | $mode[] = CRM_Utils_Money::format($modeDAO->amount, $modeDAO->currency); |
| 4035 | } |
| 4036 | else { |
| 4037 | $mode[] = 'N/A'; |
| 4038 | } |
| 4039 | } |
| 4040 | return $mode; |
| 4041 | |
| 4042 | case 'median': |
| 4043 | $currencies = CRM_Core_OptionGroup::values('currencies_enabled'); |
| 4044 | foreach ($currencies as $currency => $val) { |
| 4045 | $midValue = 0; |
| 4046 | $where = "AND {$alias}.currency = '{$currency}'"; |
| 4047 | $rowCount = CRM_Core_DAO::singleValueQuery("SELECT count(*) as count {$sql} {$where}"); |
| 4048 | |
| 4049 | $even = FALSE; |
| 4050 | $offset = 1; |
| 4051 | $medianRow = floor($rowCount / 2); |
| 4052 | if ($rowCount % 2 == 0 && !empty($medianRow)) { |
| 4053 | $even = TRUE; |
| 4054 | $offset++; |
| 4055 | $medianRow--; |
| 4056 | } |
| 4057 | |
| 4058 | $medianValue = "SELECT {$alias}.total_amount as median |
| 4059 | {$sql} {$where} |
| 4060 | ORDER BY median LIMIT {$medianRow},{$offset}"; |
| 4061 | $medianValDAO = CRM_Core_DAO::executeQuery($medianValue); |
| 4062 | while ($medianValDAO->fetch()) { |
| 4063 | if ($even) { |
| 4064 | $midValue = $midValue + $medianValDAO->median; |
| 4065 | } |
| 4066 | else { |
| 4067 | $median[] = CRM_Utils_Money::format($medianValDAO->median, $currency); |
| 4068 | } |
| 4069 | } |
| 4070 | if ($even) { |
| 4071 | $midValue = $midValue / 2; |
| 4072 | $median[] = CRM_Utils_Money::format($midValue, $currency); |
| 4073 | } |
| 4074 | } |
| 4075 | return $median; |
| 4076 | |
| 4077 | default: |
| 4078 | return; |
| 4079 | } |
| 4080 | } |
| 4081 | |
| 4082 | /** |
| 4083 | * Complete an order. |
| 4084 | * |
| 4085 | * Do not call this directly - use the contribution.completetransaction api as this function is being refactored. |
| 4086 | * |
| 4087 | * Currently overloaded to complete a transaction & repeat a transaction - fix! |
| 4088 | * |
| 4089 | * Moving it out of the BaseIPN class is just the first step. |
| 4090 | * |
| 4091 | * @param array $input |
| 4092 | * @param array $ids |
| 4093 | * @param array $objects |
| 4094 | * @param CRM_Core_Transaction $transaction |
| 4095 | * @param int $recur |
| 4096 | * @param CRM_Contribute_BAO_Contribution $contribution |
| 4097 | * @param bool $isRecurring |
| 4098 | * Duplication of param needs review. Only used by AuthorizeNetIPN |
| 4099 | * @param int $isFirstOrLastRecurringPayment |
| 4100 | * Deprecated param only used by AuthorizeNetIPN. |
| 4101 | */ |
| 4102 | public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) { |
| 4103 | $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id; |
| 4104 | // The previous details are used when calculating line items so keep it before any code that 'does something' |
| 4105 | if (!empty($contribution->id)) { |
| 4106 | $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contribution->id), |
| 4107 | CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray); |
| 4108 | } |
| 4109 | $inputContributionWhiteList = array( |
| 4110 | 'fee_amount', |
| 4111 | 'net_amount', |
| 4112 | 'trxn_id', |
| 4113 | 'check_number', |
| 4114 | 'payment_instrument_id', |
| 4115 | 'is_test', |
| 4116 | 'campaign_id', |
| 4117 | 'receive_date', |
| 4118 | ); |
| 4119 | |
| 4120 | $contributionParams = array_merge(array( |
| 4121 | 'contribution_status_id' => 'Completed', |
| 4122 | ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1) |
| 4123 | )); |
| 4124 | |
| 4125 | $participant = CRM_Utils_Array::value('participant', $objects); |
| 4126 | $memberships = CRM_Utils_Array::value('membership', $objects); |
| 4127 | $recurContrib = CRM_Utils_Array::value('contributionRecur', $objects); |
| 4128 | if (!empty($recurContrib->id)) { |
| 4129 | $contributionParams['contribution_recur_id'] = $recurContrib->id; |
| 4130 | } |
| 4131 | self::repeatTransaction($contribution, $input, $contributionParams); |
| 4132 | |
| 4133 | if (is_numeric($memberships)) { |
| 4134 | $memberships = array($objects['membership']); |
| 4135 | } |
| 4136 | |
| 4137 | $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis')); |
| 4138 | |
| 4139 | $values = array(); |
| 4140 | if (isset($input['is_email_receipt'])) { |
| 4141 | $values['is_email_receipt'] = $input['is_email_receipt']; |
| 4142 | } |
| 4143 | |
| 4144 | if ($input['component'] == 'contribute') { |
| 4145 | if ($contribution->contribution_page_id) { |
| 4146 | CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values); |
| 4147 | $contributionParams['source'] = ts('Online Contribution') . ': ' . $values['title']; |
| 4148 | } |
| 4149 | elseif ($recurContrib && $recurContrib->id) { |
| 4150 | $contributionParams['contribution_page_id'] = NULL; |
| 4151 | $values['amount'] = $recurContrib->amount; |
| 4152 | $values['financial_type_id'] = $objects['contributionType']->id; |
| 4153 | $values['title'] = $source = ts('Offline Recurring Contribution'); |
| 4154 | $domainValues = CRM_Core_BAO_Domain::getNameAndEmail(); |
| 4155 | $values['receipt_from_name'] = $domainValues[0]; |
| 4156 | $values['receipt_from_email'] = $domainValues[1]; |
| 4157 | } |
| 4158 | |
| 4159 | if (empty($contributionParams['receive_date']) && $changeDate) { |
| 4160 | $contributionParams['receive_date'] = $changeDate; |
| 4161 | } |
| 4162 | |
| 4163 | if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) { |
| 4164 | //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting |
| 4165 | // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden. |
| 4166 | $values['is_email_receipt'] = $recurContrib->is_email_receipt; |
| 4167 | } |
| 4168 | |
| 4169 | if (!empty($values['is_email_receipt'])) { |
| 4170 | $contributionParams['receipt_date'] = $changeDate; |
| 4171 | } |
| 4172 | |
| 4173 | if (!empty($memberships)) { |
| 4174 | foreach ($memberships as $membershipTypeIdKey => $membership) { |
| 4175 | if ($membership) { |
| 4176 | $membershipParams = array( |
| 4177 | 'id' => $membership->id, |
| 4178 | 'contact_id' => $membership->contact_id, |
| 4179 | 'is_test' => $membership->is_test, |
| 4180 | 'membership_type_id' => $membership->membership_type_id, |
| 4181 | ); |
| 4182 | |
| 4183 | $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'], |
| 4184 | $membershipParams['membership_type_id'], |
| 4185 | $membershipParams['is_test'], |
| 4186 | $membershipParams['id'] |
| 4187 | ); |
| 4188 | |
| 4189 | // CRM-8141 update the membership type with the value recorded in log when membership created/renewed |
| 4190 | // this picks up membership type changes during renewals |
| 4191 | $sql = " |
| 4192 | SELECT membership_type_id |
| 4193 | FROM civicrm_membership_log |
| 4194 | WHERE membership_id={$membershipParams['id']} |
| 4195 | ORDER BY id DESC |
| 4196 | LIMIT 1;"; |
| 4197 | $dao = CRM_Core_DAO::executeQuery($sql); |
| 4198 | if ($dao->fetch()) { |
| 4199 | if (!empty($dao->membership_type_id)) { |
| 4200 | $membershipParams['membership_type_id'] = $dao->membership_type_id; |
| 4201 | } |
| 4202 | } |
| 4203 | $dao->free(); |
| 4204 | |
| 4205 | $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType( |
| 4206 | $membershipParams['membership_type_id'], |
| 4207 | $primaryContributionID |
| 4208 | ); |
| 4209 | $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL); |
| 4210 | if ($currentMembership) { |
| 4211 | /* |
| 4212 | * Fixed FOR CRM-4433 |
| 4213 | * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status |
| 4214 | * when Contribution mode is notify and membership is for renewal ) |
| 4215 | */ |
| 4216 | CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate); |
| 4217 | |
| 4218 | // @todo - we should pass membership_type_id instead of null here but not |
| 4219 | // adding as not sure of testing |
| 4220 | $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'], |
| 4221 | $changeDate, NULL, $membershipParams['num_terms'] |
| 4222 | ); |
| 4223 | |
| 4224 | $dates['join_date'] = $currentMembership['join_date']; |
| 4225 | } |
| 4226 | |
| 4227 | //get the status for membership. |
| 4228 | $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], |
| 4229 | $dates['end_date'], |
| 4230 | $dates['join_date'], |
| 4231 | 'today', |
| 4232 | TRUE, |
| 4233 | $membershipParams['membership_type_id'], |
| 4234 | $membershipParams |
| 4235 | ); |
| 4236 | |
| 4237 | $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New'); |
| 4238 | //we might be renewing membership, |
| 4239 | //so make status override false. |
| 4240 | $membershipParams['is_override'] = FALSE; |
| 4241 | civicrm_api3('Membership', 'create', $membershipParams); |
| 4242 | |
| 4243 | //update related Memberships. |
| 4244 | CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $membershipParams); |
| 4245 | } |
| 4246 | } |
| 4247 | } |
| 4248 | } |
| 4249 | else { |
| 4250 | if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) { |
| 4251 | $eventDetail = civicrm_api3('Event', 'getsingle', array('id' => $objects['event']->id)); |
| 4252 | $contributionParams['source'] = ts('Online Event Registration') . ': ' . $eventDetail['title']; |
| 4253 | if ($eventDetail['is_email_confirm']) { |
| 4254 | // @todo this should be set by the function that sends the mail after sending. |
| 4255 | $contributionParams['receipt_date'] = $changeDate; |
| 4256 | } |
| 4257 | $participantParams['id'] = $participant->id; |
| 4258 | $participantParams['status_id'] = 'Registered'; |
| 4259 | civicrm_api3('Participant', 'create', $participantParams); |
| 4260 | } |
| 4261 | } |
| 4262 | |
| 4263 | $contributionParams['id'] = $contribution->id; |
| 4264 | |
| 4265 | civicrm_api3('Contribution', 'create', $contributionParams); |
| 4266 | |
| 4267 | // Add new soft credit against current $contribution. |
| 4268 | if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) { |
| 4269 | CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id); |
| 4270 | } |
| 4271 | |
| 4272 | $paymentProcessorId = ''; |
| 4273 | if (isset($objects['paymentProcessor'])) { |
| 4274 | if (is_array($objects['paymentProcessor'])) { |
| 4275 | $paymentProcessorId = $objects['paymentProcessor']['id']; |
| 4276 | } |
| 4277 | else { |
| 4278 | $paymentProcessorId = $objects['paymentProcessor']->id; |
| 4279 | } |
| 4280 | } |
| 4281 | |
| 4282 | $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array( |
| 4283 | 'labelColumn' => 'name', |
| 4284 | 'flip' => 1, |
| 4285 | )); |
| 4286 | if ((empty($input['prevContribution']) && $paymentProcessorId) || (!$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == $contributionStatuses['Pending'])) { |
| 4287 | $input['payment_processor'] = $paymentProcessorId; |
| 4288 | } |
| 4289 | $input['contribution_status_id'] = $contributionStatuses['Completed']; |
| 4290 | $input['total_amount'] = $input['amount']; |
| 4291 | $input['contribution'] = $contribution; |
| 4292 | $input['financial_type_id'] = $contribution->financial_type_id; |
| 4293 | |
| 4294 | if (!empty($contribution->_relatedObjects['participant'])) { |
| 4295 | $input['contribution_mode'] = 'participant'; |
| 4296 | $input['participant_id'] = $contribution->_relatedObjects['participant']->id; |
| 4297 | $input['skipLineItem'] = 1; |
| 4298 | } |
| 4299 | elseif (!empty($contribution->_relatedObjects['membership'])) { |
| 4300 | $input['skipLineItem'] = TRUE; |
| 4301 | $input['contribution_mode'] = 'membership'; |
| 4302 | } |
| 4303 | //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second |
| 4304 | // and subsequent payments. In this case the line items are created at |
| 4305 | // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems |
| 4306 | // and since the contribution is saved prior to this line there is always a contribution-id, |
| 4307 | // however there is never a prevContribution (which appears to mean original contribution not previous |
| 4308 | // contribution - or preUpdateContributionObject most accurately) |
| 4309 | // so, this is always called & only appears to succeed when prevContribution exists - which appears |
| 4310 | // to mean "are we updating an exisitng pending contribution" |
| 4311 | //I was able to make the unit test complete as fataling here doesn't prevent |
| 4312 | // the contribution being created - but activities would not be created or emails sent |
| 4313 | |
| 4314 | CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL); |
| 4315 | |
| 4316 | CRM_Core_Error::debug_log_message("Contribution record updated successfully"); |
| 4317 | $transaction->commit(); |
| 4318 | |
| 4319 | CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contribution); |
| 4320 | |
| 4321 | // create an activity record |
| 4322 | if ($input['component'] == 'contribute') { |
| 4323 | //CRM-4027 |
| 4324 | $targetContactID = NULL; |
| 4325 | if (!empty($ids['related_contact'])) { |
| 4326 | $targetContactID = $contribution->contact_id; |
| 4327 | $contribution->contact_id = $ids['related_contact']; |
| 4328 | } |
| 4329 | CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID); |
| 4330 | // event |
| 4331 | } |
| 4332 | else { |
| 4333 | CRM_Activity_BAO_Activity::addActivity($participant); |
| 4334 | } |
| 4335 | |
| 4336 | // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending |
| 4337 | // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set |
| 4338 | if (!array_key_exists('is_email_receipt', $values) || |
| 4339 | $values['is_email_receipt'] == 1 |
| 4340 | ) { |
| 4341 | self::sendMail($input, $ids, $objects['contribution'], $values, $recur, FALSE); |
| 4342 | CRM_Core_Error::debug_log_message("Receipt sent"); |
| 4343 | } |
| 4344 | |
| 4345 | CRM_Core_Error::debug_log_message("Success: Database updated"); |
| 4346 | if ($isRecurring) { |
| 4347 | CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur, |
| 4348 | $isFirstOrLastRecurringPayment); |
| 4349 | } |
| 4350 | } |
| 4351 | |
| 4352 | /** |
| 4353 | * Send receipt from contribution. |
| 4354 | * |
| 4355 | * Do not call this directly - it is being refactored. use contribution.sendmessage api call. |
| 4356 | * |
| 4357 | * Note that the compose message part has been moved to contribution |
| 4358 | * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it. |
| 4359 | * |
| 4360 | * @param array $input |
| 4361 | * Incoming data from Payment processor. |
| 4362 | * @param array $ids |
| 4363 | * Related object IDs. |
| 4364 | * @param CRM_Contribute_BAO_Contribution $contribution |
| 4365 | * @param array $values |
| 4366 | * Values related to objects that have already been loaded. |
| 4367 | * @param bool $recur |
| 4368 | * Is it part of a recurring contribution. |
| 4369 | * @param bool $returnMessageText |
| 4370 | * Should text be returned instead of sent. This. |
| 4371 | * is because the function is also used to generate pdfs |
| 4372 | * |
| 4373 | * @return array |
| 4374 | */ |
| 4375 | public static function sendMail(&$input, &$ids, $contribution, &$values, $recur = FALSE, $returnMessageText = FALSE) { |
| 4376 | $input['is_recur'] = $recur; |
| 4377 | // set receipt from e-mail and name in value |
| 4378 | if (!$returnMessageText) { |
| 4379 | $session = CRM_Core_Session::singleton(); |
| 4380 | $userID = $session->get('userID'); |
| 4381 | if (!empty($userID)) { |
| 4382 | list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID); |
| 4383 | $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $input, $userEmail); |
| 4384 | $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $input, $userName); |
| 4385 | } |
| 4386 | } |
| 4387 | return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText); |
| 4388 | } |
| 4389 | |
| 4390 | } |