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