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