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