| 1 | <?php |
| 2 | /* |
| 3 | +--------------------------------------------------------------------+ |
| 4 | | CiviCRM version 4.5 | |
| 5 | +--------------------------------------------------------------------+ |
| 6 | | Copyright CiviCRM LLC (c) 2004-2014 | |
| 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-2014 |
| 32 | * $Id$ |
| 33 | * |
| 34 | */ |
| 35 | class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution { |
| 36 | |
| 37 | /** |
| 38 | * static field for all the contribution information that we can potentially import |
| 39 | * |
| 40 | * @var array |
| 41 | * @static |
| 42 | */ |
| 43 | static $_importableFields = NULL; |
| 44 | |
| 45 | /** |
| 46 | * static field for all the contribution information that we can potentially export |
| 47 | * |
| 48 | * @var array |
| 49 | * @static |
| 50 | */ |
| 51 | static $_exportableFields = NULL; |
| 52 | |
| 53 | /** |
| 54 | * field for all the objects related to this contribution |
| 55 | * @var array of objects (e.g membership object, participant object) |
| 56 | */ |
| 57 | public $_relatedObjects = array(); |
| 58 | |
| 59 | /** |
| 60 | * field for the component - either 'event' (participant) or 'contribute' |
| 61 | * (any item related to a contribution page e.g. membership, pledge, contribution) |
| 62 | * This is used for composing messages because they have dependency on the |
| 63 | * contribution_page or event page - although over time we may eliminate that |
| 64 | * |
| 65 | * @var string component or event |
| 66 | */ |
| 67 | public $_component = NULL; |
| 68 | |
| 69 | /* |
| 70 | * construct method |
| 71 | */ |
| 72 | /** |
| 73 | * class constructor |
| 74 | * |
| 75 | * @access public |
| 76 | * @return \CRM_Contribute_DAO_Contribution |
| 77 | */ |
| 78 | /** |
| 79 | * |
| 80 | */ |
| 81 | 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 (reference ) an assoc array of name/value pairs |
| 93 | * @param array $ids the array that holds all the db ids |
| 94 | * |
| 95 | * @return object CRM_Contribute_BAO_Contribution object |
| 96 | * @access public |
| 97 | * @static |
| 98 | */ |
| 99 | static function add(&$params, $ids = array()) { |
| 100 | if (empty($params)) { |
| 101 | return; |
| 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 | |
| 106 | $duplicates = array(); |
| 107 | if (self::checkDuplicate($params, $duplicates, $contributionID)) { |
| 108 | $error = CRM_Core_Error::singleton(); |
| 109 | $d = implode(', ', $duplicates); |
| 110 | $error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION, |
| 111 | 'Fatal', |
| 112 | array($d), |
| 113 | "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d" |
| 114 | ); |
| 115 | return $error; |
| 116 | } |
| 117 | |
| 118 | // first clean up all the money fields |
| 119 | $moneyFields = array( |
| 120 | 'total_amount', |
| 121 | 'net_amount', |
| 122 | 'fee_amount', |
| 123 | 'non_deductible_amount', |
| 124 | ); |
| 125 | |
| 126 | //if priceset is used, no need to cleanup money |
| 127 | if (!empty($params['skipCleanMoney'])) { |
| 128 | unset($moneyFields[0]); |
| 129 | } |
| 130 | |
| 131 | foreach ($moneyFields as $field) { |
| 132 | if (isset($params[$field])) { |
| 133 | $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]); |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | // CRM-13420, set payment instrument to default if payment_instrument_id is empty |
| 138 | if (!$contributionID && empty($params['payment_instrument_id'])) { |
| 139 | $params['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', |
| 140 | FALSE, FALSE, FALSE, 'AND is_default = 1')); |
| 141 | } |
| 142 | |
| 143 | if (!empty($params['payment_instrument_id'])) { |
| 144 | $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name'); |
| 145 | if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) { |
| 146 | $params['check_number'] = 'null'; |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | // contribution status is missing, choose Completed as default status |
| 151 | // do this for create mode only |
| 152 | if (empty($ids['contribution']) && empty($params['contribution_status_id'])) { |
| 153 | $params['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'); |
| 154 | } |
| 155 | $setPrevContribution = TRUE; |
| 156 | // CRM-13964 partial payment |
| 157 | if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) { |
| 158 | $partialAmtTotal = $params['partial_payment_total']; |
| 159 | $partialAmtPay = $params['partial_amount_pay']; |
| 160 | $params['total_amount'] = $partialAmtTotal; |
| 161 | if ($partialAmtPay < $partialAmtTotal) { |
| 162 | $params['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Partially paid', 'name'); |
| 163 | $params['is_pay_later'] = 0; |
| 164 | $setPrevContribution = FALSE; |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | if ($contributionID) { |
| 169 | CRM_Utils_Hook::pre('edit', 'Contribution', $contributionID, $params); |
| 170 | } |
| 171 | else { |
| 172 | CRM_Utils_Hook::pre('create', 'Contribution', NULL, $params); |
| 173 | } |
| 174 | $contribution = new CRM_Contribute_BAO_Contribution(); |
| 175 | $contribution->copyValues($params); |
| 176 | |
| 177 | $contribution->id = $contributionID; |
| 178 | |
| 179 | if (!CRM_Utils_Rule::currencyCode($contribution->currency)) { |
| 180 | $config = CRM_Core_Config::singleton(); |
| 181 | $contribution->currency = $config->defaultCurrency; |
| 182 | } |
| 183 | |
| 184 | if ($contributionID && $setPrevContribution) { |
| 185 | $params['prevContribution'] = self::getValues(array('id' => $contributionID), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray); |
| 186 | } |
| 187 | |
| 188 | $result = $contribution->save(); |
| 189 | |
| 190 | // Add financial_trxn details as part of fix for CRM-4724 |
| 191 | $contribution->trxn_result_code = CRM_Utils_Array::value('trxn_result_code', $params); |
| 192 | $contribution->payment_processor = CRM_Utils_Array::value('payment_processor', $params); |
| 193 | |
| 194 | //add Account details |
| 195 | $params['contribution'] = $contribution; |
| 196 | self::recordFinancialAccounts($params); |
| 197 | |
| 198 | // reset the group contact cache for this group |
| 199 | CRM_Contact_BAO_GroupContactCache::remove(); |
| 200 | |
| 201 | if ($contributionID) { |
| 202 | CRM_Utils_Hook::post('edit', 'Contribution', $contribution->id, $contribution); |
| 203 | } |
| 204 | else { |
| 205 | CRM_Utils_Hook::post('create', 'Contribution', $contribution->id, $contribution); |
| 206 | } |
| 207 | |
| 208 | return $result; |
| 209 | } |
| 210 | |
| 211 | /** |
| 212 | * Given the list of params in the params array, fetch the object |
| 213 | * and store the values in the values array |
| 214 | * |
| 215 | * @param array $params input parameters to find object |
| 216 | * @param array $values output values of the object |
| 217 | * @param array $ids the array that holds all the db ids |
| 218 | * |
| 219 | * @return CRM_Contribute_BAO_Contribution|null the found object or null |
| 220 | * @access public |
| 221 | * @static |
| 222 | */ |
| 223 | static function &getValues($params, &$values, &$ids) { |
| 224 | if (empty($params)) { |
| 225 | return NULL; |
| 226 | } |
| 227 | $contribution = new CRM_Contribute_BAO_Contribution(); |
| 228 | |
| 229 | $contribution->copyValues($params); |
| 230 | |
| 231 | if ($contribution->find(TRUE)) { |
| 232 | $ids['contribution'] = $contribution->id; |
| 233 | |
| 234 | CRM_Core_DAO::storeValues($contribution, $values); |
| 235 | |
| 236 | return $contribution; |
| 237 | } |
| 238 | return NULL; |
| 239 | } |
| 240 | |
| 241 | /** |
| 242 | * takes an associative array and creates a contribution object |
| 243 | * |
| 244 | * @param array $params (reference ) an assoc array of name/value pairs |
| 245 | * @param array $ids the array that holds all the db ids |
| 246 | * |
| 247 | * @return object CRM_Contribute_BAO_Contribution object |
| 248 | * @access public |
| 249 | * @static |
| 250 | */ |
| 251 | static function create(&$params, $ids = array()) { |
| 252 | $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date'); |
| 253 | foreach ($dateFields as $df) { |
| 254 | if (isset($params[$df])) { |
| 255 | $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]); |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | $transaction = new CRM_Core_Transaction(); |
| 260 | |
| 261 | $contribution = self::add($params, $ids); |
| 262 | |
| 263 | if (is_a($contribution, 'CRM_Core_Error')) { |
| 264 | $transaction->rollback(); |
| 265 | return $contribution; |
| 266 | } |
| 267 | |
| 268 | $params['contribution_id'] = $contribution->id; |
| 269 | |
| 270 | if (!empty($params['custom']) && |
| 271 | is_array($params['custom']) |
| 272 | ) { |
| 273 | CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id); |
| 274 | } |
| 275 | |
| 276 | $session = CRM_Core_Session::singleton(); |
| 277 | |
| 278 | if (!empty($params['note'])) { |
| 279 | $noteParams = array( |
| 280 | 'entity_table' => 'civicrm_contribution', |
| 281 | 'note' => $params['note'], |
| 282 | 'entity_id' => $contribution->id, |
| 283 | 'contact_id' => $session->get('userID'), |
| 284 | 'modified_date' => date('Ymd'), |
| 285 | ); |
| 286 | if (!$noteParams['contact_id']) { |
| 287 | $noteParams['contact_id'] = $params['contact_id']; |
| 288 | } |
| 289 | CRM_Core_BAO_Note::add($noteParams); |
| 290 | } |
| 291 | |
| 292 | // make entry in batch entity batch table |
| 293 | if (!empty($params['batch_id'])) { |
| 294 | // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params |
| 295 | $titleFields = array( |
| 296 | 'contact_id', |
| 297 | 'total_amount', |
| 298 | 'currency', |
| 299 | 'financial_type_id', |
| 300 | ); |
| 301 | $retrieveRequired = 0; |
| 302 | foreach ($titleFields as $titleField) { |
| 303 | if(!isset($contribution->$titleField)){ |
| 304 | $retrieveRequired = 1; |
| 305 | break; |
| 306 | } |
| 307 | } |
| 308 | if ($retrieveRequired == 1) { |
| 309 | $contribution->find(TRUE); |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | // check if activity record exist for this contribution, if |
| 314 | // not add activity |
| 315 | $activity = new CRM_Activity_DAO_Activity(); |
| 316 | $activity->source_record_id = $contribution->id; |
| 317 | $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type', |
| 318 | 'Contribution', |
| 319 | 'name' |
| 320 | ); |
| 321 | if (!$activity->find(TRUE)) { |
| 322 | CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline'); |
| 323 | } |
| 324 | else { |
| 325 | // CRM-13237 : if activity record found, update it with campaign id of contribution |
| 326 | CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity->id, 'campaign_id', $contribution->campaign_id); |
| 327 | } |
| 328 | |
| 329 | // Handle soft credit and / or link to personal campaign page |
| 330 | $softIDs = CRM_Contribute_BAO_ContributionSoft::getSoftCreditIds($contribution->id); |
| 331 | |
| 332 | //Delete PCP against this contribution and create new on submitted PCP information |
| 333 | $pcpId = CRM_Contribute_BAO_ContributionSoft::getSoftCreditIds($contribution->id, TRUE); |
| 334 | if ($pcpId) { |
| 335 | $deleteParams = array('id' => $pcpId); |
| 336 | CRM_Contribute_BAO_ContributionSoft::del($deleteParams); |
| 337 | } |
| 338 | if ($pcp = CRM_Utils_Array::value('pcp', $params)) { |
| 339 | $softParams = array(); |
| 340 | $softParams['contribution_id'] = $contribution->id; |
| 341 | $softParams['pcp_id'] = $pcp['pcp_made_through_id']; |
| 342 | $softParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', |
| 343 | $pcp['pcp_made_through_id'], 'contact_id' |
| 344 | ); |
| 345 | $softParams['currency'] = $contribution->currency; |
| 346 | $softParams['amount'] = $contribution->total_amount; |
| 347 | $softParams['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $pcp); |
| 348 | $softParams['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $pcp); |
| 349 | $softParams['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $pcp); |
| 350 | $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name'); |
| 351 | CRM_Contribute_BAO_ContributionSoft::add($softParams); |
| 352 | } |
| 353 | if (isset($params['soft_credit'])) { |
| 354 | $softParams = $params['soft_credit']; |
| 355 | |
| 356 | if (!empty($softIDs)) { |
| 357 | foreach ( $softIDs as $softID) { |
| 358 | if (!in_array($softID, $params['soft_credit_ids'])) { |
| 359 | $deleteParams = array('id' => $softID); |
| 360 | CRM_Contribute_BAO_ContributionSoft::del($deleteParams); |
| 361 | } |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | foreach ($softParams as $softParam) { |
| 366 | $softParam['contribution_id'] = $contribution->id; |
| 367 | $softParam['currency'] = $contribution->currency; |
| 368 | //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default |
| 369 | if (empty($softParam['amount'])) { |
| 370 | $softParam['amount'] = $contribution->total_amount; |
| 371 | } |
| 372 | CRM_Contribute_BAO_ContributionSoft::add($softParam); |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | $transaction->commit(); |
| 377 | |
| 378 | // do not add to recent items for import, CRM-4399 |
| 379 | if (empty($params['skipRecentView'])) { |
| 380 | $url = CRM_Utils_System::url('civicrm/contact/view/contribution', |
| 381 | "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home" |
| 382 | ); |
| 383 | // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params |
| 384 | $titleFields = array( |
| 385 | 'contact_id', |
| 386 | 'total_amount', |
| 387 | 'currency', |
| 388 | 'financial_type_id', |
| 389 | ); |
| 390 | $retrieveRequired = 0; |
| 391 | foreach ($titleFields as $titleField) { |
| 392 | if(!isset($contribution->$titleField)){ |
| 393 | $retrieveRequired = 1; |
| 394 | break; |
| 395 | } |
| 396 | } |
| 397 | if($retrieveRequired == 1){ |
| 398 | $contribution->find(TRUE); |
| 399 | } |
| 400 | $contributionTypes = CRM_Contribute_PseudoConstant::financialType(); |
| 401 | $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id] . ')'; |
| 402 | |
| 403 | $recentOther = array(); |
| 404 | if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) { |
| 405 | $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', |
| 406 | "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home" |
| 407 | ); |
| 408 | } |
| 409 | |
| 410 | if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) { |
| 411 | $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', |
| 412 | "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home" |
| 413 | ); |
| 414 | } |
| 415 | |
| 416 | // add the recently created Contribution |
| 417 | CRM_Utils_Recent::add($title, |
| 418 | $url, |
| 419 | $contribution->id, |
| 420 | 'Contribution', |
| 421 | $contribution->contact_id, |
| 422 | NULL, |
| 423 | $recentOther |
| 424 | ); |
| 425 | } |
| 426 | |
| 427 | return $contribution; |
| 428 | } |
| 429 | |
| 430 | /** |
| 431 | * Get the values for pseudoconstants for name->value and reverse. |
| 432 | * |
| 433 | * @param array $defaults (reference) the default values, some of which need to be resolved. |
| 434 | * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name) |
| 435 | * |
| 436 | * @return void |
| 437 | * @access public |
| 438 | * @static |
| 439 | */ |
| 440 | static function resolveDefaults(&$defaults, $reverse = FALSE) { |
| 441 | self::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant::financialType(), $reverse); |
| 442 | self::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant::paymentInstrument(), $reverse); |
| 443 | self::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant::contributionStatus(), $reverse); |
| 444 | self::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant::pcPage(), $reverse); |
| 445 | } |
| 446 | |
| 447 | /** |
| 448 | * This function is used to convert associative array names to values |
| 449 | * and vice-versa. |
| 450 | * |
| 451 | * This function is used by both the web form layer and the api. Note that |
| 452 | * the api needs the name => value conversion, also the view layer typically |
| 453 | * requires value => name conversion |
| 454 | */ |
| 455 | static function lookupValue(&$defaults, $property, &$lookup, $reverse) { |
| 456 | $id = $property . '_id'; |
| 457 | |
| 458 | $src = $reverse ? $property : $id; |
| 459 | $dst = $reverse ? $id : $property; |
| 460 | |
| 461 | if (!array_key_exists($src, $defaults)) { |
| 462 | return FALSE; |
| 463 | } |
| 464 | |
| 465 | $look = $reverse ? array_flip($lookup) : $lookup; |
| 466 | |
| 467 | if (is_array($look)) { |
| 468 | if (!array_key_exists($defaults[$src], $look)) { |
| 469 | return FALSE; |
| 470 | } |
| 471 | } |
| 472 | $defaults[$dst] = $look[$defaults[$src]]; |
| 473 | return TRUE; |
| 474 | } |
| 475 | |
| 476 | /** |
| 477 | * Takes a bunch of params that are needed to match certain criteria and |
| 478 | * retrieves the relevant objects. We'll tweak this function to be more |
| 479 | * full featured over a period of time. This is the inverse function of |
| 480 | * create. It also stores all the retrieved values in the default array |
| 481 | * |
| 482 | * @param array $params (reference ) an assoc array of name/value pairs |
| 483 | * @param array $defaults (reference ) an assoc array to hold the name / value pairs |
| 484 | * in a hierarchical manner |
| 485 | * @param array $ids (reference) the array that holds all the db ids |
| 486 | * |
| 487 | * @return object CRM_Contribute_BAO_Contribution object |
| 488 | * @access public |
| 489 | * @static |
| 490 | */ |
| 491 | static function retrieve(&$params, &$defaults, &$ids) { |
| 492 | $contribution = CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids); |
| 493 | return $contribution; |
| 494 | } |
| 495 | |
| 496 | /** |
| 497 | * combine all the importable fields from the lower levels object |
| 498 | * |
| 499 | * The ordering is important, since currently we do not have a weight |
| 500 | * scheme. Adding weight is super important and should be done in the |
| 501 | * next week or so, before this can be called complete. |
| 502 | * |
| 503 | * @param string $contactType |
| 504 | * @param bool $status |
| 505 | * |
| 506 | * @return array array of importable Fields |
| 507 | * @access public |
| 508 | * @static |
| 509 | */ |
| 510 | static function &importableFields($contactType = 'Individual', $status = TRUE) { |
| 511 | if (!self::$_importableFields) { |
| 512 | if (!self::$_importableFields) { |
| 513 | self::$_importableFields = array(); |
| 514 | } |
| 515 | |
| 516 | if (!$status) { |
| 517 | $fields = array('' => array('title' => ts('- do not import -'))); |
| 518 | } |
| 519 | else { |
| 520 | $fields = array('' => array('title' => ts('- Contribution Fields -'))); |
| 521 | } |
| 522 | |
| 523 | $note = CRM_Core_DAO_Note::import(); |
| 524 | $tmpFields = CRM_Contribute_DAO_Contribution::import(); |
| 525 | unset($tmpFields['option_value']); |
| 526 | $optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute'); |
| 527 | $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL); |
| 528 | |
| 529 | // Using new Dedupe rule. |
| 530 | $ruleParams = array( |
| 531 | 'contact_type' => $contactType, |
| 532 | 'used' => 'Unsupervised', |
| 533 | ); |
| 534 | $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams); |
| 535 | $tmpContactField = array(); |
| 536 | if (is_array($fieldsArray)) { |
| 537 | foreach ($fieldsArray as $value) { |
| 538 | //skip if there is no dupe rule |
| 539 | if ($value == 'none') { |
| 540 | continue; |
| 541 | } |
| 542 | $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', |
| 543 | $value, |
| 544 | 'id', |
| 545 | 'column_name' |
| 546 | ); |
| 547 | $value = $customFieldId ? 'custom_' . $customFieldId : $value; |
| 548 | $tmpContactField[trim($value)] = $contactFields[trim($value)]; |
| 549 | if (!$status) { |
| 550 | $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)'); |
| 551 | } |
| 552 | else { |
| 553 | $title = $tmpContactField[trim($value)]['title']; |
| 554 | } |
| 555 | $tmpContactField[trim($value)]['title'] = $title; |
| 556 | } |
| 557 | } |
| 558 | |
| 559 | $tmpContactField['external_identifier'] = $contactFields['external_identifier']; |
| 560 | $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)'); |
| 561 | $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)'); |
| 562 | $fields = array_merge($fields, $tmpContactField); |
| 563 | $fields = array_merge($fields, $tmpFields); |
| 564 | $fields = array_merge($fields, $note); |
| 565 | $fields = array_merge($fields, $optionFields); |
| 566 | $fields = array_merge($fields, CRM_Financial_DAO_FinancialType::export()); |
| 567 | $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution')); |
| 568 | self::$_importableFields = $fields; |
| 569 | } |
| 570 | return self::$_importableFields; |
| 571 | } |
| 572 | |
| 573 | /** |
| 574 | * @return array |
| 575 | */ |
| 576 | static function &exportableFields() { |
| 577 | if (!self::$_exportableFields) { |
| 578 | if (!self::$_exportableFields) { |
| 579 | self::$_exportableFields = array(); |
| 580 | } |
| 581 | |
| 582 | $impFields = CRM_Contribute_DAO_Contribution::export(); |
| 583 | $expFieldProduct = CRM_Contribute_DAO_Product::export(); |
| 584 | $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct::export(); |
| 585 | $typeField = CRM_Financial_DAO_FinancialType::export(); |
| 586 | $financialAccount = CRM_Financial_DAO_FinancialAccount::export(); |
| 587 | $optionField = CRM_Core_OptionValue::getFields($mode = 'contribute'); |
| 588 | $contributionStatus = array( |
| 589 | 'contribution_status' => array( |
| 590 | 'title' => ts('Contribution Status'), |
| 591 | 'name' => 'contribution_status', |
| 592 | 'data_type' => CRM_Utils_Type::T_STRING |
| 593 | )); |
| 594 | |
| 595 | $contributionNote = array( |
| 596 | 'contribution_note' => |
| 597 | array( |
| 598 | 'title' => ts('Contribution Note'), |
| 599 | 'name' => 'contribution_note', |
| 600 | 'data_type' => CRM_Utils_Type::T_TEXT |
| 601 | ) |
| 602 | ); |
| 603 | |
| 604 | $contributionRecurId = array( |
| 605 | 'contribution_recur_id' => |
| 606 | array( |
| 607 | 'title' => ts('Recurring Contributions ID'), |
| 608 | 'name' => 'contribution_recur_id', |
| 609 | 'where' => 'civicrm_contribution.contribution_recur_id', |
| 610 | 'data_type' => CRM_Utils_Type::T_INT |
| 611 | )); |
| 612 | |
| 613 | $extraFields = array( |
| 614 | 'contribution_batch' => array( |
| 615 | 'title' => ts('Batch Name') |
| 616 | ) |
| 617 | ); |
| 618 | |
| 619 | $softCreditFields = array( |
| 620 | 'contribution_soft_credit_name' => array( |
| 621 | 'name' => 'contribution_soft_credit_name', |
| 622 | 'title' => 'Soft Credit For', |
| 623 | 'where' => 'civicrm_contact_d.display_name', |
| 624 | 'data_type' => CRM_Utils_Type::T_STRING |
| 625 | ), |
| 626 | 'contribution_soft_credit_amount' => array( |
| 627 | 'name' => 'contribution_soft_credit_amount', |
| 628 | 'title' => 'Soft Credit Amount', |
| 629 | 'where' => 'civicrm_contribution_soft.amount', |
| 630 | 'data_type' => CRM_Utils_Type::T_MONEY |
| 631 | ), |
| 632 | 'contribution_soft_credit_type' => array( |
| 633 | 'name' => 'contribution_soft_credit_type', |
| 634 | 'title' => 'Soft Credit Type', |
| 635 | 'where' => 'contribution_softcredit_type.label', |
| 636 | 'data_type' => CRM_Utils_Type::T_STRING |
| 637 | ), |
| 638 | 'contribution_soft_credit_contribution_id' => array( |
| 639 | 'name' => 'contribution_soft_credit_contribution_id', |
| 640 | 'title' => 'Soft Credit For Contribution ID', |
| 641 | 'where' => 'civicrm_contribution_soft.contribution_id', |
| 642 | 'data_type' => CRM_Utils_Type::T_INT |
| 643 | ), |
| 644 | ); |
| 645 | |
| 646 | $fields = array_merge($impFields, $typeField, $contributionStatus, $optionField, $expFieldProduct, |
| 647 | $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, |
| 648 | CRM_Core_BAO_CustomField::getFieldsForImport('Contribution') |
| 649 | ); |
| 650 | |
| 651 | self::$_exportableFields = $fields; |
| 652 | } |
| 653 | |
| 654 | return self::$_exportableFields; |
| 655 | } |
| 656 | |
| 657 | /** |
| 658 | * @param null $status |
| 659 | * @param null $startDate |
| 660 | * @param null $endDate |
| 661 | * |
| 662 | * @return array|null |
| 663 | */ |
| 664 | static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) { |
| 665 | $where = array(); |
| 666 | switch ($status) { |
| 667 | case 'Valid': |
| 668 | $where[] = 'contribution_status_id = 1'; |
| 669 | break; |
| 670 | |
| 671 | case 'Cancelled': |
| 672 | $where[] = 'contribution_status_id = 3'; |
| 673 | break; |
| 674 | } |
| 675 | |
| 676 | if ($startDate) { |
| 677 | $where[] = "receive_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'"; |
| 678 | } |
| 679 | if ($endDate) { |
| 680 | $where[] = "receive_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'"; |
| 681 | } |
| 682 | |
| 683 | $whereCond = implode(' AND ', $where); |
| 684 | |
| 685 | $query = " |
| 686 | SELECT sum( total_amount ) as total_amount, |
| 687 | count( civicrm_contribution.id ) as total_count, |
| 688 | currency |
| 689 | FROM civicrm_contribution |
| 690 | INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id ) |
| 691 | WHERE $whereCond |
| 692 | AND ( is_test = 0 OR is_test IS NULL ) |
| 693 | AND contact.is_deleted = 0 |
| 694 | GROUP BY currency |
| 695 | "; |
| 696 | |
| 697 | $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); |
| 698 | $amount = array(); |
| 699 | $count = 0; |
| 700 | while ($dao->fetch()) { |
| 701 | $count += $dao->total_count; |
| 702 | $amount[] = CRM_Utils_Money::format($dao->total_amount, $dao->currency); |
| 703 | } |
| 704 | if ($count) { |
| 705 | return array('amount' => implode(', ', $amount), |
| 706 | 'count' => $count, |
| 707 | ); |
| 708 | } |
| 709 | return NULL; |
| 710 | } |
| 711 | |
| 712 | /** |
| 713 | * Delete the indirect records associated with this contribution first |
| 714 | * |
| 715 | * @param $id |
| 716 | * |
| 717 | * @return mixed|null $results no of deleted Contribution on success, false otherwise@access public |
| 718 | * @static |
| 719 | */ |
| 720 | static function deleteContribution($id) { |
| 721 | CRM_Utils_Hook::pre('delete', 'Contribution', $id, CRM_Core_DAO::$_nullArray); |
| 722 | |
| 723 | $transaction = new CRM_Core_Transaction(); |
| 724 | |
| 725 | $results = NULL; |
| 726 | //delete activity record |
| 727 | $params = array( |
| 728 | 'source_record_id' => $id, |
| 729 | // activity type id for contribution |
| 730 | 'activity_type_id' => 6, |
| 731 | ); |
| 732 | |
| 733 | CRM_Activity_BAO_Activity::deleteActivity($params); |
| 734 | |
| 735 | //delete billing address if exists for this contribution. |
| 736 | self::deleteAddress($id); |
| 737 | |
| 738 | //update pledge and pledge payment, CRM-3961 |
| 739 | CRM_Pledge_BAO_PledgePayment::resetPledgePayment($id); |
| 740 | |
| 741 | // remove entry from civicrm_price_set_entity, CRM-5095 |
| 742 | if (CRM_Price_BAO_PriceSet::getFor('civicrm_contribution', $id)) { |
| 743 | CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution', $id); |
| 744 | } |
| 745 | // cleanup line items. |
| 746 | $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id'); |
| 747 | |
| 748 | // delete any related entity_financial_trxn, financial_trxn and financial_item records. |
| 749 | CRM_Core_BAO_FinancialTrxn::deleteFinancialTrxn($id); |
| 750 | |
| 751 | if ($participantId) { |
| 752 | CRM_Price_BAO_LineItem::deleteLineItems($participantId, 'civicrm_participant'); |
| 753 | } |
| 754 | else { |
| 755 | CRM_Price_BAO_LineItem::deleteLineItems($id, 'civicrm_contribution'); |
| 756 | } |
| 757 | |
| 758 | //delete note. |
| 759 | $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_contribution'); |
| 760 | $noteId = key($note); |
| 761 | if ($noteId) { |
| 762 | CRM_Core_BAO_Note::del($noteId, FALSE); |
| 763 | } |
| 764 | |
| 765 | $dao = new CRM_Contribute_DAO_Contribution(); |
| 766 | $dao->id = $id; |
| 767 | |
| 768 | $results = $dao->delete(); |
| 769 | |
| 770 | $transaction->commit(); |
| 771 | |
| 772 | CRM_Utils_Hook::post('delete', 'Contribution', $dao->id, $dao); |
| 773 | |
| 774 | // delete the recently created Contribution |
| 775 | $contributionRecent = array( |
| 776 | 'id' => $id, |
| 777 | 'type' => 'Contribution', |
| 778 | ); |
| 779 | CRM_Utils_Recent::del($contributionRecent); |
| 780 | |
| 781 | return $results; |
| 782 | } |
| 783 | |
| 784 | /** |
| 785 | * Check if there is a contribution with the same trxn_id or invoice_id |
| 786 | * |
| 787 | * @param $input |
| 788 | * @param array $duplicates (reference ) store ids of duplicate contribs |
| 789 | * |
| 790 | * @param null $id |
| 791 | * |
| 792 | * @internal param array $params (reference ) an assoc array of name/value pairs |
| 793 | * @return boolean true if duplicate, false otherwise |
| 794 | * @access public |
| 795 | * static |
| 796 | */ |
| 797 | static function checkDuplicate($input, &$duplicates, $id = NULL) { |
| 798 | if (!$id) { |
| 799 | $id = CRM_Utils_Array::value('id', $input); |
| 800 | } |
| 801 | $trxn_id = CRM_Utils_Array::value('trxn_id', $input); |
| 802 | $invoice_id = CRM_Utils_Array::value('invoice_id', $input); |
| 803 | |
| 804 | $clause = array(); |
| 805 | $input = array(); |
| 806 | |
| 807 | if ($trxn_id) { |
| 808 | $clause[] = "trxn_id = %1"; |
| 809 | $input[1] = array($trxn_id, 'String'); |
| 810 | } |
| 811 | |
| 812 | if ($invoice_id) { |
| 813 | $clause[] = "invoice_id = %2"; |
| 814 | $input[2] = array($invoice_id, 'String'); |
| 815 | } |
| 816 | |
| 817 | if (empty($clause)) { |
| 818 | return FALSE; |
| 819 | } |
| 820 | |
| 821 | $clause = implode(' OR ', $clause); |
| 822 | if ($id) { |
| 823 | $clause = "( $clause ) AND id != %3"; |
| 824 | $input[3] = array($id, 'Integer'); |
| 825 | } |
| 826 | |
| 827 | $query = "SELECT id FROM civicrm_contribution WHERE $clause"; |
| 828 | $dao = CRM_Core_DAO::executeQuery($query, $input); |
| 829 | $result = FALSE; |
| 830 | while ($dao->fetch()) { |
| 831 | $duplicates[] = $dao->id; |
| 832 | $result = TRUE; |
| 833 | } |
| 834 | return $result; |
| 835 | } |
| 836 | |
| 837 | /** |
| 838 | * takes an associative array and creates a contribution_product object |
| 839 | * |
| 840 | * the function extract all the params it needs to initialize the create a |
| 841 | * contribution_product object. the params array could contain additional unused name/value |
| 842 | * pairs |
| 843 | * |
| 844 | * @param array $params (reference ) an assoc array of name/value pairs |
| 845 | * |
| 846 | * @return object CRM_Contribute_BAO_ContributionProduct object |
| 847 | * @access public |
| 848 | * @static |
| 849 | */ |
| 850 | static function addPremium(&$params) { |
| 851 | $contributionProduct = new CRM_Contribute_DAO_ContributionProduct(); |
| 852 | $contributionProduct->copyValues($params); |
| 853 | return $contributionProduct->save(); |
| 854 | } |
| 855 | |
| 856 | /** |
| 857 | * Function to get list of contribution fields for profile |
| 858 | * For now we only allow custom contribution fields to be in |
| 859 | * profile |
| 860 | * |
| 861 | * @param boolean $addExtraFields true if special fields needs to be added |
| 862 | * |
| 863 | * @return return the list of contribution fields |
| 864 | * @static |
| 865 | * @access public |
| 866 | */ |
| 867 | static function getContributionFields($addExtraFields = TRUE) { |
| 868 | $contributionFields = CRM_Contribute_DAO_Contribution::export(); |
| 869 | $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue::getFields($mode = 'contribute')); |
| 870 | |
| 871 | if ($addExtraFields) { |
| 872 | $contributionFields = array_merge($contributionFields, self::getSpecialContributionFields()); |
| 873 | } |
| 874 | |
| 875 | $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType::export()); |
| 876 | |
| 877 | foreach ($contributionFields as $key => $var) { |
| 878 | if ($key == 'contribution_contact_id') { |
| 879 | continue; |
| 880 | } |
| 881 | elseif ($key == 'contribution_campaign_id') { |
| 882 | $var['title'] = ts('Campaign'); |
| 883 | } |
| 884 | $fields[$key] = $var; |
| 885 | } |
| 886 | |
| 887 | $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution')); |
| 888 | return $fields; |
| 889 | } |
| 890 | |
| 891 | /** |
| 892 | * Function to add extra fields specific to contribtion |
| 893 | * |
| 894 | * @static |
| 895 | */ |
| 896 | static function getSpecialContributionFields() { |
| 897 | $extraFields = array( |
| 898 | 'contribution_soft_credit_name' => array( |
| 899 | 'name' => 'contribution_soft_credit_name', |
| 900 | 'title' => 'Soft Credit Name', |
| 901 | 'headerPattern' => '/^soft_credit_name$/i', |
| 902 | 'where' => 'civicrm_contact_d.display_name', |
| 903 | ), |
| 904 | 'contribution_soft_credit_email' => array( |
| 905 | 'name' => 'contribution_soft_credit_email', |
| 906 | 'title' => 'Soft Credit Email', |
| 907 | 'headerPattern' => '/^soft_credit_email$/i', |
| 908 | 'where' => 'soft_email.email', |
| 909 | ), |
| 910 | 'contribution_soft_credit_phone' => array( |
| 911 | 'name' => 'contribution_soft_credit_phone', |
| 912 | 'title' => 'Soft Credit Phone', |
| 913 | 'headerPattern' => '/^soft_credit_phone$/i', |
| 914 | 'where' => 'soft_phone.phone', |
| 915 | ), |
| 916 | 'contribution_soft_credit_contact_id' => array( |
| 917 | 'name' => 'contribution_soft_credit_contact_id', |
| 918 | 'title' => 'Soft Credit Contact ID', |
| 919 | 'headerPattern' => '/^soft_credit_contact_id$/i', |
| 920 | 'where' => 'civicrm_contribution_soft.contact_id', |
| 921 | ), |
| 922 | ); |
| 923 | |
| 924 | return $extraFields; |
| 925 | } |
| 926 | |
| 927 | /** |
| 928 | * @param $pageID |
| 929 | * |
| 930 | * @return array |
| 931 | */ |
| 932 | static function getCurrentandGoalAmount($pageID) { |
| 933 | $query = " |
| 934 | SELECT p.goal_amount as goal, sum( c.total_amount ) as total |
| 935 | FROM civicrm_contribution_page p, |
| 936 | civicrm_contribution c |
| 937 | WHERE p.id = c.contribution_page_id |
| 938 | AND p.id = %1 |
| 939 | AND c.cancel_date is null |
| 940 | GROUP BY p.id |
| 941 | "; |
| 942 | |
| 943 | $config = CRM_Core_Config::singleton(); |
| 944 | $params = array(1 => array($pageID, 'Integer')); |
| 945 | $dao = CRM_Core_DAO::executeQuery($query, $params); |
| 946 | |
| 947 | if ($dao->fetch()) { |
| 948 | return array($dao->goal, $dao->total); |
| 949 | } |
| 950 | else { |
| 951 | return array(NULL, NULL); |
| 952 | } |
| 953 | } |
| 954 | |
| 955 | /** |
| 956 | * Function to get list of contribution In Honor of contact Ids |
| 957 | * |
| 958 | * @param int $honorId In Honor of Contact ID |
| 959 | * |
| 960 | * @return return the list of contribution fields |
| 961 | * |
| 962 | * @access public |
| 963 | * @static |
| 964 | */ |
| 965 | static function getHonorContacts($honorId) { |
| 966 | $params = array(); |
| 967 | $honorDAO = new CRM_Contribute_DAO_ContributionSoft(); |
| 968 | $honorDAO->contact_id = $honorId; |
| 969 | $honorDAO->find(); |
| 970 | |
| 971 | $type = CRM_Contribute_PseudoConstant::financialType(); |
| 972 | |
| 973 | while ($honorDAO->fetch()) { |
| 974 | $contributionDAO = new CRM_Contribute_DAO_Contribution(); |
| 975 | $contributionDAO->id = $honorDAO->contribution_id; |
| 976 | |
| 977 | if ($contributionDAO->find(TRUE)) { |
| 978 | $params[$contributionDAO->id]['honor_type'] = CRM_Core_OptionGroup::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id, 'value'); |
| 979 | $params[$contributionDAO->id]['honorId'] = $contributionDAO->contact_id; |
| 980 | $params[$contributionDAO->id]['display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id, 'display_name'); |
| 981 | $params[$contributionDAO->id]['type'] = $type[$contributionDAO->financial_type_id]; |
| 982 | $params[$contributionDAO->id]['type_id'] = $contributionDAO->financial_type_id; |
| 983 | $params[$contributionDAO->id]['amount'] = CRM_Utils_Money::format($contributionDAO->total_amount, $contributionDAO->currency); |
| 984 | $params[$contributionDAO->id]['source'] = $contributionDAO->source; |
| 985 | $params[$contributionDAO->id]['receive_date'] = $contributionDAO->receive_date; |
| 986 | $params[$contributionDAO->id]['contribution_status'] = CRM_Contribute_PseudoConstant::contributionStatus($contributionDAO->contribution_status_id); |
| 987 | } |
| 988 | } |
| 989 | |
| 990 | return $params; |
| 991 | } |
| 992 | |
| 993 | /** |
| 994 | * function to get the sort name of a contact for a particular contribution |
| 995 | * |
| 996 | * @param int $id id of the contribution |
| 997 | * |
| 998 | * @return null|string sort name of the contact if found |
| 999 | * @static |
| 1000 | * @access public |
| 1001 | */ |
| 1002 | static function sortName($id) { |
| 1003 | $id = CRM_Utils_Type::escape($id, 'Integer'); |
| 1004 | |
| 1005 | $query = " |
| 1006 | SELECT civicrm_contact.sort_name |
| 1007 | FROM civicrm_contribution, civicrm_contact |
| 1008 | WHERE civicrm_contribution.contact_id = civicrm_contact.id |
| 1009 | AND civicrm_contribution.id = {$id} |
| 1010 | "; |
| 1011 | return CRM_Core_DAO::singleValueQuery($query, CRM_Core_DAO::$_nullArray); |
| 1012 | } |
| 1013 | |
| 1014 | /** |
| 1015 | * @param $contactID |
| 1016 | * |
| 1017 | * @return array |
| 1018 | */ |
| 1019 | static function annual($contactID) { |
| 1020 | if (is_array($contactID)) { |
| 1021 | $contactIDs = implode(',', $contactID); |
| 1022 | } |
| 1023 | else { |
| 1024 | $contactIDs = $contactID; |
| 1025 | } |
| 1026 | |
| 1027 | $config = CRM_Core_Config::singleton(); |
| 1028 | $startDate = $endDate = NULL; |
| 1029 | |
| 1030 | $currentMonth = date('m'); |
| 1031 | $currentDay = date('d'); |
| 1032 | if ((int ) $config->fiscalYearStart['M'] > $currentMonth || |
| 1033 | ((int ) $config->fiscalYearStart['M'] == $currentMonth && |
| 1034 | (int ) $config->fiscalYearStart['d'] > $currentDay |
| 1035 | ) |
| 1036 | ) { |
| 1037 | $year = date('Y') - 1; |
| 1038 | } |
| 1039 | else { |
| 1040 | $year = date('Y'); |
| 1041 | } |
| 1042 | $nextYear = $year + 1; |
| 1043 | |
| 1044 | if ($config->fiscalYearStart) { |
| 1045 | if ($config->fiscalYearStart['M'] < 10) { |
| 1046 | $config->fiscalYearStart['M'] = '0' . $config->fiscalYearStart['M']; |
| 1047 | } |
| 1048 | if ($config->fiscalYearStart['d'] < 10) { |
| 1049 | $config->fiscalYearStart['d'] = '0' . $config->fiscalYearStart['d']; |
| 1050 | } |
| 1051 | $monthDay = $config->fiscalYearStart['M'] . $config->fiscalYearStart['d']; |
| 1052 | } |
| 1053 | else { |
| 1054 | $monthDay = '0101'; |
| 1055 | } |
| 1056 | $startDate = "$year$monthDay"; |
| 1057 | $endDate = "$nextYear$monthDay"; |
| 1058 | |
| 1059 | $query = " |
| 1060 | SELECT count(*) as count, |
| 1061 | sum(total_amount) as amount, |
| 1062 | avg(total_amount) as average, |
| 1063 | currency |
| 1064 | FROM civicrm_contribution b |
| 1065 | WHERE b.contact_id IN ( $contactIDs ) |
| 1066 | AND b.contribution_status_id = 1 |
| 1067 | AND b.is_test = 0 |
| 1068 | AND b.receive_date >= $startDate |
| 1069 | AND b.receive_date < $endDate |
| 1070 | GROUP BY currency |
| 1071 | "; |
| 1072 | $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); |
| 1073 | $count = 0; |
| 1074 | $amount = $average = array(); |
| 1075 | while ($dao->fetch()) { |
| 1076 | if ($dao->count > 0 && $dao->amount > 0) { |
| 1077 | $count += $dao->count; |
| 1078 | $amount[] = CRM_Utils_Money::format($dao->amount, $dao->currency); |
| 1079 | $average[] = CRM_Utils_Money::format($dao->average, $dao->currency); |
| 1080 | } |
| 1081 | } |
| 1082 | if ($count > 0) { |
| 1083 | return array( |
| 1084 | $count, |
| 1085 | implode(', ', $amount), |
| 1086 | implode(', ', $average), |
| 1087 | ); |
| 1088 | } |
| 1089 | return array(0, 0, 0); |
| 1090 | } |
| 1091 | |
| 1092 | /** |
| 1093 | * Check if there is a contribution with the params passed in. |
| 1094 | * Used for trxn_id,invoice_id and contribution_id |
| 1095 | * |
| 1096 | * @param array $params an assoc array of name/value pairs |
| 1097 | * |
| 1098 | * @return array contribution id if success else NULL |
| 1099 | * @access public |
| 1100 | * static |
| 1101 | */ |
| 1102 | static function checkDuplicateIds($params) { |
| 1103 | $dao = new CRM_Contribute_DAO_Contribution(); |
| 1104 | |
| 1105 | $clause = array(); |
| 1106 | $input = array(); |
| 1107 | foreach ($params as $k => $v) { |
| 1108 | if ($v) { |
| 1109 | $clause[] = "$k = '$v'"; |
| 1110 | } |
| 1111 | } |
| 1112 | $clause = implode(' AND ', $clause); |
| 1113 | $query = "SELECT id FROM civicrm_contribution WHERE $clause"; |
| 1114 | $dao = CRM_Core_DAO::executeQuery($query, $input); |
| 1115 | |
| 1116 | while ($dao->fetch()) { |
| 1117 | $result = $dao->id; |
| 1118 | return $result; |
| 1119 | } |
| 1120 | return NULL; |
| 1121 | } |
| 1122 | |
| 1123 | /** |
| 1124 | * Function to get the contribution details for component export |
| 1125 | * |
| 1126 | * @param int $exportMode export mode |
| 1127 | * @param string $componentIds component ids |
| 1128 | * |
| 1129 | * @return array associated array |
| 1130 | * |
| 1131 | * @static |
| 1132 | * @access public |
| 1133 | */ |
| 1134 | static function getContributionDetails($exportMode, $componentIds) { |
| 1135 | $paymentDetails = array(); |
| 1136 | $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) '; |
| 1137 | |
| 1138 | if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) { |
| 1139 | $componentSelect = " civicrm_participant_payment.participant_id id"; |
| 1140 | $additionalClause = " |
| 1141 | INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id |
| 1142 | AND civicrm_participant_payment.participant_id {$componentClause} ) |
| 1143 | "; |
| 1144 | } |
| 1145 | elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) { |
| 1146 | $componentSelect = " civicrm_membership_payment.membership_id id"; |
| 1147 | $additionalClause = " |
| 1148 | INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id |
| 1149 | AND civicrm_membership_payment.membership_id {$componentClause} ) |
| 1150 | "; |
| 1151 | } |
| 1152 | elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) { |
| 1153 | $componentSelect = " civicrm_pledge_payment.id id"; |
| 1154 | $additionalClause = " |
| 1155 | INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id |
| 1156 | AND civicrm_pledge_payment.pledge_id {$componentClause} ) |
| 1157 | "; |
| 1158 | } |
| 1159 | |
| 1160 | $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date, |
| 1161 | trxn_id, {$componentSelect} |
| 1162 | FROM civicrm_contribution |
| 1163 | LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument') |
| 1164 | LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value |
| 1165 | AND option_group_payment_instrument.id = payment_instrument.option_group_id ) |
| 1166 | LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status') |
| 1167 | LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value |
| 1168 | AND option_group_contribution_status.id = contribution_status.option_group_id ) |
| 1169 | {$additionalClause} |
| 1170 | "; |
| 1171 | |
| 1172 | $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); |
| 1173 | |
| 1174 | while ($dao->fetch()) { |
| 1175 | $paymentDetails[$dao->id] = array( |
| 1176 | 'total_amount' => $dao->total_amount, |
| 1177 | 'contribution_status' => $dao->status, |
| 1178 | 'receive_date' => $dao->receive_date, |
| 1179 | 'pay_instru' => $dao->payment_instrument, |
| 1180 | 'trxn_id' => $dao->trxn_id, |
| 1181 | ); |
| 1182 | } |
| 1183 | |
| 1184 | return $paymentDetails; |
| 1185 | } |
| 1186 | |
| 1187 | /** |
| 1188 | * Function to create address associated with contribution record. |
| 1189 | * |
| 1190 | * @param array $params an associated array |
| 1191 | * @param $billingLocationTypeID |
| 1192 | * |
| 1193 | * @internal param int $billingID $billingLocationTypeID |
| 1194 | * |
| 1195 | * @return address id |
| 1196 | * @static |
| 1197 | */ |
| 1198 | static function createAddress(&$params, $billingLocationTypeID) { |
| 1199 | $billingFields = array( |
| 1200 | 'street_address', |
| 1201 | 'city', |
| 1202 | 'state_province_id', |
| 1203 | 'postal_code', |
| 1204 | 'country_id', |
| 1205 | ); |
| 1206 | |
| 1207 | //build address array |
| 1208 | $addressParams = array(); |
| 1209 | $addressParams['location_type_id'] = $billingLocationTypeID; |
| 1210 | $addressParams['is_billing'] = 1; |
| 1211 | |
| 1212 | $billingFirstName = CRM_Utils_Array::value('billing_first_name', $params); |
| 1213 | $billingMiddleName = CRM_Utils_Array::value('billing_middle_name', $params); |
| 1214 | $billingLastName = CRM_Utils_Array::value('billing_last_name', $params); |
| 1215 | $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingMiddleName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingLastName}"; |
| 1216 | |
| 1217 | foreach ($billingFields as $value) { |
| 1218 | $addressParams[$value] = CRM_Utils_Array::value("billing_{$value}-{$billingLocationTypeID}", $params); |
| 1219 | } |
| 1220 | |
| 1221 | $address = CRM_Core_BAO_Address::add($addressParams, FALSE); |
| 1222 | |
| 1223 | return $address->id; |
| 1224 | } |
| 1225 | |
| 1226 | /** |
| 1227 | * Delete billing address record related contribution |
| 1228 | * |
| 1229 | * @param null $contributionId |
| 1230 | * @param null $contactId |
| 1231 | * |
| 1232 | * @internal param int $contact_id contact id |
| 1233 | * @internal param int $contribution_id contributionId |
| 1234 | * @access public |
| 1235 | * @static |
| 1236 | */ |
| 1237 | static function deleteAddress($contributionId = NULL, $contactId = NULL) { |
| 1238 | $clauses = array(); |
| 1239 | $contactJoin = NULL; |
| 1240 | |
| 1241 | if ($contributionId) { |
| 1242 | $clauses[] = "cc.id = {$contributionId}"; |
| 1243 | } |
| 1244 | |
| 1245 | if ($contactId) { |
| 1246 | $clauses[] = "cco.id = {$contactId}"; |
| 1247 | $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id"; |
| 1248 | } |
| 1249 | |
| 1250 | if (empty($clauses)) { |
| 1251 | CRM_Core_Error::fatal(); |
| 1252 | } |
| 1253 | |
| 1254 | $condition = implode(' OR ', $clauses); |
| 1255 | |
| 1256 | $query = " |
| 1257 | SELECT ca.id |
| 1258 | FROM civicrm_address ca |
| 1259 | INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id |
| 1260 | $contactJoin |
| 1261 | WHERE $condition |
| 1262 | "; |
| 1263 | $dao = CRM_Core_DAO::executeQuery($query); |
| 1264 | |
| 1265 | while ($dao->fetch()) { |
| 1266 | $params = array('id' => $dao->id); |
| 1267 | CRM_Core_BAO_Block::blockDelete('Address', $params); |
| 1268 | } |
| 1269 | } |
| 1270 | |
| 1271 | /** |
| 1272 | * This function check online pending contribution associated w/ |
| 1273 | * Online Event Registration or Online Membership signup. |
| 1274 | * |
| 1275 | * @param int $componentId participant/membership id. |
| 1276 | * @param string $componentName Event/Membership. |
| 1277 | * |
| 1278 | * @return $contributionId pending contribution id. |
| 1279 | * @static |
| 1280 | */ |
| 1281 | static function checkOnlinePendingContribution($componentId, $componentName) { |
| 1282 | $contributionId = NULL; |
| 1283 | if (!$componentId || |
| 1284 | !in_array($componentName, array('Event', 'Membership')) |
| 1285 | ) { |
| 1286 | return $contributionId; |
| 1287 | } |
| 1288 | |
| 1289 | if ($componentName == 'Event') { |
| 1290 | $idName = 'participant_id'; |
| 1291 | $componentTable = 'civicrm_participant'; |
| 1292 | $paymentTable = 'civicrm_participant_payment'; |
| 1293 | $source = ts('Online Event Registration'); |
| 1294 | } |
| 1295 | |
| 1296 | if ($componentName == 'Membership') { |
| 1297 | $idName = 'membership_id'; |
| 1298 | $componentTable = 'civicrm_membership'; |
| 1299 | $paymentTable = 'civicrm_membership_payment'; |
| 1300 | $source = ts('Online Contribution'); |
| 1301 | } |
| 1302 | |
| 1303 | $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')); |
| 1304 | |
| 1305 | $query = " |
| 1306 | SELECT component.id as {$idName}, |
| 1307 | componentPayment.contribution_id as contribution_id, |
| 1308 | contribution.source source, |
| 1309 | contribution.contribution_status_id as contribution_status_id, |
| 1310 | contribution.is_pay_later as is_pay_later |
| 1311 | FROM $componentTable component |
| 1312 | LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id ) |
| 1313 | LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id ) |
| 1314 | WHERE component.id = {$componentId}"; |
| 1315 | |
| 1316 | $dao = CRM_Core_DAO::executeQuery($query); |
| 1317 | |
| 1318 | while ($dao->fetch()) { |
| 1319 | if ($dao->contribution_id && |
| 1320 | $dao->is_pay_later && |
| 1321 | $dao->contribution_status_id == $pendingStatusId && |
| 1322 | strpos($dao->source, $source) !== FALSE |
| 1323 | ) { |
| 1324 | $contributionId = $dao->contribution_id; |
| 1325 | $dao->free(); |
| 1326 | } |
| 1327 | } |
| 1328 | |
| 1329 | return $contributionId; |
| 1330 | } |
| 1331 | |
| 1332 | /** |
| 1333 | * This function update contribution as well as related objects. |
| 1334 | */ |
| 1335 | static function transitionComponents($params, $processContributionObject = FALSE) { |
| 1336 | // get minimum required values. |
| 1337 | $contactId = CRM_Utils_Array::value('contact_id', $params); |
| 1338 | $componentId = CRM_Utils_Array::value('component_id', $params); |
| 1339 | $componentName = CRM_Utils_Array::value('componentName', $params); |
| 1340 | $contributionId = CRM_Utils_Array::value('contribution_id', $params); |
| 1341 | $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params); |
| 1342 | |
| 1343 | // if we already processed contribution object pass previous status id. |
| 1344 | $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params); |
| 1345 | |
| 1346 | $updateResult = array(); |
| 1347 | |
| 1348 | $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
| 1349 | |
| 1350 | // we process only ( Completed, Cancelled, or Failed ) contributions. |
| 1351 | if (!$contributionId || |
| 1352 | !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses), |
| 1353 | array_search('Cancelled', $contributionStatuses), |
| 1354 | array_search('Failed', $contributionStatuses), |
| 1355 | )) |
| 1356 | ) { |
| 1357 | return $updateResult; |
| 1358 | } |
| 1359 | |
| 1360 | if (!$componentName || !$componentId) { |
| 1361 | // get the related component details. |
| 1362 | $componentDetails = self::getComponentDetails($contributionId); |
| 1363 | } |
| 1364 | else { |
| 1365 | $componentDetails['contact_id'] = $contactId; |
| 1366 | $componentDetails['component'] = $componentName; |
| 1367 | |
| 1368 | if ($componentName == 'event') { |
| 1369 | $componentDetails['participant'] = $componentId; |
| 1370 | } |
| 1371 | else { |
| 1372 | $componentDetails['membership'] = $componentId; |
| 1373 | } |
| 1374 | } |
| 1375 | |
| 1376 | if (!empty($componentDetails['contact_id'])) { |
| 1377 | $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', |
| 1378 | $contributionId, |
| 1379 | 'contact_id' |
| 1380 | ); |
| 1381 | } |
| 1382 | |
| 1383 | // do check for required ids. |
| 1384 | if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) || empty($componentDetails['contact_id'])) { |
| 1385 | return $updateResult; |
| 1386 | } |
| 1387 | |
| 1388 | //now we are ready w/ required ids, start processing. |
| 1389 | |
| 1390 | $baseIPN = new CRM_Core_Payment_BaseIPN(); |
| 1391 | |
| 1392 | $input = $ids = $objects = array(); |
| 1393 | |
| 1394 | $input['component'] = CRM_Utils_Array::value('component', $componentDetails); |
| 1395 | $ids['contribution'] = $contributionId; |
| 1396 | $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails); |
| 1397 | $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails); |
| 1398 | $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails); |
| 1399 | $ids['event'] = CRM_Utils_Array::value('event', $componentDetails); |
| 1400 | $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails); |
| 1401 | $ids['contributionRecur'] = NULL; |
| 1402 | $ids['contributionPage'] = NULL; |
| 1403 | |
| 1404 | if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) { |
| 1405 | CRM_Core_Error::fatal(); |
| 1406 | } |
| 1407 | |
| 1408 | $memberships = &$objects['membership']; |
| 1409 | $participant = &$objects['participant']; |
| 1410 | $pledgePayment = &$objects['pledge_payment']; |
| 1411 | $contribution = &$objects['contribution']; |
| 1412 | |
| 1413 | if ($pledgePayment) { |
| 1414 | $pledgePaymentIDs = array(); |
| 1415 | foreach ($pledgePayment as $key => $object) { |
| 1416 | $pledgePaymentIDs[] = $object->id; |
| 1417 | } |
| 1418 | $pledgeID = $pledgePayment[0]->pledge_id; |
| 1419 | } |
| 1420 | |
| 1421 | $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus(); |
| 1422 | |
| 1423 | if ($participant) { |
| 1424 | $participantStatuses = CRM_Event_PseudoConstant::participantStatus(); |
| 1425 | $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', |
| 1426 | $participant->id, |
| 1427 | 'status_id' |
| 1428 | ); |
| 1429 | } |
| 1430 | // we might want to process contribution object. |
| 1431 | $processContribution = FALSE; |
| 1432 | if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) { |
| 1433 | if (is_array($memberships)) { |
| 1434 | foreach ($memberships as $membership) { |
| 1435 | if ($membership) { |
| 1436 | $membership->status_id = array_search('Cancelled', $membershipStatuses); |
| 1437 | $membership->save(); |
| 1438 | |
| 1439 | $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; |
| 1440 | if ($processContributionObject) { |
| 1441 | $processContribution = TRUE; |
| 1442 | } |
| 1443 | } |
| 1444 | } |
| 1445 | } |
| 1446 | |
| 1447 | if ($participant) { |
| 1448 | $updatedStatusId = array_search('Cancelled', $participantStatuses); |
| 1449 | CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE); |
| 1450 | |
| 1451 | $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; |
| 1452 | if ($processContributionObject) { |
| 1453 | $processContribution = TRUE; |
| 1454 | } |
| 1455 | } |
| 1456 | |
| 1457 | if ($pledgePayment) { |
| 1458 | CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); |
| 1459 | |
| 1460 | $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; |
| 1461 | if ($processContributionObject) { |
| 1462 | $processContribution = TRUE; |
| 1463 | } |
| 1464 | } |
| 1465 | } |
| 1466 | elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) { |
| 1467 | if (is_array($memberships)) { |
| 1468 | foreach ($memberships as $membership) { |
| 1469 | if ($membership) { |
| 1470 | $membership->status_id = array_search('Expired', $membershipStatuses); |
| 1471 | $membership->save(); |
| 1472 | |
| 1473 | $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; |
| 1474 | if ($processContributionObject) { |
| 1475 | $processContribution = TRUE; |
| 1476 | } |
| 1477 | } |
| 1478 | } |
| 1479 | } |
| 1480 | if ($participant) { |
| 1481 | $updatedStatusId = array_search('Cancelled', $participantStatuses); |
| 1482 | CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE); |
| 1483 | |
| 1484 | $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; |
| 1485 | if ($processContributionObject) { |
| 1486 | $processContribution = TRUE; |
| 1487 | } |
| 1488 | } |
| 1489 | |
| 1490 | if ($pledgePayment) { |
| 1491 | CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); |
| 1492 | |
| 1493 | $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; |
| 1494 | if ($processContributionObject) { |
| 1495 | $processContribution = TRUE; |
| 1496 | } |
| 1497 | } |
| 1498 | } |
| 1499 | elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) { |
| 1500 | |
| 1501 | // only pending contribution related object processed. |
| 1502 | if ($previousContriStatusId && |
| 1503 | ($previousContriStatusId != array_search('Pending', $contributionStatuses)) |
| 1504 | ) { |
| 1505 | // this is case when we already processed contribution object. |
| 1506 | return $updateResult; |
| 1507 | } |
| 1508 | elseif (!$previousContriStatusId && |
| 1509 | $contribution->contribution_status_id != array_search('Pending', $contributionStatuses) |
| 1510 | ) { |
| 1511 | // this is case when we are going to process contribution object later. |
| 1512 | return $updateResult; |
| 1513 | } |
| 1514 | |
| 1515 | if (is_array($memberships)) { |
| 1516 | foreach ($memberships as $membership) { |
| 1517 | if ($membership) { |
| 1518 | $format = '%Y%m%d'; |
| 1519 | |
| 1520 | //CRM-4523 |
| 1521 | $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, |
| 1522 | $membership->membership_type_id, |
| 1523 | $membership->is_test, $membership->id |
| 1524 | ); |
| 1525 | |
| 1526 | // CRM-8141 update the membership type with the value recorded in log when membership created/renewed |
| 1527 | // this picks up membership type changes during renewals |
| 1528 | $sql = " |
| 1529 | SELECT membership_type_id |
| 1530 | FROM civicrm_membership_log |
| 1531 | WHERE membership_id=$membership->id |
| 1532 | ORDER BY id DESC |
| 1533 | LIMIT 1;"; |
| 1534 | $dao = new CRM_Core_DAO; |
| 1535 | $dao->query($sql); |
| 1536 | if ($dao->fetch()) { |
| 1537 | if (!empty($dao->membership_type_id)) { |
| 1538 | $membership->membership_type_id = $dao->membership_type_id; |
| 1539 | $membership->save(); |
| 1540 | } |
| 1541 | } |
| 1542 | // else fall back to using current membership type |
| 1543 | $dao->free(); |
| 1544 | |
| 1545 | // Figure out number of terms |
| 1546 | $numterms = 1; |
| 1547 | $lineitems = CRM_Price_BAO_LineItem::getLineItems($contributionId, 'contribution'); |
| 1548 | foreach ($lineitems as $lineitem) { |
| 1549 | if ($membership->membership_type_id == CRM_Utils_Array::value('membership_type_id', $lineitem)) { |
| 1550 | $numterms = CRM_Utils_Array::value('membership_num_terms', $lineitem); |
| 1551 | |
| 1552 | // in case membership_num_terms comes through as null or zero |
| 1553 | $numterms = $numterms >= 1 ? $numterms : 1; |
| 1554 | break; |
| 1555 | } |
| 1556 | } |
| 1557 | |
| 1558 | if ($currentMembership) { |
| 1559 | CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL); |
| 1560 | $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms); |
| 1561 | $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format); |
| 1562 | } |
| 1563 | else { |
| 1564 | $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $numterms); |
| 1565 | } |
| 1566 | |
| 1567 | //get the status for membership. |
| 1568 | $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], |
| 1569 | $dates['end_date'], |
| 1570 | $dates['join_date'], |
| 1571 | 'today', |
| 1572 | TRUE, |
| 1573 | $membership->membership_type_id, |
| 1574 | (array) $membership |
| 1575 | ); |
| 1576 | |
| 1577 | $formattedParams = array( |
| 1578 | 'status_id' => CRM_Utils_Array::value('id', $calcStatus, |
| 1579 | array_search('Current', $membershipStatuses) |
| 1580 | ), |
| 1581 | 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format), |
| 1582 | 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format), |
| 1583 | 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format), |
| 1584 | ); |
| 1585 | |
| 1586 | CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams); |
| 1587 | |
| 1588 | $membership->copyValues($formattedParams); |
| 1589 | $membership->save(); |
| 1590 | |
| 1591 | //updating the membership log |
| 1592 | $membershipLog = array(); |
| 1593 | $membershipLog = $formattedParams; |
| 1594 | $logStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format); |
| 1595 | $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date']; |
| 1596 | |
| 1597 | $membershipLog['start_date'] = $logStartDate; |
| 1598 | $membershipLog['membership_id'] = $membership->id; |
| 1599 | $membershipLog['modified_id'] = $membership->contact_id; |
| 1600 | $membershipLog['modified_date'] = date('Ymd'); |
| 1601 | $membershipLog['membership_type_id'] = $membership->membership_type_id; |
| 1602 | |
| 1603 | CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray); |
| 1604 | |
| 1605 | //update related Memberships. |
| 1606 | CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams); |
| 1607 | |
| 1608 | $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'], |
| 1609 | '%B %E%f, %Y' |
| 1610 | ); |
| 1611 | $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; |
| 1612 | if ($processContributionObject) { |
| 1613 | $processContribution = TRUE; |
| 1614 | } |
| 1615 | |
| 1616 | CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership); |
| 1617 | } |
| 1618 | } |
| 1619 | } |
| 1620 | |
| 1621 | if ($participant) { |
| 1622 | $updatedStatusId = array_search('Registered', $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 | |
| 1641 | // process contribution object. |
| 1642 | if ($processContribution) { |
| 1643 | $contributionParams = array(); |
| 1644 | $fields = array( |
| 1645 | 'contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id', |
| 1646 | 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id', |
| 1647 | 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number', |
| 1648 | ); |
| 1649 | foreach ($fields as $field) { |
| 1650 | if (empty($params[$field])) { |
| 1651 | continue; |
| 1652 | } |
| 1653 | $contributionParams[$field] = $params[$field]; |
| 1654 | } |
| 1655 | |
| 1656 | $ids = array('contribution' => $contributionId); |
| 1657 | $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids); |
| 1658 | } |
| 1659 | |
| 1660 | return $updateResult; |
| 1661 | } |
| 1662 | |
| 1663 | /** |
| 1664 | * This function returns all contribution related object ids. |
| 1665 | */ |
| 1666 | public static function getComponentDetails($contributionId) { |
| 1667 | $componentDetails = $pledgePayment = array(); |
| 1668 | if (!$contributionId) { |
| 1669 | return $componentDetails; |
| 1670 | } |
| 1671 | |
| 1672 | $query = " |
| 1673 | SELECT c.id as contribution_id, |
| 1674 | c.contact_id as contact_id, |
| 1675 | mp.membership_id as membership_id, |
| 1676 | m.membership_type_id as membership_type_id, |
| 1677 | pp.participant_id as participant_id, |
| 1678 | p.event_id as event_id, |
| 1679 | pgp.id as pledge_payment_id |
| 1680 | FROM civicrm_contribution c |
| 1681 | LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id |
| 1682 | LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id |
| 1683 | LEFT JOIN civicrm_participant p ON pp.participant_id = p.id |
| 1684 | LEFT JOIN civicrm_membership m ON m.id = mp.membership_id |
| 1685 | LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id |
| 1686 | WHERE c.id = $contributionId"; |
| 1687 | |
| 1688 | $dao = CRM_Core_DAO::executeQuery($query); |
| 1689 | $componentDetails = array(); |
| 1690 | |
| 1691 | while ($dao->fetch()) { |
| 1692 | $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute'; |
| 1693 | $componentDetails['contact_id'] = $dao->contact_id; |
| 1694 | if ($dao->event_id) { |
| 1695 | $componentDetails['event'] = $dao->event_id; |
| 1696 | } |
| 1697 | if ($dao->participant_id) { |
| 1698 | $componentDetails['participant'] = $dao->participant_id; |
| 1699 | } |
| 1700 | if ($dao->membership_id) { |
| 1701 | if (!isset($componentDetails['membership'])) { |
| 1702 | $componentDetails['membership'] = $componentDetails['membership_type'] = array(); |
| 1703 | } |
| 1704 | $componentDetails['membership'][] = $dao->membership_id; |
| 1705 | $componentDetails['membership_type'][] = $dao->membership_type_id; |
| 1706 | } |
| 1707 | if ($dao->pledge_payment_id) { |
| 1708 | $pledgePayment[] = $dao->pledge_payment_id; |
| 1709 | } |
| 1710 | } |
| 1711 | |
| 1712 | if ($pledgePayment) { |
| 1713 | $componentDetails['pledge_payment'] = $pledgePayment; |
| 1714 | } |
| 1715 | |
| 1716 | return $componentDetails; |
| 1717 | } |
| 1718 | |
| 1719 | /** |
| 1720 | * @param $contactId |
| 1721 | * @param bool $includeSoftCredit |
| 1722 | * |
| 1723 | * @return null|string |
| 1724 | */ |
| 1725 | static function contributionCount($contactId, $includeSoftCredit = TRUE) { |
| 1726 | if (!$contactId) { |
| 1727 | return 0; |
| 1728 | } |
| 1729 | |
| 1730 | $contactContributionsSQL = " |
| 1731 | SELECT contribution.id AS id |
| 1732 | FROM civicrm_contribution contribution |
| 1733 | WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} "; |
| 1734 | |
| 1735 | $contactSoftCreditContributionsSQL = " |
| 1736 | SELECT contribution.id |
| 1737 | FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution |
| 1738 | ON ( contribution.id = softContribution.contribution_id ) |
| 1739 | WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} "; |
| 1740 | $query = "SELECT count( x.id ) count FROM ( "; |
| 1741 | $query .= $contactContributionsSQL; |
| 1742 | |
| 1743 | if ($includeSoftCredit) { |
| 1744 | $query .= " UNION "; |
| 1745 | $query .= $contactSoftCreditContributionsSQL; |
| 1746 | } |
| 1747 | |
| 1748 | $query .= ") x"; |
| 1749 | |
| 1750 | return CRM_Core_DAO::singleValueQuery($query); |
| 1751 | } |
| 1752 | |
| 1753 | /** |
| 1754 | * Function to get individual id for onbehalf contribution |
| 1755 | * |
| 1756 | * @param int $contributionId contribution id |
| 1757 | * @param int $contributorId contributor id |
| 1758 | * |
| 1759 | * @return array $ids containing organization id and individual id |
| 1760 | * @access public |
| 1761 | */ |
| 1762 | static function getOnbehalfIds($contributionId, $contributorId = NULL) { |
| 1763 | |
| 1764 | $ids = array(); |
| 1765 | |
| 1766 | if (!$contributionId) { |
| 1767 | return $ids; |
| 1768 | } |
| 1769 | |
| 1770 | // fetch contributor id if null |
| 1771 | if (!$contributorId) { |
| 1772 | $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', |
| 1773 | $contributionId, 'contact_id' |
| 1774 | ); |
| 1775 | } |
| 1776 | |
| 1777 | $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name'); |
| 1778 | $activityTypeId = array_search('Contribution', $activityTypeIds); |
| 1779 | |
| 1780 | if ($activityTypeId && $contributorId) { |
| 1781 | $activityQuery = " |
| 1782 | SELECT civicrm_activity_contact.contact_id |
| 1783 | FROM civicrm_activity_contact |
| 1784 | INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id |
| 1785 | WHERE civicrm_activity.activity_type_id = %1 |
| 1786 | AND civicrm_activity.source_record_id = %2 |
| 1787 | AND civicrm_activity_contact.record_type_id = %3 |
| 1788 | "; |
| 1789 | |
| 1790 | $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); |
| 1791 | $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); |
| 1792 | |
| 1793 | $params = array( |
| 1794 | 1 => array($activityTypeId, 'Integer'), |
| 1795 | 2 => array($contributionId, 'Integer'), |
| 1796 | 3 => array($sourceID, 'Integer'), |
| 1797 | ); |
| 1798 | |
| 1799 | $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params); |
| 1800 | |
| 1801 | // for on behalf contribution source is individual and contributor is organization |
| 1802 | if ($sourceContactId && $sourceContactId != $contributorId) { |
| 1803 | $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name'); |
| 1804 | // get rel type id for employee of relation |
| 1805 | foreach ($relationshipTypeIds as $id => $typeVals) { |
| 1806 | if ($typeVals['name_a_b'] == 'Employee of') { |
| 1807 | $relationshipTypeId = $id; |
| 1808 | break; |
| 1809 | } |
| 1810 | } |
| 1811 | |
| 1812 | $rel = new CRM_Contact_DAO_Relationship(); |
| 1813 | $rel->relationship_type_id = $relationshipTypeId; |
| 1814 | $rel->contact_id_a = $sourceContactId; |
| 1815 | $rel->contact_id_b = $contributorId; |
| 1816 | if ($rel->find(TRUE)) { |
| 1817 | $ids['individual_id'] = $rel->contact_id_a; |
| 1818 | $ids['organization_id'] = $rel->contact_id_b; |
| 1819 | } |
| 1820 | } |
| 1821 | } |
| 1822 | |
| 1823 | return $ids; |
| 1824 | } |
| 1825 | |
| 1826 | /** |
| 1827 | * @return array |
| 1828 | * @static |
| 1829 | */ |
| 1830 | static function getContributionDates() { |
| 1831 | $config = CRM_Core_Config::singleton(); |
| 1832 | $currentMonth = date('m'); |
| 1833 | $currentDay = date('d'); |
| 1834 | if ((int ) $config->fiscalYearStart['M'] > $currentMonth || |
| 1835 | ((int ) $config->fiscalYearStart['M'] == $currentMonth && |
| 1836 | (int ) $config->fiscalYearStart['d'] > $currentDay |
| 1837 | ) |
| 1838 | ) { |
| 1839 | $year = date('Y') - 1; |
| 1840 | } |
| 1841 | else { |
| 1842 | $year = date('Y'); |
| 1843 | } |
| 1844 | $year = array('Y' => $year); |
| 1845 | $yearDate = $config->fiscalYearStart; |
| 1846 | $yearDate = array_merge($year, $yearDate); |
| 1847 | $yearDate = CRM_Utils_Date::format($yearDate); |
| 1848 | |
| 1849 | $monthDate = date('Ym') . '01'; |
| 1850 | |
| 1851 | $now = date('Ymd'); |
| 1852 | |
| 1853 | return array( |
| 1854 | 'now' => $now, |
| 1855 | 'yearDate' => $yearDate, |
| 1856 | 'monthDate' => $monthDate, |
| 1857 | ); |
| 1858 | } |
| 1859 | |
| 1860 | /* |
| 1861 | * Load objects relations to contribution object |
| 1862 | * Objects are stored in the $_relatedObjects property |
| 1863 | * In the first instance we are just moving functionality from BASEIpn - |
| 1864 | * see http://issues.civicrm.org/jira/browse/CRM-9996 |
| 1865 | * |
| 1866 | * @param array $input Input as delivered from Payment Processor |
| 1867 | * @param array $ids Ids as Loaded by Payment Processor |
| 1868 | * @param boolean $required Is Payment processor / contribution page required |
| 1869 | * @param boolean $loadAll - load all related objects - even where id not passed in? (allows API to call this) |
| 1870 | * Note that the unit test for the BaseIPN class tests this function |
| 1871 | */ |
| 1872 | /** |
| 1873 | * @param $input |
| 1874 | * @param $ids |
| 1875 | * @param bool $required |
| 1876 | * @param bool $loadAll |
| 1877 | * |
| 1878 | * @return bool |
| 1879 | * @throws Exception |
| 1880 | */ |
| 1881 | function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false) { |
| 1882 | if($loadAll){ |
| 1883 | $ids = array_merge($this->getComponentDetails($this->id),$ids); |
| 1884 | if(empty($ids['contact']) && isset($this->contact_id)){ |
| 1885 | $ids['contact'] = $this->contact_id; |
| 1886 | } |
| 1887 | } |
| 1888 | if (empty($this->_component)) { |
| 1889 | if (! empty($ids['event'])) { |
| 1890 | $this->_component = 'event'; |
| 1891 | } |
| 1892 | else { |
| 1893 | $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute')); |
| 1894 | } |
| 1895 | } |
| 1896 | $paymentProcessorID = CRM_Utils_Array::value('paymentProcessor', $ids); |
| 1897 | $contributionType = new CRM_Financial_BAO_FinancialType(); |
| 1898 | $contributionType->id = $this->financial_type_id; |
| 1899 | if (!$contributionType->find(TRUE)) { |
| 1900 | throw new Exception("Could not find financial type record: " . $this->financial_type_id); |
| 1901 | } |
| 1902 | if (!empty($ids['contact'])) { |
| 1903 | $this->_relatedObjects['contact'] = new CRM_Contact_BAO_Contact(); |
| 1904 | $this->_relatedObjects['contact']->id = $ids['contact']; |
| 1905 | $this->_relatedObjects['contact']->find(TRUE); |
| 1906 | } |
| 1907 | $this->_relatedObjects['contributionType'] = $contributionType; |
| 1908 | |
| 1909 | if ($this->_component == 'contribute') { |
| 1910 | // retrieve the other optional objects first so |
| 1911 | // stuff down the line can use this info and do things |
| 1912 | // CRM-6056 |
| 1913 | //in any case get the memberships associated with the contribution |
| 1914 | //because we now support multiple memberships w/ price set |
| 1915 | // see if there are any other memberships to be considered for same contribution. |
| 1916 | $query = " |
| 1917 | SELECT membership_id |
| 1918 | FROM civicrm_membership_payment |
| 1919 | WHERE contribution_id = %1 "; |
| 1920 | $params = array(1 => array($this->id, 'Integer')); |
| 1921 | |
| 1922 | $dao = CRM_Core_DAO::executeQuery($query, $params ); |
| 1923 | while ($dao->fetch()) { |
| 1924 | if ($dao->membership_id) { |
| 1925 | if (!is_array($ids['membership'])) { |
| 1926 | $ids['membership'] = array(); |
| 1927 | } |
| 1928 | $ids['membership'][] = $dao->membership_id; |
| 1929 | } |
| 1930 | } |
| 1931 | |
| 1932 | if (array_key_exists('membership', $ids) && is_array($ids['membership'])) { |
| 1933 | foreach ($ids['membership'] as $id) { |
| 1934 | if (!empty($id)) { |
| 1935 | $membership = new CRM_Member_BAO_Membership(); |
| 1936 | $membership->id = $id; |
| 1937 | if (!$membership->find(TRUE)) { |
| 1938 | throw new Exception("Could not find membership record: $id"); |
| 1939 | } |
| 1940 | $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date); |
| 1941 | $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date); |
| 1942 | $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date); |
| 1943 | $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership; |
| 1944 | $membership->free(); |
| 1945 | } |
| 1946 | } |
| 1947 | } |
| 1948 | |
| 1949 | if (!empty($ids['pledge_payment'])) { |
| 1950 | |
| 1951 | foreach ($ids['pledge_payment'] as $key => $paymentID) { |
| 1952 | if (empty($paymentID)) { |
| 1953 | continue; |
| 1954 | } |
| 1955 | $payment = new CRM_Pledge_BAO_PledgePayment(); |
| 1956 | $payment->id = $paymentID; |
| 1957 | if (!$payment->find(TRUE)) { |
| 1958 | throw new Exception("Could not find pledge payment record: " . $paymentID); |
| 1959 | } |
| 1960 | $this->_relatedObjects['pledge_payment'][] = $payment; |
| 1961 | } |
| 1962 | } |
| 1963 | |
| 1964 | if (!empty($ids['contributionRecur'])) { |
| 1965 | $recur = new CRM_Contribute_BAO_ContributionRecur(); |
| 1966 | $recur->id = $ids['contributionRecur']; |
| 1967 | if (!$recur->find(TRUE)) { |
| 1968 | throw new Exception("Could not find recur record: " . $ids['contributionRecur']); |
| 1969 | } |
| 1970 | $this->_relatedObjects['contributionRecur'] = &$recur; |
| 1971 | //get payment processor id from recur object. |
| 1972 | $paymentProcessorID = $recur->payment_processor_id; |
| 1973 | } |
| 1974 | //for normal contribution get the payment processor id. |
| 1975 | if (!$paymentProcessorID) { |
| 1976 | if ($this->contribution_page_id) { |
| 1977 | // get the payment processor id from contribution page |
| 1978 | $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', |
| 1979 | $this->contribution_page_id, |
| 1980 | 'payment_processor' |
| 1981 | ); |
| 1982 | } |
| 1983 | //fail to load payment processor id. |
| 1984 | elseif (empty($ids['pledge_payment'])) { |
| 1985 | $loadObjectSuccess = TRUE; |
| 1986 | if ($required) { |
| 1987 | throw new Exception("Could not find contribution page for contribution record: " . $this->id); |
| 1988 | } |
| 1989 | return $loadObjectSuccess; |
| 1990 | } |
| 1991 | } |
| 1992 | } |
| 1993 | else { |
| 1994 | // we are in event mode |
| 1995 | // make sure event exists and is valid |
| 1996 | $event = new CRM_Event_BAO_Event(); |
| 1997 | $event->id = $ids['event']; |
| 1998 | if ($ids['event'] && |
| 1999 | !$event->find(TRUE) |
| 2000 | ) { |
| 2001 | throw new Exception("Could not find event: " . $ids['event']); |
| 2002 | } |
| 2003 | |
| 2004 | $this->_relatedObjects['event'] = &$event; |
| 2005 | |
| 2006 | $participant = new CRM_Event_BAO_Participant(); |
| 2007 | $participant->id = $ids['participant']; |
| 2008 | if ($ids['participant'] && |
| 2009 | !$participant->find(TRUE) |
| 2010 | ) { |
| 2011 | throw new Exception("Could not find participant: " . $ids['participant']); |
| 2012 | } |
| 2013 | $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date); |
| 2014 | |
| 2015 | $this->_relatedObjects['participant'] = &$participant; |
| 2016 | |
| 2017 | if (!$paymentProcessorID) { |
| 2018 | $paymentProcessorID = $this->_relatedObjects['event']->payment_processor; |
| 2019 | } |
| 2020 | } |
| 2021 | |
| 2022 | $loadObjectSuccess = TRUE; |
| 2023 | if ($paymentProcessorID) { |
| 2024 | $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID, |
| 2025 | $this->is_test ? 'test' : 'live' |
| 2026 | ); |
| 2027 | $ids['paymentProcessor'] = $paymentProcessorID; |
| 2028 | $this->_relatedObjects['paymentProcessor'] = &$paymentProcessor; |
| 2029 | } |
| 2030 | elseif ($required) { |
| 2031 | $loadObjectSuccess = FALSE; |
| 2032 | throw new Exception("Could not find payment processor for contribution record: " . $this->id); |
| 2033 | } |
| 2034 | |
| 2035 | return $loadObjectSuccess; |
| 2036 | } |
| 2037 | |
| 2038 | /* |
| 2039 | * Create array of message information - ie. return html version, txt version, to field |
| 2040 | * |
| 2041 | * @param array $input incoming information |
| 2042 | * - is_recur - should this be treated as recurring (not sure why you wouldn't |
| 2043 | * just check presence of recur object but maintaining legacy approach |
| 2044 | * to be careful) |
| 2045 | * @param array $ids IDs of related objects |
| 2046 | * @param array $values any values that may have already been compiled by calling process |
| 2047 | * This is augmented by values 'gathered' by gatherMessageValues |
| 2048 | * @param bool $returnMessageText distinguishes between whether to send message or return |
| 2049 | * message text. We are working towards this function ALWAYS returning message text & calling |
| 2050 | * function doing emails / pdfs with it |
| 2051 | * @return array $messageArray - messages |
| 2052 | */ |
| 2053 | /** |
| 2054 | * @param $input |
| 2055 | * @param $ids |
| 2056 | * @param $values |
| 2057 | * @param bool $recur |
| 2058 | * @param bool $returnMessageText |
| 2059 | * |
| 2060 | * @throws Exception |
| 2061 | */ |
| 2062 | function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) { |
| 2063 | if (empty($this->_relatedObjects)) { |
| 2064 | $this->loadRelatedObjects($input, $ids); |
| 2065 | } |
| 2066 | if (empty($this->_component)) { |
| 2067 | $this->_component = CRM_Utils_Array::value('component', $input); |
| 2068 | } |
| 2069 | |
| 2070 | //not really sure what params might be passed in but lets merge em into values |
| 2071 | $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values); |
| 2072 | $template = CRM_Core_Smarty::singleton(); |
| 2073 | $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText); |
| 2074 | //what does recur 'mean here - to do with payment processor return functionality but |
| 2075 | // what is the importance |
| 2076 | if ($recur && !empty($this->_relatedObjects['paymentProcessor'])) { |
| 2077 | $paymentObject = &CRM_Core_Payment::singleton( |
| 2078 | $this->is_test ? 'test' : 'live', |
| 2079 | $this->_relatedObjects['paymentProcessor'] |
| 2080 | ); |
| 2081 | |
| 2082 | $entityID = $entity = NULL; |
| 2083 | if (isset($ids['contribution'])) { |
| 2084 | $entity = 'contribution'; |
| 2085 | $entityID = $ids['contribution']; |
| 2086 | } |
| 2087 | if (isset($ids['membership']) && $ids['membership']) { |
| 2088 | $entity = 'membership'; |
| 2089 | $entityID = $ids['membership']; |
| 2090 | } |
| 2091 | |
| 2092 | $url = $paymentObject->subscriptionURL($entityID, $entity); |
| 2093 | $template->assign('cancelSubscriptionUrl', $url); |
| 2094 | |
| 2095 | $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing'); |
| 2096 | $template->assign('updateSubscriptionBillingUrl', $url); |
| 2097 | |
| 2098 | $url = $paymentObject->subscriptionURL($entityID, $entity, 'update'); |
| 2099 | $template->assign('updateSubscriptionUrl', $url); |
| 2100 | |
| 2101 | if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) { |
| 2102 | //direct mode showing billing block, so use directIPN for temporary |
| 2103 | $template->assign('contributeMode', 'directIPN'); |
| 2104 | } |
| 2105 | } |
| 2106 | // todo remove strtolower - check consistency |
| 2107 | if (strtolower($this->_component) == 'event') { |
| 2108 | return CRM_Event_BAO_Event::sendMail($ids['contact'], $values, |
| 2109 | $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText |
| 2110 | ); |
| 2111 | } |
| 2112 | else { |
| 2113 | $values['contribution_id'] = $this->id; |
| 2114 | if (!empty($ids['related_contact'])) { |
| 2115 | $values['related_contact'] = $ids['related_contact']; |
| 2116 | if (isset($ids['onbehalf_dupe_alert'])) { |
| 2117 | $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert']; |
| 2118 | } |
| 2119 | $entityBlock = array( |
| 2120 | 'contact_id' => $ids['contact'], |
| 2121 | 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', |
| 2122 | 'Home', 'id', 'name' |
| 2123 | ), |
| 2124 | ); |
| 2125 | $address = CRM_Core_BAO_Address::getValues($entityBlock); |
| 2126 | $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']); |
| 2127 | } |
| 2128 | $isTest = FALSE; |
| 2129 | if ($this->is_test) { |
| 2130 | $isTest = TRUE; |
| 2131 | } |
| 2132 | if (!empty($this->_relatedObjects['membership'])) { |
| 2133 | foreach ($this->_relatedObjects['membership'] as $membership) { |
| 2134 | if ($membership->id) { |
| 2135 | $values['membership_id'] = $membership->id; |
| 2136 | |
| 2137 | // need to set the membership values here |
| 2138 | $template->assign('membership_assign', 1); |
| 2139 | $template->assign('membership_name', |
| 2140 | CRM_Member_PseudoConstant::membershipType($membership->membership_type_id) |
| 2141 | ); |
| 2142 | $template->assign('mem_start_date', $membership->start_date); |
| 2143 | $template->assign('mem_join_date', $membership->join_date); |
| 2144 | $template->assign('mem_end_date', $membership->end_date); |
| 2145 | $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label'); |
| 2146 | $template->assign('mem_status', $membership_status); |
| 2147 | if ($membership_status == 'Pending' && $membership->is_pay_later == 1) { |
| 2148 | $template->assign('is_pay_later', 1); |
| 2149 | } |
| 2150 | |
| 2151 | // if separate payment there are two contributions recorded and the |
| 2152 | // admin will need to send a receipt for each of them separately. |
| 2153 | // we dont link the two in the db (but can potentially infer it if needed) |
| 2154 | $template->assign('is_separate_payment', 0); |
| 2155 | |
| 2156 | if ($recur && $paymentObject) { |
| 2157 | $url = $paymentObject->subscriptionURL($membership->id, 'membership'); |
| 2158 | $template->assign('cancelSubscriptionUrl', $url); |
| 2159 | $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing'); |
| 2160 | $template->assign('updateSubscriptionBillingUrl', $url); |
| 2161 | $url = $paymentObject->subscriptionURL($entityID, $entity, 'update'); |
| 2162 | $template->assign('updateSubscriptionUrl', $url); |
| 2163 | } |
| 2164 | |
| 2165 | $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText); |
| 2166 | |
| 2167 | return $result; |
| 2168 | // otherwise if its about sending emails, continue sending without return, as we |
| 2169 | // don't want to exit the loop. |
| 2170 | } |
| 2171 | } |
| 2172 | } |
| 2173 | else { |
| 2174 | return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText); |
| 2175 | } |
| 2176 | } |
| 2177 | } |
| 2178 | |
| 2179 | /* |
| 2180 | * Gather values for contribution mail - this function has been created |
| 2181 | * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function |
| 2182 | * Values related to the contribution in question are gathered |
| 2183 | * |
| 2184 | * @param array $input input into function (probably from payment processor) |
| 2185 | * @param array $ids the set of ids related to the inpurt |
| 2186 | * |
| 2187 | * @return array $values |
| 2188 | * |
| 2189 | * NB don't add direct calls to the function as we intend to change the signature |
| 2190 | */ |
| 2191 | /** |
| 2192 | * @param $input |
| 2193 | * @param $values |
| 2194 | * @param array $ids |
| 2195 | * |
| 2196 | * @return mixed |
| 2197 | */ |
| 2198 | function _gatherMessageValues($input, &$values, $ids = array()) { |
| 2199 | // set display address of contributor |
| 2200 | if ($this->address_id) { |
| 2201 | $addressParams = array('id' => $this->address_id); |
| 2202 | $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id'); |
| 2203 | $addressDetails = array_values($addressDetails); |
| 2204 | $values['address'] = $addressDetails[0]['display']; |
| 2205 | } |
| 2206 | if ($this->_component == 'contribute') { |
| 2207 | if (isset($this->contribution_page_id)) { |
| 2208 | CRM_Contribute_BAO_ContributionPage::setValues( |
| 2209 | $this->contribution_page_id, |
| 2210 | $values |
| 2211 | ); |
| 2212 | if ($this->contribution_page_id) { |
| 2213 | // CRM-8254 - override default currency if applicable |
| 2214 | $config = CRM_Core_Config::singleton(); |
| 2215 | $config->defaultCurrency = CRM_Utils_Array::value( |
| 2216 | 'currency', |
| 2217 | $values, |
| 2218 | $config->defaultCurrency |
| 2219 | ); |
| 2220 | } |
| 2221 | } |
| 2222 | // no contribution page -probably back office |
| 2223 | else { |
| 2224 | // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id) |
| 2225 | $values['is_email_receipt'] = 1; |
| 2226 | $values['title'] = 'Contribution'; |
| 2227 | } |
| 2228 | // set lineItem for contribution |
| 2229 | if ($this->id) { |
| 2230 | $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->id, 'contribution', 1); |
| 2231 | if (!empty($lineItem)) { |
| 2232 | $itemId = key($lineItem); |
| 2233 | foreach ($lineItem as &$eachItem) { |
| 2234 | if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership']) ) { |
| 2235 | $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date); |
| 2236 | $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date); |
| 2237 | $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date); |
| 2238 | } |
| 2239 | } |
| 2240 | $values['lineItem'][0] = $lineItem; |
| 2241 | $values['priceSetID'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id'); |
| 2242 | } |
| 2243 | } |
| 2244 | |
| 2245 | $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds( |
| 2246 | $this->id, |
| 2247 | $this->contact_id |
| 2248 | ); |
| 2249 | // if this is onbehalf of contribution then set related contact |
| 2250 | if (!empty($relatedContact['individual_id'])) { |
| 2251 | $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id']; |
| 2252 | } |
| 2253 | } |
| 2254 | else { |
| 2255 | // event |
| 2256 | $eventParams = array( |
| 2257 | 'id' => $this->_relatedObjects['event']->id, |
| 2258 | ); |
| 2259 | $values['event'] = array(); |
| 2260 | |
| 2261 | CRM_Event_BAO_Event::retrieve($eventParams, $values['event']); |
| 2262 | |
| 2263 | //get location details |
| 2264 | $locationParams = array( |
| 2265 | 'entity_id' => $this->_relatedObjects['event']->id, |
| 2266 | 'entity_table' => 'civicrm_event', |
| 2267 | ); |
| 2268 | $values['location'] = CRM_Core_BAO_Location::getValues($locationParams); |
| 2269 | |
| 2270 | $ufJoinParams = array( |
| 2271 | 'entity_table' => 'civicrm_event', |
| 2272 | 'entity_id' => $ids['event'], |
| 2273 | 'module' => 'CiviEvent', |
| 2274 | ); |
| 2275 | |
| 2276 | list($custom_pre_id, |
| 2277 | $custom_post_ids |
| 2278 | ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); |
| 2279 | |
| 2280 | $values['custom_pre_id'] = $custom_pre_id; |
| 2281 | $values['custom_post_id'] = $custom_post_ids; |
| 2282 | |
| 2283 | // set lineItem for event contribution |
| 2284 | if ($this->id) { |
| 2285 | $participantIds = CRM_Event_BAO_Participant::getParticipantIds($this->id); |
| 2286 | if (!empty($participantIds)) { |
| 2287 | foreach ($participantIds as $pIDs) { |
| 2288 | $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs); |
| 2289 | if (!CRM_Utils_System::isNull($lineItem)) { |
| 2290 | $values['lineItem'][] = $lineItem; |
| 2291 | } |
| 2292 | } |
| 2293 | } |
| 2294 | } |
| 2295 | } |
| 2296 | |
| 2297 | return $values; |
| 2298 | } |
| 2299 | |
| 2300 | /** |
| 2301 | * Apply variables for message to smarty template - this function is part of analysing what is in the huge |
| 2302 | * function & breaking it down into manageable chunks. Eventually it will be refactored into something else |
| 2303 | * Note we send directly from this function in some cases because it is only partly refactored |
| 2304 | * Don't call this function directly as the signature will change |
| 2305 | */ |
| 2306 | function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = True) { |
| 2307 | $template->assign('first_name', $this->_relatedObjects['contact']->first_name); |
| 2308 | $template->assign('last_name', $this->_relatedObjects['contact']->last_name); |
| 2309 | $template->assign('displayName', $this->_relatedObjects['contact']->display_name); |
| 2310 | if (!empty($values['lineItem']) && !empty($this->_relatedObjects['membership'])) { |
| 2311 | $template->assign('useForMember', true); |
| 2312 | } |
| 2313 | //assign honor infomation to receiptmessage |
| 2314 | $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id); |
| 2315 | |
| 2316 | if (isset($softRecord['soft_credit'])) { |
| 2317 | //if id of contribution page is present |
| 2318 | if (!empty($values['id'])) { |
| 2319 | $values['honor'] = array( |
| 2320 | 'honor_profile_values' => array(), |
| 2321 | 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'), |
| 2322 | 'honor_id' => $softRecord['soft_credit'][1]['contact_id'], |
| 2323 | ); |
| 2324 | $softCreditTypes = CRM_Core_OptionGroup::values('soft_credit_type'); |
| 2325 | |
| 2326 | $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']); |
| 2327 | $template->assign('honor_block_is_active', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id')); |
| 2328 | } |
| 2329 | else { |
| 2330 | //offline contribution |
| 2331 | $softCreditTypes = $softCredits = array(); |
| 2332 | foreach ($softRecord['soft_credit'] as $key => $softCredit) { |
| 2333 | $softCreditTypes[$key] = $softCredit['soft_credit_type_label']; |
| 2334 | $softCredits[$key] = array( |
| 2335 | 'Name' => $softCredit['contact_name'], |
| 2336 | 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']) |
| 2337 | ); |
| 2338 | } |
| 2339 | $template->assign('softCreditTypes', $softCreditTypes); |
| 2340 | $template->assign('softCredits', $softCredits); |
| 2341 | } |
| 2342 | } |
| 2343 | |
| 2344 | $dao = new CRM_Contribute_DAO_ContributionProduct(); |
| 2345 | $dao->contribution_id = $this->id; |
| 2346 | if ($dao->find(TRUE)) { |
| 2347 | $premiumId = $dao->product_id; |
| 2348 | $template->assign('option', $dao->product_option); |
| 2349 | |
| 2350 | $productDAO = new CRM_Contribute_DAO_Product(); |
| 2351 | $productDAO->id = $premiumId; |
| 2352 | $productDAO->find(TRUE); |
| 2353 | $template->assign('selectPremium', TRUE); |
| 2354 | $template->assign('product_name', $productDAO->name); |
| 2355 | $template->assign('price', $productDAO->price); |
| 2356 | $template->assign('sku', $productDAO->sku); |
| 2357 | } |
| 2358 | $template->assign('title', CRM_Utils_Array::value('title',$values)); |
| 2359 | $amount = CRM_Utils_Array::value('total_amount', $input,(CRM_Utils_Array::value('amount', $input)),null); |
| 2360 | if(empty($amount) && isset($this->total_amount)){ |
| 2361 | $amount = $this->total_amount; |
| 2362 | } |
| 2363 | $template->assign('amount', $amount); |
| 2364 | // add the new contribution values |
| 2365 | if (strtolower($this->_component) == 'contribute') { |
| 2366 | //PCP Info |
| 2367 | $softDAO = new CRM_Contribute_DAO_ContributionSoft(); |
| 2368 | $softDAO->contribution_id = $this->id; |
| 2369 | if ($softDAO->find(TRUE)) { |
| 2370 | $template->assign('pcpBlock', TRUE); |
| 2371 | $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll); |
| 2372 | $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname); |
| 2373 | $template->assign('pcp_personal_note', $softDAO->pcp_personal_note); |
| 2374 | |
| 2375 | //assign the pcp page title for email subject |
| 2376 | $pcpDAO = new CRM_PCP_DAO_PCP(); |
| 2377 | $pcpDAO->id = $softDAO->pcp_id; |
| 2378 | if ($pcpDAO->find(TRUE)) { |
| 2379 | $template->assign('title', $pcpDAO->title); |
| 2380 | } |
| 2381 | } |
| 2382 | } |
| 2383 | |
| 2384 | if ($this->financial_type_id) { |
| 2385 | $values['financial_type_id'] = $this->financial_type_id; |
| 2386 | } |
| 2387 | |
| 2388 | |
| 2389 | $template->assign('trxn_id', $this->trxn_id); |
| 2390 | $template->assign('receive_date', |
| 2391 | CRM_Utils_Date::mysqlToIso($this->receive_date) |
| 2392 | ); |
| 2393 | $template->assign('contributeMode', 'notify'); |
| 2394 | $template->assign('action', $this->is_test ? 1024 : 1); |
| 2395 | $template->assign('receipt_text', |
| 2396 | CRM_Utils_Array::value('receipt_text', |
| 2397 | $values |
| 2398 | ) |
| 2399 | ); |
| 2400 | $template->assign('is_monetary', 1); |
| 2401 | $template->assign('is_recur', (bool) $recur); |
| 2402 | $template->assign('currency', $this->currency); |
| 2403 | $template->assign('address', CRM_Utils_Address::format($input)); |
| 2404 | if ($this->_component == 'event') { |
| 2405 | $template->assign('title', $values['event']['title']); |
| 2406 | $participantRoles = CRM_Event_PseudoConstant::participantRole(); |
| 2407 | $viewRoles = array(); |
| 2408 | foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) { |
| 2409 | $viewRoles[] = $participantRoles[$v]; |
| 2410 | } |
| 2411 | $values['event']['participant_role'] = implode(', ', $viewRoles); |
| 2412 | $template->assign('event', $values['event']); |
| 2413 | $template->assign('location', $values['location']); |
| 2414 | $template->assign('customPre', $values['custom_pre_id']); |
| 2415 | $template->assign('customPost', $values['custom_post_id']); |
| 2416 | |
| 2417 | $isTest = FALSE; |
| 2418 | if ($this->_relatedObjects['participant']->is_test) { |
| 2419 | $isTest = TRUE; |
| 2420 | } |
| 2421 | |
| 2422 | $values['params'] = array(); |
| 2423 | //to get email of primary participant. |
| 2424 | $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id'); |
| 2425 | $primaryAmount[] = array('label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects['participant']->fee_amount); |
| 2426 | //build an array of cId/pId of participants |
| 2427 | $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE); |
| 2428 | unset($additionalIDs[$this->_relatedObjects['participant']->id]); |
| 2429 | //send receipt to additional participant if exists |
| 2430 | if (count($additionalIDs)) { |
| 2431 | $template->assign('isPrimary', 0); |
| 2432 | $template->assign('customProfile', NULL); |
| 2433 | //set additionalParticipant true |
| 2434 | $values['params']['additionalParticipant'] = TRUE; |
| 2435 | foreach ($additionalIDs as $pId => $cId) { |
| 2436 | $amount = array(); |
| 2437 | //to change the status pending to completed |
| 2438 | $additional = new CRM_Event_DAO_Participant(); |
| 2439 | $additional->id = $pId; |
| 2440 | $additional->contact_id = $cId; |
| 2441 | $additional->find(TRUE); |
| 2442 | $additional->register_date = $this->_relatedObjects['participant']->register_date; |
| 2443 | $additional->status_id = 1; |
| 2444 | $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id'); |
| 2445 | //if additional participant dont have email |
| 2446 | //use display name. |
| 2447 | if (!$additionalParticipantInfo) { |
| 2448 | $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id); |
| 2449 | } |
| 2450 | $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount); |
| 2451 | $primaryAmount[] = array('label' => $additional->fee_level . ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount); |
| 2452 | $additional->save(); |
| 2453 | $additional->free(); |
| 2454 | $template->assign('amount', $amount); |
| 2455 | CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText); |
| 2456 | } |
| 2457 | } |
| 2458 | |
| 2459 | //build an array of custom profile and assigning it to template |
| 2460 | $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest); |
| 2461 | |
| 2462 | if (count($customProfile)) { |
| 2463 | $template->assign('customProfile', $customProfile); |
| 2464 | } |
| 2465 | |
| 2466 | // for primary contact |
| 2467 | $values['params']['additionalParticipant'] = FALSE; |
| 2468 | $template->assign('isPrimary', 1); |
| 2469 | $template->assign('amount', $primaryAmount); |
| 2470 | $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date)); |
| 2471 | if ($this->payment_instrument_id) { |
| 2472 | $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); |
| 2473 | $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]); |
| 2474 | } |
| 2475 | // carry paylater, since we did not created billing, |
| 2476 | // so need to pull email from primary location, CRM-4395 |
| 2477 | $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later; |
| 2478 | } |
| 2479 | return $template; |
| 2480 | } |
| 2481 | |
| 2482 | /** |
| 2483 | * Function to check whether payment processor supports |
| 2484 | * cancellation of contribution subscription |
| 2485 | * |
| 2486 | * @param int $contributionId contribution id |
| 2487 | * |
| 2488 | * @param bool $isNotCancelled |
| 2489 | * |
| 2490 | * @return boolean |
| 2491 | * @access public |
| 2492 | * @static |
| 2493 | */ |
| 2494 | static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) { |
| 2495 | $cacheKeyString = "$contributionId"; |
| 2496 | $cacheKeyString .= $isNotCancelled ? '_1' : '_0'; |
| 2497 | |
| 2498 | static $supportsCancel = array(); |
| 2499 | |
| 2500 | if (!array_key_exists($cacheKeyString, $supportsCancel)) { |
| 2501 | $supportsCancel[$cacheKeyString] = FALSE; |
| 2502 | $isCancelled = FALSE; |
| 2503 | |
| 2504 | if ($isNotCancelled) { |
| 2505 | $isCancelled = self::isSubscriptionCancelled($contributionId); |
| 2506 | } |
| 2507 | |
| 2508 | $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj'); |
| 2509 | if (!empty($paymentObject)) { |
| 2510 | $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled; |
| 2511 | } |
| 2512 | } |
| 2513 | return $supportsCancel[$cacheKeyString]; |
| 2514 | } |
| 2515 | |
| 2516 | /** |
| 2517 | * Function to check whether subscription is already cancelled |
| 2518 | * |
| 2519 | * @param int $contributionId contribution id |
| 2520 | * |
| 2521 | * @return string $status contribution status |
| 2522 | * @access public |
| 2523 | * @static |
| 2524 | */ |
| 2525 | static function isSubscriptionCancelled($contributionId) { |
| 2526 | $sql = " |
| 2527 | SELECT cr.contribution_status_id |
| 2528 | FROM civicrm_contribution_recur cr |
| 2529 | LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id ) |
| 2530 | WHERE con.id = %1 LIMIT 1"; |
| 2531 | $params = array(1 => array($contributionId, 'Integer')); |
| 2532 | $statusId = CRM_Core_DAO::singleValueQuery($sql, $params); |
| 2533 | $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId); |
| 2534 | if ($status == 'Cancelled') { |
| 2535 | return TRUE; |
| 2536 | } |
| 2537 | return FALSE; |
| 2538 | } |
| 2539 | |
| 2540 | /** |
| 2541 | * Function to create all financial accounts entry |
| 2542 | * |
| 2543 | * @param array $params contribution object, line item array and params for trxn |
| 2544 | * |
| 2545 | * |
| 2546 | * @param null $financialTrxnVals |
| 2547 | * |
| 2548 | * @return null|object |
| 2549 | * @access public |
| 2550 | * @static |
| 2551 | */ |
| 2552 | static function recordFinancialAccounts(&$params, $financialTrxnVals = NULL) { |
| 2553 | $skipRecords = $update = FALSE; |
| 2554 | // in few scenarios we require the trxn record details which has got created |
| 2555 | $return = NULL; |
| 2556 | $additionalParticipantId = array(); |
| 2557 | $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
| 2558 | |
| 2559 | if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') { |
| 2560 | $entityId = $params['participant_id']; |
| 2561 | $entityTable = 'civicrm_participant'; |
| 2562 | $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId); |
| 2563 | } |
| 2564 | elseif (!empty($params['membership_id'])) { |
| 2565 | //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships |
| 2566 | // are created off one contribution should be handled elsewhere |
| 2567 | $entityId = $params['membership_id']; |
| 2568 | $entityTable = 'civicrm_membership'; |
| 2569 | } |
| 2570 | else { |
| 2571 | $entityId = $params['contribution']->id; |
| 2572 | $entityTable = 'civicrm_contribution'; |
| 2573 | } |
| 2574 | |
| 2575 | $entityID[] = $entityId; |
| 2576 | if (!empty($additionalParticipantId)) { |
| 2577 | $entityID += $additionalParticipantId; |
| 2578 | } |
| 2579 | // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated |
| 2580 | if (empty($params['prevContribution'])) { |
| 2581 | $entityID = NULL; |
| 2582 | } |
| 2583 | else { |
| 2584 | $update = TRUE; |
| 2585 | } |
| 2586 | |
| 2587 | $statusId = $params['contribution']->contribution_status_id; |
| 2588 | // CRM-13964 partial payment |
| 2589 | if (CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses) |
| 2590 | && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) { |
| 2591 | $partialAmtPay = $params['partial_amount_pay']; |
| 2592 | $partialAmtTotal = $params['partial_payment_total']; |
| 2593 | |
| 2594 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); |
| 2595 | $fromFinancialAccountId = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId); |
| 2596 | $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'); |
| 2597 | $params['total_amount'] = $partialAmtPay; |
| 2598 | |
| 2599 | $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($params['contribution']->id, $params['financial_type_id']); |
| 2600 | if (empty($balanceTrxnInfo['trxn_id'])) { |
| 2601 | // create new balance transaction record |
| 2602 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); |
| 2603 | $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId); |
| 2604 | |
| 2605 | $balanceTrxnParams['total_amount'] = $partialAmtTotal; |
| 2606 | $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount; |
| 2607 | $balanceTrxnParams['contribution_id'] = $params['contribution']->id; |
| 2608 | $balanceTrxnParams['trxn_date'] = date('YmdHis'); |
| 2609 | $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params); |
| 2610 | $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('net_amount', $params); |
| 2611 | $balanceTrxnParams['currency'] = $params['contribution']->currency; |
| 2612 | $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id; |
| 2613 | $balanceTrxnParams['status_id'] = $statusId; |
| 2614 | $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id; |
| 2615 | $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params); |
| 2616 | if (!empty($params['payment_processor'])) { |
| 2617 | $balanceTrxnParams['payment_processor_id'] = $params['payment_processor']; |
| 2618 | } |
| 2619 | CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams); |
| 2620 | } |
| 2621 | } |
| 2622 | |
| 2623 | // build line item array if its not set in $params |
| 2624 | if (empty($params['line_item']) || $additionalParticipantId) { |
| 2625 | CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable)); |
| 2626 | } |
| 2627 | |
| 2628 | if (CRM_Utils_Array::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) && |
| 2629 | !(CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later)) { |
| 2630 | $skipRecords = TRUE; |
| 2631 | $pendingStatus = array(array_search('Pending', $contributionStatuses), array_search('In Progress', $contributionStatuses)); |
| 2632 | if (in_array(CRM_Utils_Array::value('contribution_status_id', $params), $pendingStatus)) { |
| 2633 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); |
| 2634 | $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId); |
| 2635 | } |
| 2636 | elseif (!empty($params['payment_processor'])) { |
| 2637 | $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id'); |
| 2638 | } |
| 2639 | elseif (!empty($params['payment_instrument_id'])) { |
| 2640 | $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']); |
| 2641 | } |
| 2642 | else { |
| 2643 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' ")); |
| 2644 | $queryParams = array(1 => array($relationTypeId, 'Integer')); |
| 2645 | $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); |
| 2646 | } |
| 2647 | |
| 2648 | $totalAmount = CRM_Utils_Array::value('total_amount', $params); |
| 2649 | if (!isset($totalAmount) && !empty($params['prevContribution'])) { |
| 2650 | $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount; |
| 2651 | } |
| 2652 | |
| 2653 | //build financial transaction params |
| 2654 | $trxnParams = array( |
| 2655 | 'contribution_id' => $params['contribution']->id, |
| 2656 | 'to_financial_account_id' => $params['to_financial_account_id'], |
| 2657 | 'trxn_date' => date('YmdHis'), |
| 2658 | 'total_amount' => $totalAmount, |
| 2659 | 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params), |
| 2660 | 'net_amount' => CRM_Utils_Array::value('net_amount', $params), |
| 2661 | 'currency' => $params['contribution']->currency, |
| 2662 | 'trxn_id' => $params['contribution']->trxn_id, |
| 2663 | 'status_id' => $statusId, |
| 2664 | 'payment_instrument_id' => $params['contribution']->payment_instrument_id, |
| 2665 | 'check_number' => CRM_Utils_Array::value('check_number', $params), |
| 2666 | ); |
| 2667 | |
| 2668 | if (!empty($params['payment_processor'])) { |
| 2669 | $trxnParams['payment_processor_id'] = $params['payment_processor']; |
| 2670 | } |
| 2671 | |
| 2672 | if (isset($fromFinancialAccountId)) { |
| 2673 | $trxnParams['from_financial_account_id'] = $fromFinancialAccountId; |
| 2674 | } |
| 2675 | |
| 2676 | // consider external values passed for recording transaction entry |
| 2677 | if (!empty($financialTrxnVals)) { |
| 2678 | $trxnParams = array_merge($trxnParams, $financialTrxnVals); |
| 2679 | } |
| 2680 | |
| 2681 | $params['trxnParams'] = $trxnParams; |
| 2682 | |
| 2683 | if (!empty($params['prevContribution'])) { |
| 2684 | $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount; |
| 2685 | $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount; |
| 2686 | $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount; |
| 2687 | $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id; |
| 2688 | $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id; |
| 2689 | $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id; |
| 2690 | $params['trxnParams']['check_number'] = $params['prevContribution']->check_number; |
| 2691 | |
| 2692 | //if financial type is changed |
| 2693 | if (!empty($params['financial_type_id']) && |
| 2694 | $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id) { |
| 2695 | $incomeTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' ")); |
| 2696 | $oldFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $incomeTypeId); |
| 2697 | $newFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $incomeTypeId); |
| 2698 | if ($oldFinancialAccount != $newFinancialAccount) { |
| 2699 | $params['total_amount'] = 0; |
| 2700 | if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) { |
| 2701 | $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType( |
| 2702 | $params['prevContribution']->financial_type_id, $relationTypeId); |
| 2703 | } |
| 2704 | else { |
| 2705 | $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC'); |
| 2706 | if (!empty($lastFinancialTrxnId['financialTrxnId'])) { |
| 2707 | $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id'); |
| 2708 | } |
| 2709 | } |
| 2710 | self::updateFinancialAccounts($params, 'changeFinancialType'); |
| 2711 | /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */ |
| 2712 | $params['financial_account_id'] = $newFinancialAccount; |
| 2713 | $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; |
| 2714 | self::updateFinancialAccounts($params); |
| 2715 | $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; |
| 2716 | } |
| 2717 | } |
| 2718 | |
| 2719 | //Update contribution status |
| 2720 | $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id; |
| 2721 | if (!empty($params['contribution_status_id']) && |
| 2722 | $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id) { |
| 2723 | //Update Financial Records |
| 2724 | self::updateFinancialAccounts($params, 'changedStatus'); |
| 2725 | } |
| 2726 | |
| 2727 | // change Payment Instrument for a Completed contribution |
| 2728 | // first handle special case when contribution is changed from Pending to Completed status when initial payment |
| 2729 | // instrument is null and now new payment instrument is added along with the payment |
| 2730 | $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id; |
| 2731 | $params['trxnParams']['check_number'] = CRM_Utils_Array::value('check_number', $params); |
| 2732 | if (array_key_exists('payment_instrument_id', $params)) { |
| 2733 | $params['trxnParams']['total_amount'] = - $trxnParams['total_amount']; |
| 2734 | if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) && |
| 2735 | !CRM_Utils_System::isNull($params['contribution']->payment_instrument_id)) { |
| 2736 | //check if status is changed from Pending to Completed |
| 2737 | // do not update payment instrument changes for Pending to Completed |
| 2738 | if (!($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses) && |
| 2739 | in_array($params['prevContribution']->contribution_status_id, $pendingStatus))) { |
| 2740 | // for all other statuses create new financial records |
| 2741 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); |
| 2742 | $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; |
| 2743 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); |
| 2744 | } |
| 2745 | } |
| 2746 | else if ((!CRM_Utils_System::isNull($params['contribution']->payment_instrument_id) || |
| 2747 | !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) && |
| 2748 | $params['contribution']->payment_instrument_id != $params['prevContribution']->payment_instrument_id) { |
| 2749 | // for any other payment instrument changes create new financial records |
| 2750 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); |
| 2751 | $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; |
| 2752 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); |
| 2753 | } |
| 2754 | else if (!CRM_Utils_System::isNull($params['contribution']->check_number) && |
| 2755 | $params['contribution']->check_number != $params['prevContribution']->check_number) { |
| 2756 | // another special case when check number is changed, create new financial records |
| 2757 | // create financial trxn with negative amount |
| 2758 | $params['trxnParams']['check_number'] = $params['prevContribution']->check_number; |
| 2759 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); |
| 2760 | // create financial trxn with positive amount |
| 2761 | $params['trxnParams']['check_number'] = $params['contribution']->check_number; |
| 2762 | $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; |
| 2763 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); |
| 2764 | } |
| 2765 | } |
| 2766 | |
| 2767 | //if Change contribution amount |
| 2768 | $params['trxnParams']['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params); |
| 2769 | $params['trxnParams']['net_amount'] = CRM_Utils_Array::value('net_amount', $params); |
| 2770 | $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount; |
| 2771 | $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id; |
| 2772 | if (isset($totalAmount) && |
| 2773 | $totalAmount != $params['prevContribution']->total_amount) { |
| 2774 | //Update Financial Records |
| 2775 | $params['trxnParams']['from_financial_account_id'] = NULL; |
| 2776 | self::updateFinancialAccounts($params, 'changedAmount'); |
| 2777 | } |
| 2778 | } |
| 2779 | |
| 2780 | if (!$update) { |
| 2781 | // records finanical trxn and entity financial trxn |
| 2782 | // also make it available as return value |
| 2783 | $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams); |
| 2784 | $params['entity_id'] = $financialTxn->id; |
| 2785 | } |
| 2786 | } |
| 2787 | // record line items and finacial items |
| 2788 | if (empty($params['skipLineItem'])) { |
| 2789 | CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $update); |
| 2790 | } |
| 2791 | |
| 2792 | // create batch entry if batch_id is passed |
| 2793 | if (!empty($params['batch_id'])) { |
| 2794 | $entityParams = array( |
| 2795 | 'batch_id' => $params['batch_id'], |
| 2796 | 'entity_table' => 'civicrm_financial_trxn', |
| 2797 | 'entity_id' => $financialTxn->id, |
| 2798 | ); |
| 2799 | CRM_Batch_BAO_Batch::addBatchEntity($entityParams); |
| 2800 | } |
| 2801 | |
| 2802 | // when a fee is charged |
| 2803 | if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) { |
| 2804 | CRM_Core_BAO_FinancialTrxn::recordFees($params); |
| 2805 | } |
| 2806 | |
| 2807 | if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant' |
| 2808 | && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id) { |
| 2809 | $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id'); |
| 2810 | $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level); |
| 2811 | CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel); |
| 2812 | } |
| 2813 | unset($params['line_item']); |
| 2814 | |
| 2815 | return $return; |
| 2816 | } |
| 2817 | |
| 2818 | /** |
| 2819 | * Function to update all financial accounts entry |
| 2820 | * |
| 2821 | * @param array $params contribution object, line item array and params for trxn |
| 2822 | * |
| 2823 | * @param string $context update scenarios |
| 2824 | * |
| 2825 | * @param null $skipTrxn |
| 2826 | * |
| 2827 | * @access public |
| 2828 | * @static |
| 2829 | */ |
| 2830 | static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) { |
| 2831 | $itemAmount = $trxnID = NULL; |
| 2832 | //get all the statuses |
| 2833 | $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
| 2834 | if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus) |
| 2835 | || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus)) |
| 2836 | && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus) |
| 2837 | && $context == 'changePaymentInstrument') { |
| 2838 | return; |
| 2839 | } |
| 2840 | if ($context == 'changedAmount' || $context == 'changeFinancialType') { |
| 2841 | $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount; |
| 2842 | } |
| 2843 | if ($context == 'changedStatus') { |
| 2844 | //get all the statuses |
| 2845 | $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
| 2846 | |
| 2847 | if ($params['prevContribution']->contribution_status_id == array_search('Completed', $contributionStatus) |
| 2848 | && ($params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus) |
| 2849 | || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus))) { |
| 2850 | $params['trxnParams']['total_amount'] = - $params['total_amount']; |
| 2851 | } |
| 2852 | elseif (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus) |
| 2853 | && $params['prevContribution']->is_pay_later) || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus)) { |
| 2854 | $financialTypeID = CRM_Utils_Array::value('financial_type_id', $params) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id; |
| 2855 | if ($params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) { |
| 2856 | $params['trxnParams']['to_financial_account_id'] = NULL; |
| 2857 | $params['trxnParams']['total_amount'] = - $params['total_amount']; |
| 2858 | } |
| 2859 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); |
| 2860 | $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType( |
| 2861 | $financialTypeID, $relationTypeId); |
| 2862 | } |
| 2863 | $itemAmount = $params['trxnParams']['total_amount']; |
| 2864 | } |
| 2865 | elseif ($context == 'changePaymentInstrument') { |
| 2866 | if ($params['trxnParams']['total_amount'] < 0) { |
| 2867 | $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC'); |
| 2868 | if (!empty($lastFinancialTrxnId['financialTrxnId'])) { |
| 2869 | $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id'); |
| 2870 | $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id; |
| 2871 | } |
| 2872 | } |
| 2873 | else { |
| 2874 | $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id']; |
| 2875 | $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id; |
| 2876 | } |
| 2877 | } |
| 2878 | $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']); |
| 2879 | $params['entity_id'] = $trxn->id; |
| 2880 | |
| 2881 | if ($context == 'changedStatus') { |
| 2882 | if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus) |
| 2883 | || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus)) |
| 2884 | && ($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus))) { |
| 2885 | $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'"; |
| 2886 | $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'"; |
| 2887 | |
| 2888 | $entityParams = array( |
| 2889 | 'entity_table' => 'civicrm_financial_item', |
| 2890 | 'financial_trxn_id' => $trxn->id, |
| 2891 | ); |
| 2892 | foreach ($params['line_item'] as $fieldId => $fields) { |
| 2893 | foreach ($fields as $fieldValueId => $fieldValues) { |
| 2894 | $fparams = array( |
| 2895 | 1 => array(CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'), 'Integer'), |
| 2896 | 2 => array($fieldValues['id'], 'Integer'), |
| 2897 | ); |
| 2898 | CRM_Core_DAO::executeQuery($query, $fparams); |
| 2899 | $fparams = array( |
| 2900 | 1 => array($fieldValues['id'], 'Integer'), |
| 2901 | ); |
| 2902 | $financialItem = CRM_Core_DAO::executeQuery($sql, $fparams); |
| 2903 | while ($financialItem->fetch()) { |
| 2904 | $entityParams['entity_id'] = $financialItem->id; |
| 2905 | $entityParams['amount'] = $financialItem->amount; |
| 2906 | CRM_Financial_BAO_FinancialItem::createEntityTrxn($entityParams); |
| 2907 | } |
| 2908 | } |
| 2909 | } |
| 2910 | return; |
| 2911 | } |
| 2912 | } |
| 2913 | if ($context != 'changePaymentInstrument') { |
| 2914 | $itemParams['entity_table'] = 'civicrm_line_item'; |
| 2915 | $trxnIds['id'] = $params['entity_id']; |
| 2916 | foreach ($params['line_item'] as $fieldId => $fields) { |
| 2917 | foreach ($fields as $fieldValueId => $fieldValues) { |
| 2918 | $prevParams['entity_id'] = $fieldValues['id']; |
| 2919 | $prevfinancialItem = CRM_Financial_BAO_FinancialItem::retrieve($prevParams, CRM_Core_DAO::$_nullArray); |
| 2920 | |
| 2921 | $receiveDate = CRM_Utils_Date::isoToMysql($params['prevContribution']->receive_date); |
| 2922 | if ($params['contribution']->receive_date) { |
| 2923 | $receiveDate = CRM_Utils_Date::isoToMysql($params['contribution']->receive_date); |
| 2924 | } |
| 2925 | |
| 2926 | $financialAccount = $prevfinancialItem->financial_account_id; |
| 2927 | if (!empty($params['financial_account_id'])) { |
| 2928 | $financialAccount = $params['financial_account_id']; |
| 2929 | } |
| 2930 | |
| 2931 | $currency = $params['prevContribution']->currency; |
| 2932 | if ($params['contribution']->currency) { |
| 2933 | $currency = $params['contribution']->currency; |
| 2934 | } |
| 2935 | if (!empty($params['is_quick_config'])) { |
| 2936 | $amount = $itemAmount; |
| 2937 | if (!$amount) { |
| 2938 | $amount = $params['total_amount']; |
| 2939 | } |
| 2940 | } |
| 2941 | else { |
| 2942 | $diff = 1; |
| 2943 | if ($context == 'changeFinancialType' || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus) |
| 2944 | || $params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus)) { |
| 2945 | $diff = -1; |
| 2946 | } |
| 2947 | $amount = $diff * $fieldValues['line_total']; |
| 2948 | } |
| 2949 | |
| 2950 | $itemParams = array( |
| 2951 | 'transaction_date' => $receiveDate, |
| 2952 | 'contact_id' => $params['prevContribution']->contact_id, |
| 2953 | 'currency' => $currency, |
| 2954 | 'amount' => $amount, |
| 2955 | 'description' => $prevfinancialItem->description, |
| 2956 | 'status_id' => $prevfinancialItem->status_id, |
| 2957 | 'financial_account_id' => $financialAccount, |
| 2958 | 'entity_table' => 'civicrm_line_item', |
| 2959 | 'entity_id' => $fieldValues['id'] |
| 2960 | ); |
| 2961 | CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds); |
| 2962 | } |
| 2963 | } |
| 2964 | } |
| 2965 | } |
| 2966 | |
| 2967 | /** |
| 2968 | * Function to check status validation on update of a contribution |
| 2969 | * |
| 2970 | * @param array $values previous form values before submit |
| 2971 | * |
| 2972 | * @param array $fields the input form values |
| 2973 | * |
| 2974 | * @param array $errors list of errors |
| 2975 | * |
| 2976 | * @return bool |
| 2977 | * @access public |
| 2978 | * @static |
| 2979 | */ |
| 2980 | static function checkStatusValidation($values, &$fields, &$errors) { |
| 2981 | if (CRM_Utils_System::isNull($values) && !empty($fields['id'])) { |
| 2982 | $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id'); |
| 2983 | if ($values['contribution_status_id'] == $fields['contribution_status_id']) { |
| 2984 | return FALSE; |
| 2985 | } |
| 2986 | } |
| 2987 | $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
| 2988 | $checkStatus = array( |
| 2989 | 'Cancelled' => array('Completed', 'Refunded'), |
| 2990 | 'Completed' => array('Cancelled', 'Refunded'), |
| 2991 | 'Pending' => array('Cancelled', 'Completed', 'Failed'), |
| 2992 | 'In Progress' => array('Cancelled', 'Completed', 'Failed'), |
| 2993 | 'Refunded' => array('Cancelled', 'Completed') |
| 2994 | ); |
| 2995 | |
| 2996 | if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) { |
| 2997 | $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(1 => $contributionStatuses[$values['contribution_status_id']], 2 => $contributionStatuses[$fields['contribution_status_id']])); |
| 2998 | } |
| 2999 | } |
| 3000 | |
| 3001 | /** |
| 3002 | * Function to delete contribution of contact |
| 3003 | * |
| 3004 | * CRM-12155 |
| 3005 | * |
| 3006 | * @param integer $contactId contact id |
| 3007 | * |
| 3008 | * @access public |
| 3009 | * @static |
| 3010 | */ |
| 3011 | static function deleteContactContribution($contactId) { |
| 3012 | $contribution = new CRM_Contribute_DAO_Contribution(); |
| 3013 | $contribution->contact_id = $contactId; |
| 3014 | $contribution->find(); |
| 3015 | while ($contribution->fetch()) { |
| 3016 | self::deleteContribution($contribution->id); |
| 3017 | } |
| 3018 | } |
| 3019 | |
| 3020 | /** |
| 3021 | * Get options for a given contribution field. |
| 3022 | * @see CRM_Core_DAO::buildOptions |
| 3023 | * |
| 3024 | * @param String $fieldName |
| 3025 | * @param String $context : @see CRM_Core_DAO::buildOptionsContext |
| 3026 | * @param Array $props : whatever is known about this dao object |
| 3027 | * |
| 3028 | * @return Array|bool |
| 3029 | */ |
| 3030 | public static function buildOptions($fieldName, $context = NULL, $props = array()) { |
| 3031 | $className = __CLASS__; |
| 3032 | $params = array(); |
| 3033 | switch ($fieldName) { |
| 3034 | // This field is not part of this object but the api supports it |
| 3035 | case 'payment_processor': |
| 3036 | $className = 'CRM_Contribute_BAO_ContributionPage'; |
| 3037 | // Filter results by contribution page |
| 3038 | if (!empty($props['contribution_page_id'])) { |
| 3039 | $page = civicrm_api('contribution_page', 'getsingle', array( |
| 3040 | 'version' => 3, |
| 3041 | 'id' => ($props['contribution_page_id']) |
| 3042 | )); |
| 3043 | $types = (array) CRM_Utils_Array::value('payment_processor', $page, 0); |
| 3044 | $params['condition'] = 'id IN (' . implode(',', $types) . ')'; |
| 3045 | } |
| 3046 | } |
| 3047 | return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context); |
| 3048 | } |
| 3049 | |
| 3050 | /** |
| 3051 | * Function to validate financial type |
| 3052 | * |
| 3053 | * CRM-13231 |
| 3054 | * |
| 3055 | * @param integer $financialTypeId Financial Type id |
| 3056 | * |
| 3057 | * @param string $relationName |
| 3058 | * |
| 3059 | * @return array|bool |
| 3060 | * @access public |
| 3061 | * @static |
| 3062 | */ |
| 3063 | static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') { |
| 3064 | $expenseTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' ")); |
| 3065 | $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $expenseTypeId); |
| 3066 | |
| 3067 | if (!$financialAccount) { |
| 3068 | return CRM_Contribute_PseudoConstant::financialType($financialTypeId); |
| 3069 | } |
| 3070 | return FALSE; |
| 3071 | } |
| 3072 | |
| 3073 | |
| 3074 | /* |
| 3075 | * Function to record additional payment for partial and refund contributions |
| 3076 | * |
| 3077 | * @param integer $contributionId : is the invoice contribution id (got created after processing participant payment) |
| 3078 | * @param array $trxnData : to take user provided input of transaction details. |
| 3079 | * @param string $paymentType 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments |
| 3080 | */ |
| 3081 | /** |
| 3082 | * @param $contributionId |
| 3083 | * @param $trxnsData |
| 3084 | * @param string $paymentType |
| 3085 | * @param null $participantId |
| 3086 | * |
| 3087 | * @return null|object |
| 3088 | */ |
| 3089 | static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) { |
| 3090 | $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'); |
| 3091 | $getInfoOf['id'] = $contributionId; |
| 3092 | $defaults = array(); |
| 3093 | $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray); |
| 3094 | |
| 3095 | if ($paymentType == 'owed') { |
| 3096 | // build params for recording financial trxn entry |
| 3097 | $params['contribution'] = $contributionDAO; |
| 3098 | $params = array_merge($defaults, $params); |
| 3099 | $params['skipLineItem'] = TRUE; |
| 3100 | $params['partial_payment_total'] = $contributionDAO->total_amount; |
| 3101 | $params['partial_amount_pay'] = $trxnsData['total_amount']; |
| 3102 | $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis'); |
| 3103 | |
| 3104 | // record the entry |
| 3105 | $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData); |
| 3106 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); |
| 3107 | $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId); |
| 3108 | |
| 3109 | $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id); |
| 3110 | $trxnId = $trxnId['trxn_id']; |
| 3111 | |
| 3112 | // update statuses |
| 3113 | // criteria for updates contribution total_amount == financial_trxns of partial_payments |
| 3114 | $sql = "SELECT SUM(ft.total_amount) as sum_of_payments |
| 3115 | FROM civicrm_financial_trxn ft |
| 3116 | LEFT JOIN civicrm_entity_financial_trxn eft |
| 3117 | ON (ft.id = eft.financial_trxn_id) |
| 3118 | WHERE eft.entity_table = 'civicrm_contribution' |
| 3119 | AND eft.entity_id = {$contributionId} |
| 3120 | AND ft.to_financial_account_id != {$toFinancialAccount} |
| 3121 | AND ft.status_id = {$statusId} |
| 3122 | "; |
| 3123 | $sumOfPayments = CRM_Core_DAO::singleValueQuery($sql); |
| 3124 | |
| 3125 | // update statuses |
| 3126 | if ($contributionDAO->total_amount == $sumOfPayments) { |
| 3127 | // update contribution status |
| 3128 | $contributionUpdate['id'] = $contributionId; |
| 3129 | $contributionUpdate['contribution_status_id'] = $statusId; |
| 3130 | $contributionUpdate['skipLineItem'] = TRUE; |
| 3131 | // note : not using the self::add method, |
| 3132 | // the reason because it performs 'status change' related code execution for financial records |
| 3133 | // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates |
| 3134 | // are coded below i.e. just updating financial_item status to 'Paid' |
| 3135 | $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId); |
| 3136 | |
| 3137 | if ($participantId) { |
| 3138 | // update participant status |
| 3139 | $participantStatuses = CRM_Event_PseudoConstant::participantStatus(); |
| 3140 | $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId); |
| 3141 | foreach ($ids as $val) { |
| 3142 | $participantUpdate['id'] = $val; |
| 3143 | $participantUpdate['status_id'] = array_search('Registered', $participantStatuses); |
| 3144 | CRM_Event_BAO_Participant::add($participantUpdate); |
| 3145 | } |
| 3146 | } |
| 3147 | |
| 3148 | // update financial item statuses |
| 3149 | $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id'); |
| 3150 | $paidStatus = array_search('Paid', $financialItemStatus); |
| 3151 | |
| 3152 | $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId); |
| 3153 | $sqlFinancialItemUpdate = " |
| 3154 | UPDATE civicrm_financial_item fi |
| 3155 | LEFT JOIN civicrm_entity_financial_trxn eft |
| 3156 | ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item') |
| 3157 | SET status_id = {$paidStatus} |
| 3158 | WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']}) |
| 3159 | "; |
| 3160 | CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate); |
| 3161 | } |
| 3162 | } |
| 3163 | elseif ($paymentType == 'refund') { |
| 3164 | // build params for recording financial trxn entry |
| 3165 | $params['contribution'] = $contributionDAO; |
| 3166 | $params = array_merge($defaults, $params); |
| 3167 | $params['skipLineItem'] = TRUE; |
| 3168 | $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis'); |
| 3169 | $trxnsData['total_amount'] = - $trxnsData['total_amount']; |
| 3170 | |
| 3171 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); |
| 3172 | $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId); |
| 3173 | $trxnsData['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name'); |
| 3174 | // record the entry |
| 3175 | $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData); |
| 3176 | |
| 3177 | // note : not using the self::add method, |
| 3178 | // the reason because it performs 'status change' related code execution for financial records |
| 3179 | // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates |
| 3180 | // are coded below i.e. just updating financial_item status to 'Paid' |
| 3181 | $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId); |
| 3182 | |
| 3183 | // add financial item entry |
| 3184 | $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id'); |
| 3185 | $getLine['entity_id'] = $contributionDAO->id; |
| 3186 | $getLine['entity_table'] = 'civicrm_contribution'; |
| 3187 | $lineItemId = CRM_Price_BAO_LineItem::retrieve($getLine, CRM_Core_DAO::$_nullArray); |
| 3188 | if (!empty($lineItemId->id)) { |
| 3189 | $addFinancialEntry = array( |
| 3190 | 'transaction_date' => $financialTrxn->trxn_date, |
| 3191 | 'contact_id' => $contributionDAO->contact_id, |
| 3192 | 'amount' => $financialTrxn->total_amount, |
| 3193 | 'status_id' => array_search('Paid', $financialItemStatus), |
| 3194 | 'entity_id' => $lineItemId->id, |
| 3195 | 'entity_table' => 'civicrm_line_item' |
| 3196 | ); |
| 3197 | $trxnIds['id'] = $financialTrxn->id; |
| 3198 | CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds); |
| 3199 | } |
| 3200 | if ($participantId) { |
| 3201 | // update participant status |
| 3202 | $participantStatuses = CRM_Event_PseudoConstant::participantStatus(); |
| 3203 | $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId); |
| 3204 | foreach ($ids as $val) { |
| 3205 | $participantUpdate['id'] = $val; |
| 3206 | $participantUpdate['status_id'] = array_search('Registered', $participantStatuses); |
| 3207 | CRM_Event_BAO_Participant::add($participantUpdate); |
| 3208 | } |
| 3209 | } |
| 3210 | } |
| 3211 | |
| 3212 | // activity creation |
| 3213 | if (!empty($financialTrxn)) { |
| 3214 | if ($participantId) { |
| 3215 | $inputParams['id'] = $participantId; |
| 3216 | $values = array(); |
| 3217 | $ids = array(); |
| 3218 | $component = 'event'; |
| 3219 | $entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids); |
| 3220 | $entityObj = $entityObj[$participantId]; |
| 3221 | } |
| 3222 | $activityType = ($paymentType == 'refund') ? 'Refund' : 'Payment'; |
| 3223 | |
| 3224 | self::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId); |
| 3225 | } |
| 3226 | return $financialTrxn; |
| 3227 | } |
| 3228 | |
| 3229 | /** |
| 3230 | * @param $entityObj |
| 3231 | * @param $trxnObj |
| 3232 | * @param $activityType |
| 3233 | * @param $component |
| 3234 | * @param $contributionId |
| 3235 | * |
| 3236 | * @throws CRM_Core_Exception |
| 3237 | */ |
| 3238 | static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) { |
| 3239 | if ($component == 'event') { |
| 3240 | $date = CRM_Utils_Date::isoToMysql($trxnObj->trxn_date); |
| 3241 | $paymentAmount = CRM_Utils_Money::format($trxnObj->total_amount, $trxnObj->currency); |
| 3242 | $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id, 'title'); |
| 3243 | $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}"; |
| 3244 | $targetCid = $entityObj->contact_id; |
| 3245 | // source record id would be the contribution id |
| 3246 | $srcRecId = $contributionId; |
| 3247 | } |
| 3248 | |
| 3249 | // activity params |
| 3250 | $activityParams = array( |
| 3251 | 'source_contact_id' => $targetCid, |
| 3252 | 'source_record_id' => $srcRecId, |
| 3253 | 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', |
| 3254 | $activityType, |
| 3255 | 'name' |
| 3256 | ), |
| 3257 | 'subject' => $subject, |
| 3258 | 'activity_date_time' => $date, |
| 3259 | 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', |
| 3260 | 'Completed', |
| 3261 | 'name' |
| 3262 | ), |
| 3263 | 'skipRecentView' => TRUE, |
| 3264 | ); |
| 3265 | |
| 3266 | // create activity with target contacts |
| 3267 | $session = CRM_Core_Session::singleton(); |
| 3268 | $id = $session->get('userID'); |
| 3269 | if ($id) { |
| 3270 | $activityParams['source_contact_id'] = $id; |
| 3271 | $activityParams['target_contact_id'][] = $targetCid; |
| 3272 | } |
| 3273 | CRM_Activity_BAO_Activity::create($activityParams); |
| 3274 | } |
| 3275 | |
| 3276 | /** |
| 3277 | * @param $id |
| 3278 | * @param $component |
| 3279 | * @param bool $getTrxnInfo |
| 3280 | * @param bool $usingLineTotal |
| 3281 | * |
| 3282 | * @return mixed |
| 3283 | */ |
| 3284 | static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) { |
| 3285 | if ($component == 'event') { |
| 3286 | $entity = 'participant'; |
| 3287 | $entityTable = 'civicrm_participant'; |
| 3288 | $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id'); |
| 3289 | |
| 3290 | if (!$contributionId) { |
| 3291 | if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) { |
| 3292 | $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id'); |
| 3293 | $id = $primaryParticipantId; |
| 3294 | } |
| 3295 | } |
| 3296 | } |
| 3297 | $total = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId); |
| 3298 | $baseTrxnId = !empty($total['trxn_id']) ? $total['trxn_id'] : NULL; |
| 3299 | $isBalance = NULL; |
| 3300 | if ($baseTrxnId) { |
| 3301 | $isBalance = TRUE; |
| 3302 | } |
| 3303 | else { |
| 3304 | $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId); |
| 3305 | $baseTrxnId = $baseTrxnId['financialTrxnId']; |
| 3306 | $isBalance = FALSE; |
| 3307 | } |
| 3308 | if (empty($total) || $usingLineTotal) { |
| 3309 | // for additional participants |
| 3310 | if ($entityTable == 'civicrm_participant') { |
| 3311 | $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId); |
| 3312 | $total = 0; |
| 3313 | foreach ($ids as $val) { |
| 3314 | $total += CRM_Price_BAO_LineItem::getLineTotal($val, $entityTable); |
| 3315 | } |
| 3316 | } |
| 3317 | else { |
| 3318 | $total = CRM_Price_BAO_LineItem::getLineTotal($id, $entityTable); |
| 3319 | } |
| 3320 | } |
| 3321 | else { |
| 3322 | $baseTrxnId = $total['trxn_id']; |
| 3323 | $total = $total['total_amount']; |
| 3324 | } |
| 3325 | |
| 3326 | $paymentBalance = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($id, $entity, FALSE, $total); |
| 3327 | $contributionIsPayLater = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later'); |
| 3328 | if ($paymentBalance == 0 && $contributionIsPayLater) { |
| 3329 | $paymentBalance = $total; |
| 3330 | } |
| 3331 | |
| 3332 | $info['total'] = $total; |
| 3333 | $info['paid'] = $total - $paymentBalance; |
| 3334 | $info['balance'] = $paymentBalance; |
| 3335 | $info['id'] = $id; |
| 3336 | $info['component'] = $component; |
| 3337 | $info['payLater'] = $contributionIsPayLater; |
| 3338 | $rows = array(); |
| 3339 | if ($getTrxnInfo && $baseTrxnId) { |
| 3340 | $sql = " |
| 3341 | SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number |
| 3342 | FROM civicrm_contribution con |
| 3343 | LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution') |
| 3344 | LEFT JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id |
| 3345 | WHERE con.id = {$contributionId} |
| 3346 | "; |
| 3347 | |
| 3348 | // conditioned WHERE clause |
| 3349 | if ($isBalance) { |
| 3350 | // if balance trxn exists don't include details of it in transaction info |
| 3351 | $sql .= " AND ft.id != {$baseTrxnId} "; |
| 3352 | } |
| 3353 | $resultDAO = CRM_Core_DAO::executeQuery($sql); |
| 3354 | |
| 3355 | $statuses = CRM_Contribute_PseudoConstant::contributionStatus(); |
| 3356 | $financialTypes = CRM_Contribute_PseudoConstant::financialType(); |
| 3357 | while($resultDAO->fetch()) { |
| 3358 | $paidByLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id); |
| 3359 | $paidByName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id); |
| 3360 | $val = array( |
| 3361 | 'total_amount' => $resultDAO->total_amount, |
| 3362 | 'financial_type' => $financialTypes[$resultDAO->financial_type_id], |
| 3363 | 'payment_instrument' => $paidByLabel, |
| 3364 | 'receive_date' => $resultDAO->trxn_date, |
| 3365 | 'trxn_id' => $resultDAO->trxn_id, |
| 3366 | 'status' => $statuses[$resultDAO->status_id], |
| 3367 | ); |
| 3368 | if ($paidByName == 'Check') { |
| 3369 | $val['check_number'] = $resultDAO->check_number; |
| 3370 | } |
| 3371 | $rows[] = $val; |
| 3372 | } |
| 3373 | $info['transaction'] = $rows; |
| 3374 | } |
| 3375 | return $info; |
| 3376 | } |
| 3377 | } |