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