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